<?php

namespace App\Http\Controllers\Owner\User;

use App\Http\Controllers\Controller;
use App\Modules\Shared\Domain\Bus\Query\QueryBus;
use App\Modules\Shared\Validator\Infraestructure\LaravelValidator;
use App\Modules\User\Application\SearchBookingReport\SearchBookingByTourUserQuery;
use App\Modules\User\Application\SearchBookingReport\SearchBookingByTourUserResponse;
use App\Modules\User\Infraestructure\UserValidators;
use App\Providers\User\BookingReport\UserBookingByTourExcel;
use App\Providers\User\BookingReport\UserReportBookingData;
use App\Providers\User\BookingReport\UserReportBookingDataCollection;
use App\Providers\UserBooking\BookingTypeImage;
use Illuminate\Http\Request;

class UserBookingByTourExcelController extends Controller
{

    public function __construct(
        private QueryBus $queryBus
    ) {
    }

    public function __invoke(Request $request, $Id)
    {
        (new LaravelValidator)->validate($request->all(), 'User', UserValidators::EXPORT_BOOKING_BY_TOUR);

        /** @var SearchBookingByTourUserResponse $response */
        $response = $this->queryBus->ask(new SearchBookingByTourUserQuery(
            $Id,
            $request->input('User_DateStart'),
            $request->input('User_DateEnd'),
        ));
        (new UserBookingByTourExcel())
            ->exportToExcel(
                new UserReportBookingDataCollection(
                    ...$this->doEverything($response->response()),
                )
            );
    }

    private function doEverything($bookingList)
    {
        $bookingList = array_map([$this, 'richData'], $bookingList);
        return array_map([$this, 'convertToReportBookingData'], $bookingList);
    }

    private function richData($booking)
    {
        $booking->User_Path = config('var.PATH_PUBLIC') . config("var.USER_COUNTRY_THUMB");
        return $booking;
    }

    private function convertToReportBookingData($booking)
    {
        return new UserReportBookingData(
            $booking->Booking_PassengerAmount,
            $booking->Booking_Code,
            date('d-m-Y', strtotime($booking->Booking_DateConfirm)),
            BookingTypeImage::getAssetValue($booking)['text'],
            $this->getUserName($booking),
            $booking->User_Email,
            $booking->Admin_Name,
            $booking->Admin_LastName,
            $booking->BookingTour_Name,
            $booking->Package_Code,
            $booking->Tour_Code,
            $booking->Package_Duration,
            $booking->BookingTour_DateStart,
            $booking->BookingTour_Full,
            $booking->BookingTour_MinimumFull,
            $booking->BookingTourPassenger_Price
        );
    }

    private function getUserName($booking)
    {
        return $booking->User_Type == 1 ? $booking->User_Name . ' ' . $booking->User_LastName : $booking->User_LastName;
    }
}
