<?php

namespace App\Http\Controllers\Api\Driver;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Vehicle;
use App\Notifications\VehicleSubmittedForReview;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class VehicleController extends Controller
{
    /**
     * Driver self-service vehicle submission — always lands as 'pending',
     * same as the old project's addvehicle() (all fields flagged for
     * approval regardless of what the driver enters).
     */
    public function store(Request $request): JsonResponse
    {
        $driver = $request->user()->driver;
        abort_unless($driver, 404, __('api.no_driver_profile'));

        $data = $request->validate([
            'vehicle_type_id' => ['required', 'exists:vehicle_types,id'],
            'registration_number' => ['required', 'string', 'max:255'],
            'make' => ['nullable', 'string', 'max:255'],
            'model' => ['nullable', 'string', 'max:255'],
            'year' => ['nullable', 'integer', 'min:1980', 'max:'.(now()->year + 1)],
            'color' => ['nullable', 'string', 'max:255'],
        ]);

        $vehicle = Vehicle::create($data + [
            'company_id' => $driver->company_id,
            'driver_id' => $driver->id,
            'status' => 'pending',
        ]);

        User::where('company_id', $driver->company_id)->get()->each(
            fn (User $admin) => $admin->notify(new VehicleSubmittedForReview(
                $driver->full_name, $vehicle->registration_number, route('admin.vehicles.edit', $vehicle)
            ))
        );

        return response()->json(['vehicle' => $vehicle], 201);
    }

    public function index(Request $request): JsonResponse
    {
        $driver = $request->user()->driver;
        abort_unless($driver, 404, __('api.no_driver_profile'));

        return response()->json(['vehicles' => $driver->vehicles()->with('vehicleType')->get()]);
    }
}
