<?php

namespace App\Http\Controllers\Admin;

use App\Models\Vehicle;
use App\Constants\Status;
use App\Models\FleetType;
use App\Lib\RequiredConfig;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class VehicleController extends Controller {

    public function vehicles() {
        $pageTitle = 'All Vehicles';
        $fleetType = FleetType::where('status', Status::ENABLE)->orderBy('id', 'desc')->get();
        $vehicles  = Vehicle::with('fleetType')->searchable(['brand_name', 'vehicle_no', 'register_no', 'engine_no', 'chassis_no', 'model_no', 'fleetType:name'])->orderBy('id', 'desc')->paginate(getPaginate());
        return view('admin.fleet.vehicles', compact('pageTitle', 'vehicles', 'fleetType'));
    }

    public function vehiclesStore(Request $request, $id = 0) {

        $request->validate([
            'brand_name'        => 'required|string',
            'fleet_type_id'     => 'required|numeric|exists:fleet_types,id',
            'vehicle_no'        => 'required|string|unique:vehicles,vehicle_no,' . $id,
            'register_no'   => 'nullable|string|unique:vehicles,register_no,' . $id,
            'engine_no'         => 'nullable|string|unique:vehicles,engine_no,' . $id,
            'chassis_no'        => 'nullable|string|unique:vehicles,chassis_no,' . $id,
            'model_no'          => 'nullable|string',
        ]);

        if ($id) {
            $vehicle = Vehicle::findOrFail($id);
            $message = "Vehicle updated successfully";
        } else {
            $vehicle = new Vehicle();
            $message = "Vehicle added successfully";
        }

        $vehicle->vehicle_no        = $request->vehicle_no;
        $vehicle->brand_name        = $request->brand_name;
        $vehicle->fleet_type_id     = $request->fleet_type_id;
        $vehicle->register_no       = $request->register_no;
        $vehicle->engine_no         = $request->engine_no;
        $vehicle->chassis_no        = $request->chassis_no;
        $vehicle->model_no          = $request->model_no;
        $vehicle->save();

        RequiredConfig::configured('vehicle');
        $notify[] = ['success', $message];
        return back()->withNotify($notify);
    }

    public function vehicleStatus($id) {
        return Vehicle::changeStatus($id);
    }
}
