<?php

namespace App\Modules\Package\Application;

use App\Modules\Tour\Application\TourDaysGenerator;
use Illuminate\Support\Facades\DB;

class PackageTourDaysGetter
{

    public function __construct()
    {
    }

    public function __invoke($year, $month, $tours)
    {
        foreach ($tours as $t) {
            $t->duration = $t->Tour_Duration;
        }
        $data = array_map(fn($tour) => [
            'IdTour' => $tour->Id_Tour,
            'TourDays' => $this->generateDaysTour($tour, $year, $month)
        ], $tours);
        return $data;
    }

    private function generateDaysTour($tourData, $year, $month)
    {
        
        $yearMonthStr = $year . '-' . $month . '-';
        $daysInMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);

        $oParam = [
            $tourData->Id_Tour,
            $month,
            $year,
            $tourData->duration
        ];
        $availableDays  = DB::select('call sp_client_tour_availability(?,?,?,?)', $oParam);
        $locks  = DB::select('call sp_tour_lock_list(?,?,?,?)', $oParam);
        
        
        $tour = DB::select('call sp_tour_index(?)', [ $tourData->Id_Tour ]);

        return (new TourDaysGenerator())
        ->__invoke(
            $daysInMonth,
            $yearMonthStr,
            $tour,
            $availableDays,
            $locks
        );
    }
}
