<?php

namespace App\Http\Controllers\Api\Driver;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Notifications\DocumentReviewNeeded;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rule;

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

        return response()->json(['documents' => $driver->documents]);
    }

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

        $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');

        $document = $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 response()->json(['document' => $document], 201);
    }
}
