<?php

namespace App\Http\Controllers\Client\PaxInformationPassenger;

use App\Http\Controllers\Client\c_Passenger;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use App\Http\Helpers\ResponseBuilder;
use App\Modules\PaxInformation\Application\PaxInformationTokenEmptyFinder;
use App\Modules\PaxInformation\Domain\PaxInformationToken;
use App\Modules\PaxInformation\Infraestructure\MysqlPaxInformationSearchTokenRepository;
use App\Modules\PaxInformation\Infraestructure\Validators\PaxInformationSearchToken;
use App\Modules\PaxInformationPassenger\Application\PaxInformationPassengerIndexer;
use App\Modules\PaxInformationPassenger\Application\PaxInformationPassengerUser;
use App\Modules\PaxInformationPassenger\Domain\IdPaxInformationPassenger;
use App\Modules\PaxInformationPassenger\Infraestructure\MysqlPaxInformationPassengerRepository;
use App\Modules\PaxInformationPassenger\Infraestructure\Validators\PaxInformationPassengerTokenValidators;
use App\Modules\Shared\Application\ActionHandler;
use App\Modules\Shared\Domain\GenerateActionException;
use App\Modules\Shared\Validator\Infraestructure\LaravelValidator;
use Illuminate\Support\Facades\DB;

final class UpdateToken extends Controller
{
    private $oDomain;

    public function __construct()
    {
        $this->oDomain = 'Pax Information';
    }

    public function __invoke(Request $Request, $PaxInformation_Token)
    {

        $val = (new LaravelValidator);
        $token = ['PaxInformation_Token' => $PaxInformation_Token];
        $val->validate($token, $this->oDomain, PaxInformationSearchToken::BASIC);

        $response = (new PaxInformationTokenEmptyFinder(
            new MysqlPaxInformationSearchTokenRepository
        ))->__invoke(
            new PaxInformationToken($PaxInformation_Token),
        );

        if ($response['Response_Data'][0]->PaxInformation_Lock == 2) {

            $val->validate($Request->all(), $this->oDomain, PaxInformationPassengerTokenValidators::UPDATE_LOCK);
        } else {
            // ------------------------se valida todos los datos que se reciben----
            $val->validate($Request->all(), $this->oDomain, PaxInformationPassengerTokenValidators::UPDATE);
        }

        $responseLockPaxInformation = $response['Response_Data'][0]->PaxInformation_Lock;

        $paxInfoPassenger = (new PaxInformationPassengerIndexer(
            new MysqlPaxInformationPassengerRepository
        ))->__invoke(
            new IdPaxInformationPassenger($Request->input('Id_PaxInformationPassenger'))
        );

        if ($paxInfoPassenger['Response_Data'][0]->Id_PaxInformation != $response['Response_Data'][0]->Id_PaxInformation) {
            (new GenerateActionException)('The Pax Information Passenger is not available');
        }

        if ($paxInfoPassenger['Response_Data'][0]->PaxInformationPassenger_Status == 2) {
            (new GenerateActionException)('The Pax Information Passenger is already used');
        }

        $oResponse = c_Passenger::Image_Upload(1, $Request);

        $response = [
            "Response_Status"           => $oResponse["RespCode"],
            "Response_Code"             => $oResponse["RespCode"],
            "Response_Domain"           => $this->oDomain,
            "Response_Message"          => $oResponse["RespMessage"],
            "Response_Data"             => ['Image_Name' => $oResponse["Image_Name"]],
            "Response_Error_Message"    => $oResponse["ErMessage"],
            "Response_Error_Reason"     => $oResponse["ErReason"],
        ];

        if ($response['Response_Status'] != 200) {
            return ResponseBuilder::Response($response);
        }


        $Passenger_ImgDocument1     = $oResponse["Image_Name"];
        $currentPassenger = DB::select("CALL sp_passenger_index(?, '', '', '', '')", [$paxInfoPassenger['Response_Data'][0]->Id_Passenger])[0];

        // -------------------------------------------------FAAAAAAALLLLLLLLLLLLLLL-------------------------------------------------

        // dd($response['Response_Data']);

        $dateEntrance = $Request->input("Passenger_DateEntrance")
            ? $Request->input("Passenger_DateEntrance") . ' 00:00:00'
            : $currentPassenger->Passenger_DateEntrance;

        if ((int) $responseLockPaxInformation === 2) {
            $paramsLock2 = [
                $currentPassenger->Id_Passenger,
                trim($Request->input("Passenger_Email")),
                trim($Request->input("Passenger_PhoneCode")),
                trim($Request->input("Passenger_Phone")),
                $dateEntrance,
                trim($Request->input("Passenger_Restriction")),
                trim($Request->input("Passenger_Extras")),
                $Passenger_ImgDocument1,
                $currentPassenger->Passenger_ImgDocument2,
                $currentPassenger->Passenger_Status,
            ];

            (new ActionHandler())->handle(
                DB::select(
                    'CALL sp_passenger_update_onlylock_alter(?,?,?,?,?,?,?,?,?,?)',
                    $paramsLock2
                )
            );
        } else {
            $oParam = [
                $currentPassenger->Id_Passenger,
                Str::title(trim($Request->input("Passenger_Name"))),
                Str::title(trim($Request->input("Passenger_LastName"))),
                trim($Request->input("Passenger_Email")),
                trim($Request->input("Passenger_PhoneCode")),
                trim($Request->input("Passenger_Phone")),
                $Request->input("Passenger_Gender"),
                $Request->input("Passenger_DOB"),
                Str::upper(trim($Request->input("Passenger_NoDocument"))),
                $dateEntrance,
                trim($Request->input("Passenger_Restriction")),
                trim($Request->input("Passenger_Extras")),
                $Passenger_ImgDocument1,
                $currentPassenger->Passenger_ImgDocument2,
                $currentPassenger->Passenger_Status,
                $Request->input("Id_TypeDocument"),
                $Request->input("Id_UserCountry")
            ];

            (new ActionHandler())->handle(
                DB::select(
                    'call sp_passenger_update_all_alter(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)',
                    $oParam
                )
            );
        }

        // dd($response['Response_Data'][0]);
        // --------------------------------------------------------------------------------------------------------------------



        $update = (new PaxInformationPassengerUser(new MysqlPaxInformationPassengerRepository))
            ->__invoke(
                new IdPaxInformationPassenger($Request->input('Id_PaxInformationPassenger'))
            );
        $index = (new PaxInformationPassengerIndexer(new MysqlPaxInformationPassengerRepository))
            ->__invoke(
                new IdPaxInformationPassenger($Request->input('Id_PaxInformationPassenger'))
            );
        $index['Response_Message'] = $update['Response_Message'];
        return ResponseBuilder::Response($index);
    }

    public static function validateToken($token)
    {
        $val = new LaravelValidator();
        $tokenValidators = ['PaxInformation_Token' => $token];
        $val->validate($tokenValidators, 'Pax Information', PaxInformationSearchToken::BASIC);
        return (new PaxInformationTokenEmptyFinder(
            new MysqlPaxInformationSearchTokenRepository
        ))->__invoke(
            new PaxInformationToken($token),
        );
    }
}
