<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Country;
use App\Models\Currency;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\File;
use Illuminate\Validation\Rules;
use Inertia\Inertia;
use Inertia\Response;

class RegisteredUserController extends Controller
{
    public function create(Request $request): Response
    {
        $detectedCountryIso2 = null;
        $dbPath = storage_path('app/ip2location/IP2LOCATION.BIN');

        // Securely read the BIN file to detect country based on User IP
        if (File::exists($dbPath)) {
            try {
                $db = new \IP2Location\Database($dbPath, \IP2Location\Database::FILE_IO);
                $ip = $request->ip();
                
                // Note: 127.0.0.1 (Localhost) will return '-' because it's not a real public IP.
                // In production, this will perfectly capture their true country code.
                $records = $db->lookup($ip, \IP2Location\Database::ALL);
                if ($records && isset($records['countryCode']) && $records['countryCode'] !== '-') {
                    $detectedCountryIso2 = $records['countryCode'];
                }
            } catch (\Exception $e) {
                // Silently ignore if BIN is invalid or missing
            }
        }

        return Inertia::render('Auth/Register', [
            'detectedCountryIso2' => $detectedCountryIso2
        ]);
    }

    public function checkUsername(Request $request)
    {
        $request->validate([
            'username' => ['required', 'string', 'min:3', 'max:20', 'regex:/^[a-zA-Z0-9_]+$/']
        ]);

        $exists = User::where('username', strtolower($request->username))->exists();

        return response()->json(['available' => !$exists]);
    }

    public function store(Request $request): RedirectResponse
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'username' => ['required', 'string', 'min:3', 'max:20', 'regex:/^[a-zA-Z0-9_]+$/', 'unique:'.User::class],
            'email' => 'required|string|lowercase|email|max:255|unique:'.User::class,
            'phone_code' => 'required|string|max:10', // Added for prefix (e.g. +880)
            'phone' => 'required|string|max:20',      // Added for local number
            'country_id' => 'required|exists:countries,id',
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
        ]);

        $country = Country::find($request->country_id);
        
        /**
         * COMBINE PHONE PREFIX AND NUMBER
         * We ensure the prefix starts with '+' and there is a space between the code and number
         * Example: +880 186706XXXX
         */
        $prefix = str_starts_with($request->phone_code, '+') ? $request->phone_code : '+' . $request->phone_code;
        // Strip any leading zeros from the local number if user included them
        $localNumber = ltrim(preg_replace('/[^0-9]/', '', $request->phone), '0');
        
        $finalPhone = $prefix . ' ' . $localNumber;

        if (User::where('phone', $finalPhone)->exists()) {
            return back()->withErrors(['phone' => 'This phone number is already registered.'])->withInput();
        }

        $user = User::create([
            'name' => $request->name,
            'username' => strtolower($request->username),
            'email' => $request->email,
            'phone' => $finalPhone,
            'country_id' => $request->country_id,
            'password' => Hash::make($request->password),
        ]);

        // AUTO-SET CURRENCY: If the country has a default currency and it is active in your admin panel, 
        // switch the user's session to that currency automatically!
        if ($country && $country->currency) {
            $currencyExists = Currency::where('code', $country->currency)->where('is_active', true)->exists();
            if ($currencyExists) {
                session(['currency' => $country->currency]);
            }
        }

        event(new Registered($user));

        Auth::login($user);

        return redirect(route('dashboard', absolute: false));
    }
}