<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\VehicleRequest;
use App\Models\Company;
use App\Models\Driver;
use App\Models\Vehicle;
use App\Models\VehicleType;
use App\Services\ActivityLogger;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;

class VehicleController extends Controller
{
    public function index(Request $request): View
    {
        $vehicles = Vehicle::with(['vehicleType', 'driver', 'company'])
            ->when($request->user()->company_id, fn ($q, $companyId) => $q->where('company_id', $companyId))
            ->latest()
            ->get();

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

    public function create(Request $request): View
    {
        $companyId = $request->user()->company_id;

        return view('admin.vehicles.create', [
            'vehicle' => new Vehicle(['status' => 'pending']),
            'companies' => $companyId ? collect() : Company::orderBy('name')->get(),
            'vehicleTypes' => VehicleType::when($companyId, fn ($q) => $q->where('company_id', $companyId))->orderBy('name')->get(),
            // A driver can own more than one vehicle now, so every company
            // driver is a valid option here — not just ones with none yet.
            'drivers' => Driver::when($companyId, fn ($q) => $q->where('company_id', $companyId))
                ->orderBy('first_name')->get(),
        ]);
    }

    public function store(VehicleRequest $request, ActivityLogger $activity): RedirectResponse
    {
        $data = $request->validated();
        $data['company_id'] = $request->user()->company_id ?: $data['company_id'];
        $documentRows = $data['documents'] ?? [];
        unset($data['documents']);

        $vehicle = DB::transaction(function () use ($data, $documentRows, $request) {
            $vehicle = Vehicle::create($data);

            // Rows the wizard's "add another document" left with no type or
            // no file selected are just unused template rows — skip them
            // rather than creating an empty document.
            foreach ($documentRows as $i => $row) {
                if (empty($row['type']) || ! $request->hasFile("documents.{$i}.file")) {
                    continue;
                }

                $path = $request->file("documents.{$i}.file")->store("vehicle-documents/{$vehicle->id}", 'local');

                $vehicle->documents()->create([
                    'type' => $row['type'],
                    'document_number' => $row['document_number'] ?? null,
                    'expiry_date' => $row['expiry_date'] ?? null,
                    'file_path' => $path,
                    'status' => 'pending',
                ]);
            }

            return $vehicle;
        });

        $activity->created($vehicle);

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

    public function edit(Request $request, Vehicle $vehicle): View
    {
        $this->authorizeCompanyOwnership($vehicle);

        $companyId = $request->user()->company_id;

        return view('admin.vehicles.edit', [
            'vehicle' => $vehicle->load('documents'),
            'companies' => $companyId ? collect() : Company::orderBy('name')->get(),
            'vehicleTypes' => VehicleType::when($companyId, fn ($q) => $q->where('company_id', $companyId))->orderBy('name')->get(),
            'drivers' => Driver::when($companyId, fn ($q) => $q->where('company_id', $companyId))
                ->orderBy('first_name')->get(),
        ]);
    }

    public function update(VehicleRequest $request, Vehicle $vehicle, ActivityLogger $activity): RedirectResponse
    {
        $this->authorizeCompanyOwnership($vehicle);

        $data = $request->validated();
        $data['company_id'] = $request->user()->company_id ?: ($data['company_id'] ?? $vehicle->company_id);

        $vehicle->update($data);
        $activity->updated($vehicle, $vehicle->getChanges());

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

    public function destroy(Vehicle $vehicle, ActivityLogger $activity): RedirectResponse
    {
        $this->authorizeCompanyOwnership($vehicle);

        $vehicle->delete();
        $activity->deleted($vehicle);

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