<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\AppSetting;
use App\Models\Driver;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class DriverVerificationController extends Controller
{
    public function legalTerms()
    {
        $settings = AppSetting::first();

        return response()->json([
            'success' => true,
            'data' => [
                'driver_legal_terms' => $settings->driver_legal_terms ?? '',
                'driver_legal_terms_html' => $settings->driver_legal_terms
                    ? nl2br(e($settings->driver_legal_terms))
                    : '',
            ],
        ], 200, [], JSON_UNESCAPED_UNICODE);
    }

    public function status(Request $request)
    {
        $user = $request->user();
        if ($user->user_type !== 'driver') {
            return response()->json(['success' => false, 'message' => 'غير مصرح'], 403);
        }

        return response()->json([
            'success' => true,
            'data' => [
                'account_verified' => (bool) $user->account_verified,
                'driver_verification_status' => $user->driver_verification_status ?? 'none',
                'driver_legal_accepted_at' => $user->driver_legal_accepted_at,
                'driver_verification_note' => $user->driver_verification_note,
            ],
        ], 200, [], JSON_UNESCAPED_UNICODE);
    }

    public function acceptLegal(Request $request)
    {
        $user = $request->user();
        if ($user->user_type !== 'driver') {
            return response()->json(['success' => false, 'message' => 'غير مصرح'], 403);
        }

        $request->validate([
            'accepted' => 'required|accepted',
        ], [
            'accepted.required' => 'يجب الموافقة على الشروط',
            'accepted.accepted' => 'يجب الموافقة على الشروط',
        ]);

        $user->update([
            'driver_legal_accepted_at' => now(),
        ]);

        return response()->json([
            'success' => true,
            'message' => 'تم حفظ موافقتك على الشروط',
        ], 200, [], JSON_UNESCAPED_UNICODE);
    }

    public function submit(Request $request)
    {
        $user = $request->user();
        if ($user->user_type !== 'driver') {
            return response()->json(['success' => false, 'message' => 'غير مصرح'], 403);
        }

        if (! $user->driver_legal_accepted_at) {
            return response()->json([
                'success' => false,
                'message' => 'يرجى الموافقة على التعليمات القانونية أولاً',
            ], 422);
        }

        if (($user->driver_verification_status ?? '') === 'pending') {
            return response()->json([
                'success' => false,
                'message' => 'طلبك قيد المراجعة لدى الإدارة',
            ], 422);
        }

        if ($user->account_verified) {
            return response()->json([
                'success' => false,
                'message' => 'حسابك موثق مسبقاً',
            ], 422);
        }

        $request->validate([
            'name' => 'required|string|max:255',
            'experience_years' => 'required|integer|min:0|max:60',
            'vehicle_type' => 'required|string|max:100',
            'license_plate' => 'required|string|max:32',
            'vehicle_model_year' => 'required|integer|min:1980|max:' . ((int) date('Y') + 1),
            'vehicle_color' => 'required|string|max:100',
            'profile_image' => 'required|image|mimes:jpeg,png,jpg,webp|max:4096',
        ], [], [
            'name' => 'الاسم الكامل',
            'experience_years' => 'سنوات الخبرة',
            'vehicle_type' => 'نوع السيارة',
            'license_plate' => 'رقم السيارة (اللوحة)',
            'vehicle_model_year' => 'سنة الموديل',
            'vehicle_color' => 'لون السيارة',
            'profile_image' => 'الصورة الشخصية',
        ]);

        $path = $request->file('profile_image')->store('profile_images', 'public');
        if ($user->profile_image && $user->profile_image !== $path) {
            Storage::disk('public')->delete($user->profile_image);
        }

        $user->update([
            'name' => $request->name,
            'profile_image' => $path,
            'vehicle_type' => $request->vehicle_type,
            'vehicle_color' => $request->vehicle_color,
            'license_plate' => $request->license_plate,
            'vehicle_model_year' => (int) $request->vehicle_model_year,
            'driver_verification_status' => 'pending',
            'driver_verification_note' => null,
        ]);

        if ($user->driver) {
            $user->driver->update([
                'vehicle_type' => $request->vehicle_type,
                'experience_years' => (int) $request->experience_years,
            ]);
        } else {
            Driver::create([
                'user_id' => $user->id,
                'license_number' => null,
                'vehicle_type' => $request->vehicle_type,
                'experience_years' => (int) $request->experience_years,
                'license_expiry' => null,
                'national_id' => null,
                'phone' => $user->phone,
                'emergency_contact' => null,
                'rating' => 0.00,
                'total_trips' => 0,
                'is_verified' => false,
                'is_active' => true,
                'is_available' => false,
            ]);
        }

        return response()->json([
            'success' => true,
            'message' => 'تم إرسال بياناتك للمراجعة. ستظهر علامة التوثيق الزرقاء بعد موافقة الإدارة.',
        ], 200, [], JSON_UNESCAPED_UNICODE);
    }
}
