<?php

namespace App\Http\Controllers;

use App\Models\TransportRoute;
use App\Models\Vehicle;
use App\Support\BranchContext;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;
use Illuminate\View\View;

class VehicleController extends Controller implements HasMiddleware
{
    public static function middleware(): array
    {
        return [
            new Middleware('can:transport.view', only: ['index']),
            new Middleware('can:transport.create', only: ['create', 'store']),
            new Middleware('can:transport.update', only: ['edit', 'update']),
            new Middleware('can:transport.delete', only: ['destroy']),
        ];
    }

    public function index(): View
    {
        $vehicles = Vehicle::with('route')->orderBy('registration_no')->get();

        return view('transport.vehicles.index', compact('vehicles'));
    }

    public function create(): View
    {
        return view('transport.vehicles.create', ['vehicle' => new Vehicle(), 'routes' => $this->routes()]);
    }

    public function store(Request $request, BranchContext $context): RedirectResponse
    {
        $data = $this->validateData($request);
        $data['branch_id'] = $context->currentId() ?? auth()->user()->branch_id;
        Vehicle::create($data);

        return redirect()->route('vehicles.index')->with('success', 'Vehicle added.');
    }

    public function edit(Vehicle $vehicle): View
    {
        return view('transport.vehicles.edit', ['vehicle' => $vehicle, 'routes' => $this->routes()]);
    }

    public function update(Request $request, Vehicle $vehicle): RedirectResponse
    {
        $vehicle->update($this->validateData($request));

        return redirect()->route('vehicles.index')->with('success', 'Vehicle updated.');
    }

    public function destroy(Vehicle $vehicle): RedirectResponse
    {
        $vehicle->delete();

        return redirect()->route('vehicles.index')->with('success', 'Vehicle deleted.');
    }

    private function routes()
    {
        return TransportRoute::active()->orderBy('name')->get();
    }

    private function validateData(Request $request): array
    {
        $data = $request->validate([
            'registration_no' => ['required', 'string', 'max:40'],
            'model' => ['nullable', 'string', 'max:100'],
            'capacity' => ['nullable', 'integer', 'min:1'],
            'driver_name' => ['nullable', 'string', 'max:150'],
            'driver_phone' => ['nullable', 'string', 'max:30'],
            'driver_license' => ['nullable', 'string', 'max:50'],
            'transport_route_id' => ['nullable', 'exists:transport_routes,id'],
            'is_active' => ['nullable', 'boolean'],
        ]);
        $data['is_active'] = (bool) ($data['is_active'] ?? false);

        return $data;
    }
}
