<?php

namespace App\Http\Controllers;

use App\Models\Vehicle;
use Illuminate\Http\Request;

class VehicleController extends Controller
{
    public function __construct() { $this->middleware('auth'); }

    private function authorizeVehicleAccess(Request $request): void
    {
        $user = $request->user();
        if (!$user) abort(403);
        if (method_exists($user, 'isDeveloper') && $user->isDeveloper()) return;
        if (method_exists($user, 'can') && ($user->can('manage settings') || $user->can('create orders') || $user->can('view orders') || $user->can('process payments'))) return;
        abort(403, 'Anda tidak memiliki akses ke data kendaraan.');
    }

    public function index(Request $request)
    {
        $this->authorizeVehicleAccess($request);
        $query = Vehicle::query();
        if ($request->filled('search')) {
            $search = trim((string) $request->search);
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                    ->orWhere('plate_number', 'like', "%{$search}%")
                    ->orWhere('driver_name', 'like', "%{$search}%")
                    ->orWhere('driver_phone', 'like', "%{$search}%");
            });
        }
        if ($request->filled('status')) $query->where('is_active', $request->status === 'active');
        return view('pages.vehicles.index', ['title' => 'Data Kendaraan', 'vehicles' => $query->latest()->paginate(20)->withQueryString()]);
    }

    public function create(Request $request)
    {
        $this->authorizeVehicleAccess($request);
        return view('pages.vehicles.create', ['title' => 'Tambah Kendaraan', 'vehicle' => new Vehicle(['is_active' => true])]);
    }

    public function store(Request $request)
    {
        $this->authorizeVehicleAccess($request);
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'plate_number' => ['nullable', 'string', 'max:50'],
            'driver_name' => ['nullable', 'string', 'max:255'],
            'driver_phone' => ['nullable', 'string', 'max:50'],
            'notes' => ['nullable', 'string', 'max:1000'],
            'is_active' => ['nullable'],
        ]);
        $validated['is_active'] = $request->boolean('is_active');
        Vehicle::create($validated);
        return redirect()->route('vehicles.index')->with('success', 'Kendaraan berhasil ditambahkan.');
    }

    public function edit(Request $request, Vehicle $vehicle)
    {
        $this->authorizeVehicleAccess($request);
        return view('pages.vehicles.edit', ['title' => 'Edit Kendaraan', 'vehicle' => $vehicle]);
    }

    public function update(Request $request, Vehicle $vehicle)
    {
        $this->authorizeVehicleAccess($request);
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'plate_number' => ['nullable', 'string', 'max:50'],
            'driver_name' => ['nullable', 'string', 'max:255'],
            'driver_phone' => ['nullable', 'string', 'max:50'],
            'notes' => ['nullable', 'string', 'max:1000'],
            'is_active' => ['nullable'],
        ]);
        $validated['is_active'] = $request->boolean('is_active');
        $vehicle->update($validated);
        return redirect()->route('vehicles.index')->with('success', 'Kendaraan berhasil diperbarui.');
    }

    public function destroy(Request $request, Vehicle $vehicle)
    {
        $this->authorizeVehicleAccess($request);
        if ($vehicle->deliveryNotes()->exists()) {
            $vehicle->update(['is_active' => false]);
            return redirect()->route('vehicles.index')->with('success', 'Kendaraan sudah pernah dipakai, status diubah menjadi nonaktif.');
        }
        $vehicle->delete();
        return redirect()->route('vehicles.index')->with('success', 'Kendaraan berhasil dihapus.');
    }
}
