<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Services\EmailService;
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\Validation\Rules;
use Illuminate\View\View;
use App\Helpers\ConfigHelper;
use Illuminate\Support\Facades\Http;

class RegisteredUserController extends Controller
{
    protected EmailService $emailService;

    public function __construct(EmailService $emailService)
    {
        $this->emailService = $emailService;
    }

    /**
     * Verify Google reCAPTCHA token with Google's API
     */
    private function verifyRecaptcha(string $token, string $secret, string $remoteIp = null): bool
    {
        try {
            $response = Http::asForm()->post('https://www.google.com/recaptcha/api/siteverify', [
                'secret' => $secret,
                'response' => $token,
                'remoteip' => $remoteIp,
            ]);

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

            $body = $response->json();
            return isset($body['success']) && $body['success'] === true;
        } catch (\Exception $e) {
            // On error, consider verification failed
            return false;
        }
    }

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

    /**
     * Handle an incoming registration request.
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    public function store(Request $request): RedirectResponse
    {
        $request->validate([
            'firstname' => ['required', 'string', 'max:255'],
            'lastname' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
            'phonenumber' => ['nullable', 'string', 'max:50'],
            'country' => ['nullable', 'string', 'max:100'],
        ]);

        // Anti-spam validation: human question or Google reCAPTCHA
        $enableCaptcha = ConfigHelper::getSetting('enable_captcha', false);
        $captchaSecret = ConfigHelper::getSetting('captcha_secret_key', '');
        $enableHumanQuestion = ConfigHelper::getSetting('enable_human_question', true);

        // Validate captcha independently if enabled
        if ($enableCaptcha && $captchaSecret) {
            $token = $request->input('g-recaptcha-response');
            if (empty($token)) {
                return back()->withErrors(['g-recaptcha-response' => __('Please complete the captcha')])->withInput();
            }

            $verified = $this->verifyRecaptcha($token, $captchaSecret, $request->ip());
            if (! $verified) {
                return back()->withErrors(['g-recaptcha-response' => __('Captcha verification failed')])->withInput();
            }
        }

        // Validate human question independently if enabled
        if ($enableHumanQuestion) {
            $humanQuestionsJson = ConfigHelper::getSetting('human_questions', null);
            $humanQuestions = [];
            if (!empty($humanQuestionsJson)) {
                try {
                    $humanQuestions = json_decode($humanQuestionsJson, true) ?: [];
                } catch (\Exception $e) {
                    $humanQuestions = [];
                }
            }

            $given = strtolower(trim((string)$request->input('human_answer', '')));
            $index = $request->input('human_question_index', null);

            if ($index === null || !isset($humanQuestions[$index])) {
                // Fallback to single-answer setting if provided
                $expected = ConfigHelper::getSetting('human_question_answer', '5');
                if ($given === '' || strtolower(trim((string)$expected)) !== $given) {
                    return back()->withErrors(['human_answer' => __('Incorrect answer to the anti-spam question')])->withInput();
                }
            } else {
                $expected = strtolower(trim((string)($humanQuestions[$index]['answer'] ?? '')));
                if ($given === '' || $expected !== $given) {
                    return back()->withErrors(['human_answer' => __('Incorrect answer to the anti-spam question')])->withInput();
                }
            }
        }

        $user = User::create([
            'name' => $request->firstname . ' ' . $request->lastname,
            'firstname' => $request->firstname,
            'lastname' => $request->lastname,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'phonenumber' => $request->phonenumber,
            'country' => $request->country,
        ]);

        event(new Registered($user));

        // Send welcome email
        try {
            $this->emailService->sendWelcome($user, [
                'registration_date' => now()->format('Y-m-d H:i:s'),
            ]);
        } catch (\Exception $e) {
            // Silently handle email errors to not fail registration
        }

        Auth::login($user);

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