<?php

namespace App\Modules\BookingExtraPassenger\Domain;

use App\Modules\Shared\Domain\Storage\Criteria\StorageCriteria;
use Illuminate\Support\Facades\DB;

class ListByIdBookingExtraPassenger implements StorageCriteria
{

    public function __construct(
        private array $ids
    ) {}

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

    protected function query()
    {
        $select = BookingExtraPassenger::select('`bep`');

        $where = $this->whereIn('`bep`.`Id_BookingExtraPassenger`', $this->ids);

        return DB::select(
            "SELECT $select,
                `p`.`Id_Passenger`,
                `p`.`Passenger_Gender`,
                `p`.`Passenger_Name`,
                `p`.`Passenger_LastName`,

                `bt`.`Id_BookingTour`,
                `bt`.`BookingTour_TourName`,
                `bt`.`BookingTour_DateStart`,
                `bt`.`BookingTour_TourDuration`,

                `b`.`Id_Booking`,
                `b`.`Booking_Code`,
                `b`.`Booking_InternalRemark`,
                `b`.`Booking_Observation`,

                `uc`.`Id_UserCountry`,
                `uc`.`UserCountry_Name`,
                `uc`.`UserCountry_Img`

            FROM `t_booking_extra_passenger` `bep`
            INNER JOIN `t_booking_extra` `be` ON `be`.`Id_BookingExtra` = `bep`.`Id_BookingExtra`
            INNER JOIN `t_booking_tour` `bt` ON `bt`.`Id_BookingTour` = `be`.`Id_BookingTour`
            INNER JOIN `t_booking` `b` ON `b`.`Id_Booking` = `bt`.`Id_Booking`
            INNER JOIN `t_booking_tour_passenger` `btp` ON `btp`.`Id_BookingTourPassenger` = `bep`.`Id_BookingTourPassenger`
            INNER JOIN `t_passenger` `p` ON `p`.`Id_Passenger` = `btp`.`Id_Passenger`
            INNER JOIN `t_user_country` `uc` ON `uc`.`Id_UserCountry` = `p`.`Id_UserCountry`
            WHERE $where",
            $this->ids
        );
    }

    private function whereIn($index, $ids)
    {
        return $index . ' IN (' . $this->getQuestionMarks($ids) . ')';
    }

    private function getQuestionMarks($ids)
    {
        return implode(',', array_fill(0, count($ids), '?'));
    }

    protected function analize($data)
    {
        return array_map(fn($bep) => ListBookingExtraPassenger::fromDTO($bep), $data);
    }
}
