<?php

namespace App\Modules\Tour\Application;

class TourDaysGeneratorWithDay
{

    public function __construct()
    {
    }

    public function __invoke($daysInMonth, string $yearMonthStr, $oTour, $availableDays, $locks, $duration)
    {
        $arr = self::generateArrayFromDays($daysInMonth);
        $datesOfMonth = self::getDateStringOfMonth($arr, $yearMonthStr);

        $oData = array();

        $paxFree = $oTour[0]->Tour_Availability;
        foreach ($datesOfMonth as $k => $day) {
            $lock = 0;
                $paxFree = $oTour[0]->Tour_Availability;
                $paxAmount = 0;

                for ($j = 0; $j < count($availableDays); $j++) {
                    if ($availableDays[$j]->BookingTour_DateStart == $day) {
                        $paxFree = $paxFree - $availableDays[$j]->pax;
                        $paxAmount += $availableDays[$j]->pax;
                    }
                }

                foreach ($locks as $tourLock) {
                    if (self::betweenDates($day, $tourLock->TourLock_DateStart, $tourLock->TourLock_DateEnd)) {
                        $lock = 1;
                    }
                }
            
            if ($oTour[0]->Tour_AvailabilityStatus == 1) {
                $paxFree = -1;
            }
            if ($this->getAnticipation($oTour[0], $duration, $day)) {
                $lock = 1;
                
            }
            $oData[$k] = [
                "date"              => $day,
                "paxFree"           => $paxFree,
                'paxAmount'         => $paxAmount,
                'paxMin'            => $oTour[0]->Tour_MinPax,
                'lock'              => $lock
            ];
        }
        return $oData;
    }

    public function getAnticipation($tour, $duration, $date)
    {
        
        $anticipationFactor = 1;
        if ($tour->Tour_AnticipationType == 2) {
            $anticipationFactor = 24;
        } else if ($tour->Tour_AnticipationType == 3) {
            $anticipationFactor = 720;
        }

        $anticipation = $tour->Tour_Anticipation * $anticipationFactor;
        $currentTime = time() + ($anticipation - $duration * 24 - 5) * 3600;
        $currentDate = strtotime($date);
        return $currentTime > $currentDate;
    }

    public static function betweenDates($date1, $date2, $date3)
    {
        $time = strtotime($date1);
        return $time >= strtotime($date2) && $time <= strtotime($date3);
    }

    public static function generateArrayFromDays(int $days)
    {
        return range(0, $days - 1);
    }

    public static function getDateStringOfMonth(array $days, string $yearMonthStr)
    {
        return array_map(fn ($val) => date("Y-m-d", strtotime($yearMonthStr . ($val + 1))), $days);
    }
}
