<?php

namespace App\Http\Controllers\Owner\Info;

use Illuminate\Support\Facades\DB;

class ChangeBookingExtraController
{
    public function __invoke()
    {
        $IdBookingExtra = 28680;
        $IdBookingTourNuevo = 35145;
        $GroupNew = 2;
        $invoiceDetailType = 2;
        $bookingExtra = DB::select('SELECT * FROM t_booking_extra WHERE Id_BookingExtra=?', [$IdBookingExtra]);
        $bookingTour = DB::select('SELECT * FROM t_booking_tour WHERE Id_BookingTour=?', [$bookingExtra[0]->Id_BookingTour]);
        $newPassengers = DB::select('SELECT * FROM t_booking_tour_passenger WHERE Id_BookingTour=?', [$IdBookingTourNuevo]);
        if ($bookingExtra[0]->Id_BookingTour == $IdBookingTourNuevo) {
            echo 'El Id_BookingExtra ya está en el nuevo Id_BookingTour';
            return;
        }

        $bookingExtraPassengers = DB::select(
            'SELECT bep., btp.
      FROM t_booking_extra_passenger bep
      INNER JOIN t_booking_tour_passenger btp ON btp.Id_BookingTourPassenger=bep.Id_BookingTourPassenger
      WHERE Id_BookingExtra=?',
            [$bookingExtra[0]->Id_BookingExtra]
        );

        foreach ($bookingExtraPassengers as $bep) {
            $found = $this->findBookingExtraPassenger($bep->Id_Passenger, $newPassengers);
            if ($found) {
                DB::update('UPDATE t_booking_extra_passenger SET Id_BookingTourPassenger=? WHERE Id_BookingExtraPassenger=?', [$found->Id_BookingTourPassenger, $bep->Id_BookingExtraPassenger]);
            }
        }

        DB::update('UPDATE t_booking_extra SET Id_BookingTour=? WHERE Id_BookingExtra=?', [$IdBookingTourNuevo, $IdBookingExtra]);

        DB::update(
            'UPDATE t_invoice_detail SET InvoiceDetail_Group=? WHERE Id=? AND InvoiceDetail_Type=? AND Id_Invoice IN (SELECT Id_Invoice FROM t_invoice WHERE Id_Booking=?)',
            [$GroupNew, $bookingExtra[0]->Id_BookingExtra, $invoiceDetailType, $bookingTour[0]->Id_Booking]
        );
        echo 'OK';
    }

    public function findBookingExtraPassenger($Id_Passenger, $bookingTourPassenger)
    {
        $found = array_values(array_filter($bookingTourPassenger, fn($btp) => $btp->Id_Passenger == $Id_Passenger));
        return count($found) ? $found[0] : null;
    }
}
