<?php

namespace App\Http\Controllers\Admin;

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

class DriverController extends Controller
{
    public function index(Request $request): View
    {
        $drivers = Driver::with('company')
            ->withAvg('ratingsReceived', 'stars')
            ->withCount('ratingsReceived')
            ->when($request->user()->company_id, fn ($q, $companyId) => $q->where('company_id', $companyId))
            ->latest()
            ->get();

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

    public function create(Request $request): View
    {
        return view('admin.drivers.create', [
            'driver' => new Driver(['status' => 'active']),
            'companies' => $request->user()->company_id ? collect() : Company::orderBy('name')->get(),
        ]);
    }

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

        $driver = DB::transaction(function () use ($data, $documentRows, $request) {
            $driver = Driver::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("driver-documents/{$driver->id}", 'local');

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

            return $driver;
        });

        $activity->created($driver);

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

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

        return view('admin.drivers.edit', [
            'driver' => $driver->load('documents'),
            'companies' => $request->user()->company_id ? collect() : Company::orderBy('name')->get(),
        ]);
    }

    public function update(DriverRequest $request, Driver $driver, ActivityLogger $activity): RedirectResponse
    {
        $this->authorizeCompanyOwnership($driver);

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

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

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

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

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

        return redirect()->route('admin.drivers.index')->with('success', 'Driver removed.');
    }
}
