<?php

namespace App\Modules\HtlCampSchedule\Domain;

use App\Modules\HtlCamp\Domain\IdHtlCamp;
use App\Modules\Shared\Domain\DateTimeEnd;
use App\Modules\Shared\Domain\DateTimeStart;
use App\Modules\Shared\Domain\Storage\Criteria\StorageCriteria;
use Illuminate\Support\Facades\DB;

class ListHtlCampSchedule implements StorageCriteria
{

    public function __construct(
        private IdHtlCamp $idHtlCamp,
        private DateTimeStart $dateTimeStart,
        private DateTimeEnd $dateTimeEnd
    ) {
    }

    public function run()
    {
        return $this->analize($this->query());
    }

    protected function query()
    {
        $select = HtlCampSchedule::select('`hcs`');
        return DB::select(
            "SELECT $select,
                    CONCAT('[', GROUP_CONCAT(JSON_OBJECT(
                        'Id_HtlCampBooking', `hcb`.`Id_HtlCampBooking`,
                        'HtlCampBooking_Amount', `hcb`.`HtlCampBooking_Amount`,
                        'HtlCampBooking_AmountTotal', `hcb`.`HtlCampBooking_AmountTotal`,
                        'HtlCampBooking_Status', `hcb`.`HtlCampBooking_Status`,
                        'HtlCampBooking_Lock', `hcb`.`HtlCampBooking_Lock`,
                        'Id_BookingTour', `bt`.`Id_BookingTour`,
                        'Id_Tour', `t`.`Id_Tour`,
                        'Tour_Name', `t`.`Tour_Name`,
                        'Tour_Color', `t`.`Tour_Color`
                    ) SEPARATOR ','), ']') AS `HtlCampBooking`
            FROM `t_htl_camp_schedule` `hcs`
            LEFT JOIN `t_htl_camp_booking` `hcb` ON `hcs`.`Id_HtlCampSchedule` = `hcb`.`Id_HtlCampSchedule`
                        AND `hcb`.`HtlCampBooking_Status` IN (1, 2)
            LEFT JOIN `t_booking_tour` `bt` ON `hcb`.`Id_BookingTour` = `bt`.`Id_BookingTour`
            LEFT JOIN `t_tour` `t` ON `bt`.`Id_Tour` = `t`.`Id_Tour`
            WHERE `hcs`.`Id_HtlCamp` = ?
            AND `hcs`.`HtlCampSchedule_DateSchedule` BETWEEN ? AND ?
            GROUP BY `hcs`.`Id_HtlCampSchedule`
            ORDER BY `hcs`.`HtlCampSchedule_DateSchedule` ASC",
            [$this->idHtlCamp->value(), $this->dateTimeStart->value(), $this->dateTimeEnd->value()]
        );
    }

    protected function analize($data)
    {
        return $data;
    }
}
