<?php

namespace App\Http\Controllers\Owner\BookingTour;

use App\Http\Controllers\Controller;
use App\Http\Helpers\ResponseBuilder;
use App\Modules\Shared\Application\SelectHandler;
use Illuminate\Support\Facades\DB;

class BookingTourHotelListController extends Controller
{
    private $domain = 'BookingTour';
    public function __construct() {}

    public function __invoke($Id_Booking)
    {
        $data = [];
        $data['BookingTours'] = array_map([$this, 'fillBookingTour'], $this->bookingTourList($Id_Booking));
        $data['Rooms'] = array_map([$this, 'fillRoom'], $this->roomList($Id_Booking));

        $oResponse = [];
        $oResponse["Response_Status"]           = 200;
        $oResponse["Response_Code"]             = 200;
        $oResponse["Response_Domain"]           = $this->domain;
        $oResponse["Response_Message"]          = 'Lista enviada con éxito';
        $oResponse["Response_Data"]             = $data;
        $oResponse["Response_Error_Message"]    = '';
        $oResponse["Response_Error_Reason"]     = '';

        return ResponseBuilder::Response($oResponse);
    }

    public function fillBookingTour($bookingTour)
    {
        $bookingTour->BookingExtras = array_map([$this, 'fillBookingExtra'], $this->bookingExtraList($bookingTour->Id_BookingTour));
        return $bookingTour;
    }

    public function fillBookingExtra($bookingExtra)
    {
        $bookingExtra->BookingExtraPassengers = $this->bookingExtraPassengerList($bookingExtra->Id_BookingExtra);
        return $bookingExtra;
    }

    private function bookingTourList($idBooking)
    {
        return (new SelectHandler())->handle(DB::select('CALL sp_booking_tour_list(?)', [$idBooking]));
    }

    private function bookingExtraList(int $idBookingTour)
    {
        $idTypeExtra = 4;
        return array_values(array_filter(
            (new SelectHandler())->handle(DB::select('CALL sp_booking_extra_list(?)', [$idBookingTour])),
            fn($bep) => $bep->Id_TypeExtra === $idTypeExtra
        ));
    }

    public function fillRoom($room)
    {
        $room->RoomPassengers = $this->roomPassengerList($room->Id_Room);
        return $room;
    }

    private function bookingExtraPassengerList(int $idBookingExtra)
    {
        return (new SelectHandler())->handle(DB::select('CALL sp_booking_extra_passenger_list(?,?)', [$idBookingExtra, 0]));
    }

    private function roomList(int $idBooking)
    {
        return (new SelectHandler())->handle(DB::select('call sp_room_list(?)', [$idBooking]));
    }

    private function roomPassengerList(int $idBooking)
    {
        return (new SelectHandler())->handle(DB::select('call sp_room_passenger_list(?)', [$idBooking]));
    }
}
