<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Http;

class RegisterController extends Controller
{
    protected function fallbackCountries()
    {
        return collect([
            [
                'name'  => 'Bangladesh',
                'flag'  => '🇧🇩',
                'short' => 'BD',
                'codes' => ['+880'],
            ],
            [
                'name'  => 'India',
                'flag'  => '🇮🇳',
                'short' => 'IN',
                'codes' => ['+91'],
            ],
            [
                'name'  => 'Pakistan',
                'flag'  => '🇵🇰',
                'short' => 'PK',
                'codes' => ['+92'],
            ],
        ]);
    }

    protected function getCountries()
    {
        try {
            $response = Http::get('https://restcountries.com/v3.1/all', [
                'fields' => 'name,cca2,flag,idd',
            ]);

            if (! $response->ok()) {
                return $this->fallbackCountries();
            }

            return collect($response->json())
                ->filter(function ($c) {
                    return isset($c['idd']['root']);
                })
                ->map(function ($c) {
                    $root     = $c['idd']['root'] ?? '';
                    $suffixes = $c['idd']['suffixes'] ?? [''];

                    $codes = collect($suffixes)->map(function ($s) use ($root) {
                        return $root . $s;
                    })->all();

                    return [
                        'name'  => $c['name']['common'] ?? '',
                        'flag'  => $c['flag'] ?? '',
                        'short' => $c['cca2'] ?? '',
                        'codes' => $codes,
                    ];
                })
                ->sortBy('short')
                ->values();
        } catch (\Throwable $e) {
            return $this->fallbackCountries();
        }
    }

    public function showRegistrationForm()
    {
        $countries = $this->getCountries();

        return view('frontend.auth.register', compact('countries'));
    }

    public function register(Request $request)
    {
        $request->validate([
            'name'         => ['required', 'string', 'max:255'],
            'country_code' => ['required', 'string', 'max:6'],
            'role'         => ['required', 'in:student,teacher,guardian,business,employee,other'],
            'phone'        => ['required', 'string', 'max:20', 'unique:users,phone'],
            'password'     => ['required', 'string', 'min:6'],
        ], [
            'name.required'         => 'নাম লিখুন।',
            'country_code.required' => 'কান্ট্রি কোড নির্বাচন করুন।',
            'role.required'         => 'ভূমিকা নির্বাচন করুন।',
            'phone.required'        => 'মোবাইল নম্বর লিখুন।',
            'phone.unique'          => 'এই মোবাইল নম্বর দিয়ে আগে থেকেই একাউন্ট রয়েছে।',
            'password.min'          => 'পাসওয়ার্ড ন্যূনতম ৬ অক্ষরের হতে হবে।',
        ]);

        $user = User::create([
            'name'         => $request->name,
            'country_code' => $request->country_code,
            'role'         => $request->role,
            'phone'        => $request->phone,
            'password'     => Hash::make($request->password),
            'status'       => 'active',
        ]);

        Auth::login($user);

        return redirect()->intended('/dashboard');
    }
}
