<?php

namespace App\Http\Controllers\Owner\Booking;

use App\Http\Controllers\Controller;
use App\Http\Helpers\ParamsValidator;
use Illuminate\Http\Request;
use App\Http\Helpers\ResponseBuilder;
use App\Modules\BookingCalendar\Application\List\ListBookingCalendarQuery;
use App\Modules\BookingCalendar\Application\List\ListBookingCalendarResponse;
use App\Modules\HtlCampSchedule\Application\List\ListHtlCampScheduleQuery;
use App\Modules\HtlCampSchedule\Application\Order\OrderHtlCampScheduleQuery;
use App\Modules\Shared\Domain\Bus\Query\QueryBus;
use App\Modules\Shared\Domain\DataHandlerService;
use App\Modules\Shared\Validator\Infraestructure\LaravelValidator;

class BookingCalendarCategoryController extends Controller
{
    private $oDomain;

    public function __construct(
        private QueryBus $queryBus,
        private DataHandlerService $dataHandlerService
    ) {
        $this->oDomain = "Booking";
    }

    public function __invoke(Request $request)
    {
        (new LaravelValidator())->validate($request->all(), $this->oDomain, [
            'Id_CategoryTour'   => 'required|int',
            'Id_TypeTour'       => 'int',
            'Id_tour'           => 'required|int',
            // 'Id_Package'        => 'required|int',
            'Month'             => 'required|int',
            'Year'              => 'required|int',
            // 'Id_HtlCamp'        => 'required|int'
        ]);

        $dateStart = date('Y-m-d', mktime(0, 0, 0, $request->input('Month'), 1, $request->input('Year')));
        $dateEnd = date('Y-m-d', mktime(0, 0, 0, $request->input('Month') + 1, 0, $request->input('Year')));
        $year = $request->input("Year");
        $month = $request->input("Month");

        /** @var ListBookingCalendarResponse $response */
        $response = $this->queryBus->ask(new ListBookingCalendarQuery(
            $request->get('Id_CategoryTour'),
            $request->get('Id_TypeTour', 0),
            $request->get('Id_tour'),
            $request->get('Id_Package', 0),
            $dateStart,
            $dateEnd,
            $request->header('Token', '')
        ));
        // dd($response);

        $campSchedule = [];
        // if ($request->input('Id_HtlCamp', 0) != 0) {
        //     /** @var HtlCampScheduleResponses $response */
        //     $response = $this->queryBus->ask(new ListHtlCampScheduleQuery($request->input('Id_HtlCamp'), $dateStart . ' 00:00:00', $dateEnd . ' 00:00:00'));
        //     /** @var OrderHtlCampScheduleResponse $orderer */
        //     $orderer = $this->queryBus->ask(new OrderHtlCampScheduleQuery($dateStart . ' 00:00:00', $dateEnd . ' 00:00:00', $response->data()));
        //     $campSchedule = $orderer->response;
        // }

        $oResponse  = array();
        $oValParams     = array(
            'Id_CategoryTour'   => 'required|int',
            'Id_tour'           => 'required|int',
            'Month'             => 'required|int',
            'Year'              => 'required|int'
        );

        $oResponse = ParamsValidator::Validate_Request($request, $oValParams, $this->oDomain);
        if ($oResponse['Response_Code'] !== 200) {
            return ResponseBuilder::Response($oResponse);
        }

        $oData = [(object)[]];

        $calendarTours = $this->simplifyTours($response->response()['Response_Data']);
        $groups = $this->dataHandlerService->groupDataBy($calendarTours, 'Calendar_DateCurrent');
        $daysInMonth = $this->daysInMonth(year: $year, month: $month);


        $days = [];
        $value = 0;

        for ($k = 0; $k < $daysInMonth; $k++) {
            $days[$k] = [];
            $currentDate = $this->dateFrom($year, $month, $k + 1);
            $tours = [];
            $dayPaxAmount = 0;
            if (isset($groups->{$currentDate})) {
                foreach ($groups->{$currentDate} as $tour) {
                    $dayPaxAmount += $tour->Calendar_Amount;
                    $tours[] = [
                        'name' => $tour->Tour_Name,
                        'paxs' => $tour->Calendar_Amount,
                        'color' => $tour->Tour_Color,
                        'value' => $value
                    ];
                }
            }
            $days[$k] = [
                "date"      => $currentDate,
                "pax"       => $dayPaxAmount,
                "tours"     => $tours,
                "tourWPax"  => count($tours)
            ];
        }

        $oData[0]->days = $days;
        $oData[0]->campSchedule = $campSchedule;

        $oResponse["Response_Status"]           = 200;
        $oResponse["Response_Code"]             = 200;
        $oResponse["Response_Domain"]           = $this->oDomain;
        $oResponse["Response_Message"]          = $this->oDomain . " Index ";
        $oResponse["Response_Data"]             = $oData;
        $oResponse["Response_Error_Message"]    = "";
        $oResponse["Response_Error_Reason"]     = "";

        return ResponseBuilder::Response($oResponse);
    }

    private function dateFrom($year, $month, $day)
    {
        return date("Y-m-d", strtotime("$year-$month-$day"));
    }

    private function daysInMonth($year, $month)
    {
        return cal_days_in_month(CAL_GREGORIAN, $month, $year);
    }

    private function simplifyTours($tours)
    {
        return array_map(function ($tour) {
            unset($tour->Package_List);
            unset($tour->Group_List);
            return $tour;
        }, $tours);
    }
}
