<?php

namespace App\Http\Controllers;

use App\Models\AppSetting;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;

class DriverWebRegistrationController extends Controller
{
    private const SESSION_KEY = 'driver_legal_accepted';

    public function showTerms()
    {
        $settings = AppSetting::first();
        $terms = $settings->driver_legal_terms ?? '';

        return view('driver_public.terms', [
            'driver_legal_terms' => $terms,
        ]);
    }

    public function acceptTerms(Request $request)
    {
        $request->validate([
            'legal_accept' => 'accepted',
        ], [
            'legal_accept.accepted' => 'يجب الموافقة على التعليمات القانونية للمتابعة.',
        ]);

        session([self::SESSION_KEY => true]);

        return redirect()->route('driver.subscribe.register');
    }

    public function showRegisterForm()
    {
        if (! session(self::SESSION_KEY)) {
            return redirect()->route('driver.subscribe.terms')
                ->with('error', 'يرجى قراءة الشروط والموافقة عليها أولاً.');
        }

        return view('driver_public.register');
    }

    public function register(Request $request)
    {
        if (! session(self::SESSION_KEY)) {
            return redirect()->route('driver.subscribe.terms')
                ->with('error', 'يرجى قراءة الشروط والموافقة عليها أولاً.');
        }

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'phone' => 'required|string|max:20',
            'email' => 'required|email|max:255|unique:users,email',
            'password' => 'required|string|min:8|confirmed',
            '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',
        ], [], [
            'experience_years' => 'سنوات الخبرة (السنوية)',
        ]);

        $normalizedPhone = $this->normalizePhone($validated['phone']);
        if ($this->userExistsForPhone($validated['phone'])) {
            return redirect()->back()->withInput()->withErrors([
                'phone' => 'رقم الهاتف مسجل مسبقاً',
            ]);
        }

        $path = $request->file('profile_image')->store('profile_images', 'public');

        DB::beginTransaction();
        try {
            $user = User::create([
                'name' => $validated['name'],
                'phone' => $normalizedPhone,
                'email' => $validated['email'],
                'password' => Hash::make($validated['password']),
                'user_type' => 'driver',
                'service_type' => 'taxi',
                'status' => 'active',
                'profile_image' => $path,
                'account_verified' => false,
                'driver_legal_accepted_at' => now(),
                'driver_verification_status' => 'pending',
                'vehicle_type' => $validated['vehicle_type'],
                'vehicle_color' => $validated['vehicle_color'],
                'license_plate' => $validated['license_plate'],
                'vehicle_model_year' => (int) $validated['vehicle_model_year'],
            ]);

            $user->driver()->create([
                'license_number' => null,
                'vehicle_type' => $validated['vehicle_type'],
                'experience_years' => (int) $validated['experience_years'],
                'license_expiry' => null,
                'national_id' => null,
                'phone' => $normalizedPhone,
                'emergency_contact' => null,
                'rating' => 0.00,
                'total_trips' => 0,
                'is_verified' => false,
                'is_active' => true,
                'is_available' => false,
            ]);

            DB::commit();
        } catch (\Throwable $e) {
            DB::rollBack();
            Storage::disk('public')->delete($path);
            \Log::error('driver web register: ' . $e->getMessage());

            return redirect()->back()->withInput()->with('error', 'تعذر إكمال التسجيل. حاول لاحقاً.');
        }

        session()->forget(self::SESSION_KEY);

        return redirect()->route('driver.subscribe.terms')
            ->with('success', 'تم استلام طلبك. راجع الإدارة حسابك؛ بعد الموافقة سيظهر توثيق أزرق بجانب اسمك في التطبيق.');
    }

    private function normalizePhone(string $phone): string
    {
        $phone = preg_replace('/\D/', '', $phone);
        if (strlen($phone) === 10 && (str_starts_with($phone, '07') || str_starts_with($phone, '01'))) {
            return '964' . substr($phone, 1);
        }
        if (strlen($phone) === 11 && str_starts_with($phone, '964')) {
            return $phone;
        }
        if (! str_starts_with($phone, '964')) {
            $phone = '964' . ltrim($phone, '0');
        }

        return $phone;
    }

    private function userExistsForPhone(string $phone): bool
    {
        $normalized = $this->normalizePhone($phone);
        $digits = preg_replace('/\D/', '', $phone);

        if (User::where('phone', $normalized)->exists()) {
            return true;
        }

        if (strlen($digits) >= 10) {
            $localFormat = (str_starts_with($digits, '964') ? '0' . substr($digits, 3) : $digits);
            if (strlen($localFormat) === 11 && str_starts_with($localFormat, '07')) {
                if (User::where('phone', $localFormat)->exists()) {
                    return true;
                }
            }
            if (strlen($localFormat) === 11 && str_starts_with($localFormat, '01')) {
                if (User::where('phone', $localFormat)->exists()) {
                    return true;
                }
            }
        }

        return false;
    }
}
