<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rules;
use App\Services\CurrencyResolver;
use App\Services\WhmcsAuthService;
use Illuminate\Validation\ValidationException;
use Illuminate\View\View;

class RegisteredUserController extends Controller
{
    public function __construct(
        private readonly WhmcsAuthService $whmcsAuth,
        private readonly CurrencyResolver $currencyResolver,
    ) {}

    /**
     * Display the registration view.
     */
    public function create(): View
    {
        return view('auth.register');
    }

    /**
     * Handle an incoming registration request.
     *
     * @throws ValidationException
     */
    public function store(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'first_name' => ['required', 'string', 'max:255'],
            'last_name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
            'phone_country_code' => ['nullable', 'string', 'max:10'],
            'phone' => ['nullable', 'string', 'max:30'],
            'company_name' => ['nullable', 'string', 'max:255'],
            'street_address' => ['nullable', 'string', 'max:255'],
            'street_address_2' => ['nullable', 'string', 'max:255'],
            'city' => ['nullable', 'string', 'max:255'],
            'state' => ['nullable', 'string', 'max:255'],
            'postcode' => ['nullable', 'string', 'max:50'],
            'country' => ['required', 'string', 'max:2'],
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
            'captcha' => ['required', 'captcha'],
        ]);

        // Lock the same currency the guest was seeing at registration. After
        // the WHMCS client is created, authenticated pages use the account
        // currency and never recalculate it from a later IP/VPN location.
        $resolvedCurrency = $this->currencyResolver->resolve($request);
        $currency = strtoupper((string) ($resolvedCurrency['currency'] ?? ''));

        if (! in_array($currency, ['USD', 'PKR'], true)) {
            $currency = strtoupper((string) $this->currencyResolver->currencyForCountry($data['country']));
        }

        $result = $this->whmcsAuth->registerAndMirror($data, $currency);

        if (! ($result['ok'] ?? false) || empty($result['user'])) {
            throw ValidationException::withMessages([
                'email' => 'Account creation could not be completed. Please review your details or contact support.',
            ]);
        }

        $user = $result['user'];

        event(new Registered($user));

        Auth::login($user);

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