<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\Vehicle;
use App\Models\PrepaidCard;
use App\Traits\PaginatorHelper;

class VehicleController extends Controller
{
    use PaginatorHelper;

    public function index(Request $request)
    {
        $helper = $this->processRequest($request);
        $vehicles = Vehicle::whereNotNull('id');
        $vehicles->with('ansapass');
        if ($request->cardId) {
            $card = PrepaidCard::find($request->cardId);
            $vehicles = $card->vehicles()->with(['profile','vehicleBrand','vehicleType'])->paginate(50);
        } else {
            $vehicles = $this->applyFilters($vehicles, $helper,
                ['plate', 'year', 'color', 'profile.names,surnames,id_card', 'vehicleBrand.name', 'vehicleType.name']);
        }

        return response()->json($vehicles);
    }

    public function search(Request $request)
    {
        $plate = $request->plate;
        $profileId = $request->profileId;
        $vehicle = Vehicle::where('plate', $plate)->where('status', 1)->first();
        if ($vehicle) {
            if ($vehicle->profile_id != $profileId) {
                return response()->json([
                    "status" => -1,
                    "item" => $vehicle,
                    "message" => "Vehiculo asignado a otro usuario"
                ]);
            } else {
                return response()->json([
                    "status" => 1,
                    "item" => $vehicle,
                    "message" => "Vehiculo encontrado"
                ]);
            }
        } else {
            return response()->json([
                "status" => 0,
                "message" => "Vehiculo No encontrado"
            ]);
        }
    }

    public function save(Request $request)
    {
        $id = $request->id;

        try{
            // Begin of the transaction
            DB::beginTransaction();
            if ($id) {
                $vehicle = Vehicle::find($id);
            } else {
                $vehicle = new Vehicle();
                $vehicle->plate = $request->plate;
                $vehicle->profile_id = $request->profileId;
            }

            $vehicle->vehicle_type_id = $request->vehicleTypeId;
            $vehicle->vehicle_brand_id = $request->vehicleBrandId;
            $vehicle->year = $request->year;
            $vehicle->color = $request->color;

            $vehicle->save();

            // Write in the database
            DB::commit();
            if ($vehicle) {
                return response()->json([
                    "status" => 1,
                    "item" => $vehicle,
                    "message" => "Vehiculo actualizado exitosamente"
                ]);
            } else {
                return response()->json([
                    "status" => 0,
                    "message" => "Vehiculo No encontrado"
                ]);
            }
        } catch(\Exception $e) {
            // Make a Rollback
            DB::rollback();

            // Return Response
            return response()->json([
                "status" => 0,
                "message" => $e
            ]);
        }
    }

    public function delete(Request $request)
    {
        $id = $request->id;
        try{
            $vehicle = Vehicle::find($id);
            if ($vehicle->prepaidCards->count()){
                return response()->json([
                    "status" => 0,
                    "message" => "Este Vehiculo ya esta asociado a al menos un carnet prepagado, es imposible eliminarlo"
                ]);
            }

            if ($vehicle->ansapass){
                return response()->json([
                    "status" => 0,
                    "message" => "Este Vehiculo ya esta asociado un Ansapass, es imposible eliminarlo"
                ]);
            }


            $vehicle->delete();
            return response()->json([
                "status" => 1,
                "message" => "Vehiculo ". $vehicle->plate . " eliminado exitosamente"
            ]);

        } catch (\Exception $e) {
            return response()->json([
                "status" => 0,
                "message" => "Ocurrio un error, intente mas tarde, si el problema persiste comuniquese con su administrador"
            ]);
        }
    }

    public function toggleStatus(Request $request)
    {
        $id = $request->id;
        try{
            $vehicle = Vehicle::find($id);
            if(!$vehicle){
                return response()->json([
                    "status" => 0,
                    "message" => "Vehiculo No existe en la base de datos"
                ]);
            }

            $vehicle->status = !$vehicle->status;
            $vehicle->save();
            return response()->json([
                "status" => 1,
                "message" => "Estatus del Vehiculo ha sido cambiado exitosamente"
            ]);

        } catch (\Exception $e) {
            return response()->json([
                "status" => 0,
                "message" => "Ocurrio un error, intente mas tarde, si el problema persiste comuniquese con su administrador"
            ]);
        }
    }
}