<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Models\Cliente;
use App\Models\Iticket;
use App\Models\EstacionamientoCajon;
use App\Models\IticketValet;
use App\Models\Sucursal;
use App\Repositories\IticketRepository;
use App\Repositories\IticketValetRepository;
use Carbon\Carbon;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class IticketAPIController extends Controller
{
    private $iticketRepository;
    private $iticketvaletRepository;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct(IticketRepository $iticketRepository, IticketValetRepository $iticketvaletRepository)
    {
        $this->iticketRepository = $iticketRepository;
        $this->iticketvaletRepository = $iticketvaletRepository;

    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Request $request)
    {

    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {

    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Marca  $marca
     * @return \Illuminate\Http\Response
     */
    public function show()
    {
        //
    }


   public function recibirvehiculo(Request $request){
        $this->validate($request, [
            'idvehiculo' => 'required',
            'idcompany' => 'required',
            'idsucursal' => 'required',
            'idempleado' => 'required',
            'idcliente' => 'required'
        ]);

        $cliente = Cliente::where('id', $request->idcliente)->first();
        $sucursal = Sucursal::where('id', $request->idsucursal)->first();
        $token = Str::random(8);

        try{
            $iticket = $this->iticketRepository->create(array(
                'idvehiculo' => $request->idvehiculo,
                'idcompany' => $request->idcompany,
                'idsucursal' => $request->idsucursal,
                'idempleado' => $request->idempleado,
                'idcliente' => $request->idcliente,
                'activo' => 1,
                'token' => $token,
                'idstatusvehiculo' => 1
            ));

            
            
            $iticketvalet = new IticketValet;
            $iticketvalet->iditicket = $iticket->id;
            $iticketvalet->idempleado = $request->idempleado;
            $iticketvalet->idstatusvehiculo = 1;
            $iticketvalet->fecha_asignacion = Carbon::now();
            $iticketvalet->save();


            
            $iticket =  $iticket->id;
            $url = "https://apps.ecdevelopment.mx/SmsEngine/Services/SmsEngine.svc/SMSRequest";
            Http::post($url, [
                "security" => [
                    "AppId" => 6,
                    "Time" => "1634093106",
                    "Hash" => "41d7c1734734ff80b12d02a3a961af51"
                ],
                    "message" => [
                        "SiteId" => "SMS",
                        "Cellphone" => $cliente->celular,
                        "Message"=> "Ticket $iticket." .PHP_EOL. "¡Bienvenido a $sucursal->nombre!" .PHP_EOL. "Presione https://foliattiapp.innovationti.mx/public/foliattiapp.html para solicitar su vehículo ".PHP_EOL. "¡Gracias!"
                    ]
            ]); //" .env('APP_URL')."/api/getToken/$token
            
        } catch (\Exception $e) {
            //Log::error($e->getMessage());
            return $this->sendError($e->getMessage(), 401);
        }

        return $this->sendResponse($iticket, 'Ticket de valet creado');

    }


    public function estacionarvehiculo(Request $request){
        $this->validate($request, [
            'iditicket' => 'required',
            'idestacionamientocajon' => 'required',
        ]);
        try{
            $this->iticketRepository->update(array(
                'idempleado' => NULL,
                'idestacionamientocajon' => $request->idestacionamientocajon,
                'idstatusvehiculo' => 2
            ), $request->iditicket);


            $iticketvalet = $this->iticketvaletRepository->create(array(
				'iditicket' => $request->iditicket,
				'idestacionamientocajon' => $request->idestacionamientocajon,
				'idstatusvehiculo' => 2,
				'fecha_asignacion' => Carbon::now()

            ));


/*            $iticketvalet = new IticketValet;
            $iticketvalet->iditicket = $request->iditicket;
            $iticketvalet->idestacionamientocajon = $request->idestacionamientocajon;
            $iticketvalet->idstatusvehiculo = 2;
            $iticketvalet->fecha_asignacion = Carbon::now();
            $iticketvalet->save();
*/

            $estacionamientoC = EstacionamientoCajon::where('id', $request->idestacionamientocajon)->first();
            $estacionamientoC->disponible = 0;
            $estacionamientoC->save();

            
        } catch (\Exception $e) {
            //Log::error($e->getMessage());
            return $this->sendError($e->getMessage(), 401);
        }

        return $this->sendResponse($iticketvalet, ('El vehículo ha sido estacionado'));
    }

    public function movervehiculo(Request $request){
        $iticket = $this->validate($request, [
            'iditicket' => 'required',
            "idempleado" => 'required',
            'idestacionamientocajon' => 'nullable',
        ]);
        try{
            $this->iticketRepository->update(array(
                'idempleado' => $request->idempleado,
                'idestacionamientocajon' => $request->idestacionamientocajon,
                'idstatusvehiculo' => 3
            ), $request->iditicket);


            $iticketvalet = $this->iticketvaletRepository->create(array(
				'iditicket' => $request->iditicket,
				'idestacionamientocajon' => $request->idestacionamientocajon,
				'idempleado' => $request->idempleado,
				'idstatusvehiculo' => 3,
				'fecha_asignacion' => Carbon::now()

            ));

/*
            $iticketvalet = new IticketValet;
            $iticketvalet->iditicket = $request->iditicket;
            $iticketvalet->idempleado = $request->idempleado;
            $iticketvalet->idstatusvehiculo = 3;
            $iticketvalet->idestacionamientocajon = $request->idestacionamientocajon;
            $iticketvalet->fecha_asignacion = Carbon::now();
            $iticketvalet->save();
*/            
            $estacionamientoC = EstacionamientoCajon::where('id', $request->idestacionamientocajon)->first();
            $estacionamientoC->disponible = 1;
            $estacionamientoC->save();

            
        } catch (\Exception $e) {
            //Log::error($e->getMessage());
            return $this->sendError($e->getMessage(), 401);
        }

        return $this->sendResponse($iticket, ('Vehículo reubicado con éxito'));
    }

    public function recolectararticuloReq(Request $request){
        $this->validate($request, [
            'iditicket' => 'required',
            "detalles" => 'required',
        ]);
        try{
           $iticket = $this->iticketRepository->update(array(
                'idempleado' => NULL,
                'idstatusvehiculo' => 4,
			    'detalles' => $request->detalles
            ), $request->iditicket);

/*
            $iticketvalet = IticketValet::where('iditicket', $request->iditicket)->first();
            $iticketvalet->iditicket = $request->iditicket;
            $iticketvalet->idstatusvehiculo = 4;
            $iticketvalet->detalles = $request->detalles;
            $iticketvalet->save();
*/


            
        } catch (\Exception $e) {
            //Log::error($e->getMessage());
            return $this->sendError($e->getMessage(), 401);
        }

        return $this->sendResponse($iticket, 'Se ha enviado su solicitud');
    }

    public function recolectararticuloValet(Request $request){
        $this->validate($request, [
            'iditicket' => 'required',
            'idempleado' => 'required',
        ]);
        try{
            $iticket = $this->iticketRepository->update(array(
                'idempleado' => $request->idempleado,
            ), $request->iditicket);

			/*
            $iticketvalet = IticketValet::where('iditicket', $request->iditicket)->get()->last();
            $iticketvalet->idempleado = $request->idempleado;
            $iticketvalet->save();
            */

            $iticket = IticketValet::where("iditicket", $request->iditicket)->join('iticket', 'iticket.id', "=", "iticket_valet.iditicket")->select('iticket.*', 'iticket_valet.detalles as detalles')->first();
        } catch (\Exception $e) {
            //Log::error($e->getMessage());
            return $this->sendError($e->getMessage(), 401);
        }

        return $this->sendResponse($iticket, 'Se ha asignado la solicitud');
    }


    public function recolectararticuloValetRes(Request $request){
        $this->validate($request, [
            'iditicket' => 'required',
            'idempleado' => 'required',
           // "detalles" => 'required',
        ]);
        try{
            $iticket = $this->iticketRepository->update(array(
                'idempleado' =>  NULL,
                'idstatusvehiculo' => 2
            ), $request->iditicket);

			
			$iticketTemp = Iticket::where('id', $request->iditicket)->first();

            $iticketvalet = $this->iticketvaletRepository->create(array(
				'iditicket' => $request->iditicket,
//				'idestacionamientocajon' => $request->idestacionamientocajon,
				'idempleado' => $request->idempleado,
				'detalles' => $iticketTemp->detalles,
				'idstatusvehiculo' => 4,
				'fecha_asignacion' => Carbon::now()

            ));

/*
            $iticketvalet = new IticketValet;
            $iticketvalet->iditicket = $request->iditicket;
            $iticketvalet->idempleado = $request->idempleado;
            $iticketvalet->idstatusvehiculo = 4;
            $iticketvalet->detalles = $request->detalles;
            $iticketvalet->fecha_asignacion = Carbon::now();
            $iticketvalet->save();
*/
/*
            $iticketvalet = IticketValet::where('iditicket', $request->iditicket)->get()->last();
            $iticketvalet->idempleado = $request->idempleado;
            $iticketvalet->idstatusvehiculo = 2;
            $iticketvalet->detalles = $request->detalles;
            $iticketvalet->save();
*/


			//Enviar notificación al cliente
			$iticketFullData = Iticket::where('id', $request->iditicket)->first();
            $iticketId =  $iticketFullData->id;
			$cliente = Cliente::where('id', $iticketFullData->idcliente)->first();

            $url = "https://apps.ecdevelopment.mx/SmsEngine/Services/SmsEngine.svc/SMSRequest";
            Http::post($url, [
                "security" => [
                    "AppId" => 6,
                    "Time" => "1634093106",
                    "Hash" => "41d7c1734734ff80b12d02a3a961af51"
                ],
                    "message" => [
                        "SiteId" => "SMS",
                        "Cellphone" => $cliente->celular,
                        "Message"=> "Su solicitud ha sido atendida, diríjase al módulo de Valet Parking " . $request->detalles
                    ]
            ]);

            
        } catch (\Exception $e) {
            //Log::error($e->getMessage());
            return $this->sendError($e->getMessage(), 401);
        }

        return $this->sendResponse($iticket, 'La solicitud ha sido atendida');
    }


    public function calificariTicket(Request $request){
        $this->validate($request, [
            'iditicket' => 'required',
            'calificacion' => 'required',
            "comentarios" => 'nullable',
        ]);
        try{
            $iticket = $this->iticketRepository->update(array(
                'calificacion' =>  $request->calificacion,
                'comentarios' =>  $request->comentarios,
                'calificado' =>  true,
				'ranked_at' =>now()
            ), $request->iditicket);

/*
			$iticketvalet = IticketValet::where('iditicket', $request->iditicket)->get()->last();
            $iticketvalet->idempleado = $request->idempleado;
            $iticketvalet->idstatusvehiculo = 2;
            $iticketvalet->detalles = $request->detalles;
            $iticketvalet->save();
*/
            
        } catch (\Exception $e) {
            //Log::error($e->getMessage());
            return $this->sendError($e->getMessage(), 401);
        }

        return $this->sendResponse($iticket, ('Su calificación ha sido enviada'));
    }




    public function getToken($token){
        $iticket = Iticket::where('token', $token)->first();
        $iticketid = new Request(array('iditicket' => $iticket->id));
       // $this->solicitarvehiculo($iticketid);
        return view('welcome');
    }

    public function solicitarvehiculo(Request $request){
        $this->validate($request, [
            'iditicket' => 'required',
        ]);
        try{
            $iticket = $this->iticketRepository->update(array(
                'idempleado' =>  NULL,
                'idstatusvehiculo' => 5
            ), $request->iditicket);

/*
            $iticketvalet = IticketValet::where('iditicket', $request->iditicket)->get()->last();
            $iticketvalet->idstatusvehiculo = 5;
            $iticketvalet->save();
*/

            $iticketvalet = $this->iticketvaletRepository->create(array(
				'iditicket' => $request->iditicket,
//				'idestacionamientocajon' => $request->idestacionamientocajon,
//				'idempleado' => $request->idempleado,
//				'detalles' => $request->detalles,
				'idstatusvehiculo' => 5,
				'fecha_asignacion' => Carbon::now()

            ));

            
        } catch (\Exception $e) {
            //Log::error($e->getMessage());
            return $this->sendError($e->getMessage(), 401);
        }

        return $this->sendResponse($iticket, ('Ha solicitado su vehículo'));
    }

    public function solicitarvehiculoValet(Request $request){
        $this->validate($request, [
            'iditicket' => 'required',
            'idempleado' => 'required'
        ]);
        try{
            $iticket = $this->iticketRepository->update(array(
                'idempleado' =>  $request->idempleado,
                'idstatusvehiculo' => 6
            ), $request->iditicket);


            $iticketvalet = $this->iticketvaletRepository->create(array(
				'iditicket' => $request->iditicket,
//				'idestacionamientocajon' => $request->idestacionamientocajon,
				'idempleado' => $request->idempleado,
//				'detalles' => $request->detalles,
				'idstatusvehiculo' => 6,
				'fecha_asignacion' => Carbon::now()

            ));

/*

            $iticketvalet = new IticketValet;
            $iticketvalet->iditicket = $request->iditicket;
            $iticketvalet->idempleado = $request->idempleado;
            $iticketvalet->idstatusvehiculo = 6;
            $iticketvalet->fecha_asignacion = Carbon::now();
            $iticketvalet->save();
*/
			/*
            $iticketvalet = IticketValet::where('iditicket', $request->iditicket)->get()->last();
            $iticketvalet->idempleado = $request->idempleado;
            $iticketvalet->idstatusvehiculo = 6;
            $iticketvalet->save();
*/

            
        } catch (\Exception $e) {
            //Log::error($e->getMessage());
            return $this->sendError($e->getMessage(), 401);
        }

        return $this->sendResponse($iticket, ('Se ha asignado un vehículo para entrega'));
    }


    public function cancelarSolicitud(Request $request){
        $this->validate($request, [
            'iditicket' => 'required'
        ]);
		$iticketFinal = 9;

        try{
			$iticketGotten = Iticket::where('id', $request->iditicket)->get()->last();

            if($iticketGotten->idstatusvehiculo == 5)
				$iticketFinal = 2;

			$iticket = $this->iticketRepository->update(array(
                'idstatusvehiculo' => $iticketFinal
            ), $request->iditicket);


            $iticketvalet = $this->iticketvaletRepository->create(array(
				'iditicket' => $request->iditicket,
//				'idestacionamientocajon' => $request->idestacionamientocajon,
//				'idempleado' => $request->idempleado,
//				'detalles' => $request->detalles,
				'idstatusvehiculo' => 9,
				'fecha_asignacion' => Carbon::now()

            ));

/*
            $iticketvalet = new IticketValet;
            $iticketvalet->iditicket = $request->iditicket;
//            $iticketvalet->idempleado = $request->idempleado;
            $iticketvalet->idstatusvehiculo = 9;
            $iticketvalet->fecha_asignacion = Carbon::now();
            $iticketvalet->save();
*/
/*
            $iticketvalet = IticketValet::where('iditicket', $request->iditicket)->get()->last();
            $iticketvalet->idempleado = $request->idempleado;
            $iticketvalet->idstatusvehiculo = 9;
            $iticketvalet->save();
*/

            
        } catch (\Exception $e) {
            //Log::error($e->getMessage());
            return $this->sendError($e->getMessage(), 401);
        }

        return $this->sendResponse($iticket, ('Se ha cancelado la Solicitud de Vehículo'));
    }


    public function dejarlistovehiculo(Request $request){
        $this->validate($request, [
            'iditicket' => 'required',
            'idempleado' => 'required'
        ]);
        try{
            $iticket = $this->iticketRepository->update(array(
                'idempleado' =>  $request->idempleado,
                //'activo' => 0,
                'idstatusvehiculo' => 7
            ), $request->iditicket);


            $iticketvalet = $this->iticketvaletRepository->create(array(
				'iditicket' => $request->iditicket,
//				'idestacionamientocajon' => $request->idestacionamientocajon,
				'idempleado' => $request->idempleado,
//				'detalles' => $request->detalles,
				'idstatusvehiculo' => 7,
				'fecha_asignacion' => Carbon::now()

            ));

/*
            $iticketvalet = new IticketValet;
            $iticketvalet->iditicket = $request->iditicket;
            $iticketvalet->idempleado = $request->idempleado;
            $iticketvalet->idstatusvehiculo = 7;
            $iticketvalet->fecha_asignacion = Carbon::now();
            $iticketvalet->save();
*/
/*
            $iticketvalet = IticketValet::where('iditicket', $request->iditicket)->get()->last();
            $iticketvalet->idempleado = $request->idempleado;
            $iticketvalet->idstatusvehiculo = 7;
            $iticketvalet->save();
*/            
            $estacionamientoC = EstacionamientoCajon::where('id', $iticket->idestacionamientocajon)->first();
            $estacionamientoC->disponible = 1;
            $estacionamientoC->save();


			//Enviar notificación al cliente
			$iticketFullData = Iticket::where('id', $request->iditicket)->first();
            $iticketId =  $iticketFullData->id;
			$cliente = Cliente::where('id', $iticketFullData->idcliente)->first();
            $url = "https://apps.ecdevelopment.mx/SmsEngine/Services/SmsEngine.svc/SMSRequest";
            Http::post($url, [
                "security" => [
                    "AppId" => 6,
                    "Time" => "1634093106",
                    "Hash" => "41d7c1734734ff80b12d02a3a961af51"
                ],
                    "message" => [
                        "SiteId" => "SMS",
                        "Cellphone" => $cliente->celular,
                        "Message"=> "Su vehículo está listo"
                    ]
            ]);
            
        } catch (\Exception $e) {
            //Log::error($e->getMessage());
            return $this->sendError($e->getMessage(), 401);
        }

        return $this->sendResponse($iticket, ('El vehículo se encuentra listo para entrega'));
    }

    public function entregarvehiculo(Request $request){
        $this->validate($request, [
            'iditicket' => 'required',
            'idempleado' => 'required'
        ]);
        try{
            $iticket = $this->iticketRepository->update(array(
                'idempleado' =>  NULL,
                //'activo' => 0,
                'idstatusvehiculo' => 8
            ), $request->iditicket);


            $iticketvalet = $this->iticketvaletRepository->create(array(
				'iditicket' => $request->iditicket,
//				'idestacionamientocajon' => $request->idestacionamientocajon,
				'idempleado' => $request->idempleado,
//				'detalles' => $request->detalles,
				'idstatusvehiculo' => 8,
				'fecha_asignacion' => Carbon::now()

            ));

/*
            $iticketvalet = new IticketValet;
            $iticketvalet->iditicket = $request->iditicket;
            $iticketvalet->idempleado = $request->idempleado;
            $iticketvalet->idstatusvehiculo = 8;
            $iticketvalet->fecha_asignacion = Carbon::now();
            $iticketvalet->save();
*/
/*
            $iticketvalet = IticketValet::where('iditicket', $request->iditicket)->get()->last();
            $iticketvalet->idempleado = $request->idempleado;
            $iticketvalet->idstatusvehiculo = 8;
            $iticketvalet->save();
*/            


            
        } catch (\Exception $e) {
            //Log::error($e->getMessage());
            return $this->sendError($e->getMessage(), 401);
        }

        return $this->sendResponse($iticket, ('El vehiculo ha sido entregado'));
    }


    public function desactivariTicket(Request $request){
        $this->validate($request, [
            'iditicket' => 'required',
        ]);
        try{
            $iticket = $this->iticketRepository->update(array(
                'activo' =>  0,
            ), $request->iditicket);

            
        } catch (\Exception $e) {
            //Log::error($e->getMessage());
            return $this->sendError($e->getMessage(), 401);
        }

        return $this->sendResponse($iticket, 'El iTicket ha finalizado');
    }





    public function getVehiculocliente($idcliente){
        $vehiculo = Iticket::where('iticket.idcliente',$idcliente)->leftjoin('vehiculos', 'vehiculos.id', '=' , 'iticket.idvehiculo')->leftjoin('estacionamientocajon', 'estacionamientocajon.id', '=' , 'iticket.idestacionamientocajon')->select('iticket.id as iditicket', 'vehiculos.*', 'estacionamientocajon.*', 'iticket.detalles as detalles', 'iticket.*')->where('iticket.activo', '=', '1')->first();
        if (empty($vehiculo)) {
            return $this->sendError('Vehículo no encontrado');
        }else {
            return $this->sendResponse($vehiculo, ('Vehículo encontrado'));
        }   
    }

    public function getVehiculovalet($idempleado){
        $vehiculo = Iticket::where('iticket.idempleado', $idempleado)->leftjoin('vehiculos', 'vehiculos.id', '=' , 'iticket.idvehiculo')->leftjoin('estacionamientocajon', 'estacionamientocajon.id', '=' , 'iticket.idestacionamientocajon')->select('iticket.id as iditicket', 'vehiculos.*', 'estacionamientocajon.*', 'iticket.detalles as detalles', 'iticket.*')->where('iticket.activo', '=', '1')->get();
    
        if ($vehiculo->isEmpty()) {
            return $this->sendError(('Vehículo no encontrado'));
        }else {
            return $this->sendResponse($vehiculo, ('Vehículo encontrado'));
        }   
    }

    public function getVehiculosucursal($idsucursal){
        $vehiculo = Iticket::where('iticket.idsucursal',$idsucursal)->leftjoin('vehiculos', 'vehiculos.id', '=' , 'iticket.idvehiculo')->leftjoin('estacionamientocajon', 'estacionamientocajon.id', '=' , 'iticket.idestacionamientocajon')->select('iticket.id as iditicket', 'vehiculos.*', 'estacionamientocajon.*', 'iticket.detalles as detalles', 'iticket.*')->where('iticket.activo', '=', '1')->orderBy('iticket.id', 'desc')->get();
    
        if ($vehiculo->isEmpty()) {
            return $this->sendError('Vehículo no encontrado');
        }else {
            return $this->sendResponse($vehiculo, ('Vehículo encontrado'));
        }   
    }


    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\marca  $marca
     * @return \Illuminate\Http\Response
     */
    public function edit()
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\marca  $marca
     * @return \Illuminate\Http\Response
     */
    public function update()
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\marca  $marca
     * @return \Illuminate\Http\Response
     */
    public function destroy()
    {
        //
    }
}