<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Driver;
use App\Models\DriverDocument;
use App\Models\User;
use App\Notifications\DocumentReviewNeeded;
use App\Services\FcmService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rule;

class DriverDocumentController extends Controller
{
    public function store(Request $request, Driver $driver): RedirectResponse
    {
        $this->authorizeCompanyOwnership($driver);

        $data = $request->validate([
            'type' => ['required', Rule::in(['licence', 'phv_badge', 'passport', 'biometric_residence_permit'])],
            'document_number' => ['nullable', 'string', 'max:255'],
            'expiry_date' => ['nullable', 'date'],
            'file' => ['required', 'file', 'mimes:jpg,jpeg,png,pdf', 'max:10240'],
        ]);

        $existing = $driver->documents()->where('type', $data['type'])->first();
        if ($existing?->file_path) {
            Storage::disk('local')->delete($existing->file_path);
        }

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

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

        User::where('company_id', $driver->company_id)->get()->each(
            fn (User $admin) => $admin->notify(new DocumentReviewNeeded(
                $driver->full_name, $data['type'], route('admin.drivers.edit', $driver)
            ))
        );

        return back()->with('success', 'Document uploaded — awaiting review.');
    }

    public function updateStatus(Request $request, Driver $driver, DriverDocument $document, FcmService $fcm): RedirectResponse
    {
        $this->authorizeCompanyOwnership($driver);
        abort_unless($document->driver_id === $driver->id, 404);

        $data = $request->validate(['status' => ['required', Rule::in(['active', 'rejected', 'pending'])]]);

        $document->update($data);

        if ($driver->user) {
            $fcm->sendToOwner(
                $driver->user,
                'Document '.$data['status'],
                str($document->type)->headline().' was '.$data['status'].'.',
                ['type' => 'document_status_changed', 'document_id' => (string) $document->id]
            );
        }

        return back()->with('success', 'Document status updated.');
    }

    public function download(Driver $driver, DriverDocument $document)
    {
        $this->authorizeCompanyOwnership($driver);
        abort_unless($document->driver_id === $driver->id, 404);
        abort_unless($document->file_path && Storage::disk('local')->exists($document->file_path), 404);

        return Storage::disk('local')->download($document->file_path);
    }

    public function destroy(Driver $driver, DriverDocument $document): RedirectResponse
    {
        $this->authorizeCompanyOwnership($driver);
        abort_unless($document->driver_id === $driver->id, 404);

        if ($document->file_path) {
            Storage::disk('local')->delete($document->file_path);
        }

        $document->delete();

        return back()->with('success', 'Document removed.');
    }
}
