<?php

namespace App\Http\Controllers\Auth;

use App\Helpers\PasswordHelper;
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\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
use Inertia\Inertia;
use Inertia\Response;

class RegisteredUserController extends Controller
{
    /**
     * Show the registration page.
     */
    public function create(): Response
    {
        // Check if setting exists, if not, disable by default
        $pinFieldSetting = DB::table('settings')->where('key', 'pin_field_enabled')->first();
        if (!$pinFieldSetting) {
            // Insert default value of disabled for new installations
            DB::table('settings')->insert([
                'key' => 'pin_field_enabled',
                'value' => '0', // Disabled by default
                'created_at' => now(),
                'updated_at' => now()
            ]);
            $pinFieldEnabled = false;
        } else {
            $pinFieldEnabled = $pinFieldSetting->value === '1';
        }
        
        // Get application name from .env config
        $appName = config('app.name', 'Perfect World');
        
        // Check if Google login is enabled
        $googleLoginEnabled = DB::table('settings')->where('key', 'google_login_enabled')->value('value') === '1';
        
        return Inertia::render('auth/register', [
            'pinFieldEnabled' => $pinFieldEnabled,
            'appName' => $appName,
            'googleLoginEnabled' => $googleLoginEnabled,
        ]);
    }

    /**
     * Handle an incoming registration request.
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    public function store(Request $request): RedirectResponse
    {
        // Check if setting exists, if not, disable by default
        $pinFieldSetting = DB::table('settings')->where('key', 'pin_field_enabled')->first();
        if (!$pinFieldSetting) {
            // Insert default value of disabled for new installations
            DB::table('settings')->insert([
                'key' => 'pin_field_enabled',
                'value' => '0', // Disabled by default
                'created_at' => now(),
                'updated_at' => now()
            ]);
            $pinFieldEnabled = false;
        } else {
            $pinFieldEnabled = $pinFieldSetting->value === '1';
        }

        // Check Turnstile settings
        $turnstileEnabled = DB::table('settings')->where('key', 'turnstile_enabled')->value('value') === '1';
        $turnstileSiteKey = DB::table('settings')->where('key', 'turnstile_site_key')->value('value');
        
        // Check activation required setting
        $activationRequired = DB::table('settings')->where('key', 'activation_required')->value('value') === '1';
        
        $rules = [
            'name' => 'required|string|max:32|unique:users,name',
            'truename' => 'required|string|max:32',
            'email' => 'required|string|lowercase|email|max:64|unique:' . User::class . '|regex:/@gmail\.com$/i',
            'password' => ['required', 'confirmed', \Illuminate\Validation\Rules\Password::defaults()],
        ];

        // Only require Turnstile if it's enabled
        if ($turnstileEnabled && $turnstileSiteKey) {
            $rules['cf-turnstile-response'] = 'required|string';
        }

        if ($pinFieldEnabled) {
            $rules['pin'] = 'required|digits:6';
        }

        $request->validate($rules);

        // Only verify Turnstile if it's enabled
        if ($turnstileEnabled && $turnstileSiteKey && $request->has('cf-turnstile-response')) {
            $turnstileResponse = $request->input('cf-turnstile-response');
            $secretKey = env('TURNSTILE_SECRET_KEY');
            
            $response = Http::post('https://challenges.cloudflare.com/turnstile/v0/siteverify', [
                'secret' => $secretKey,
                'response' => $turnstileResponse,
                'remoteip' => $request->ip(),
            ]);

            if (!$response->json(['success'])) {
                return back()->withErrors([
                    'cf-turnstile-response' => 'CAPTCHA verification failed. Please try again.',
                ])->withInput($request->except(['password', 'password_confirmation']));
            }
        }

        // Use pw.sql adduser stored procedure to create account (handles userid: 1024, 1040, 1056, ...)
        DB::statement(
            'CALL adduser(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
            [
                $request->name,
                PasswordHelper::encryptPassword($request->name, $request->password),
                '',
                '',
                $request->truename,
                '',
                $request->email,
                '',
                '',
                '',
                '',
                '',
                '',
                0,
                '2000-01-01',
                $pinFieldEnabled ? $request->pin : '',
                '',
            ]
        );

        // Fetch the created user and update Laravel-specific columns
        $pwUser = User::where('name', $request->name)->first();

        $updateData = [
            'role' => 'player',
            'is_activated' => !$activationRequired,
        ];

        if ($activationRequired) {
            $updateData['activation_token'] = Str::random(64);
            $updateData['activation_sent_at'] = now();
        }

        User::where('name', $request->name)->update($updateData);

        $user = User::where('name', $request->name)->first();

        event(new Registered($user));

        // If activation is required, send activation email and redirect to pending page
        if ($activationRequired) {
            $activationController = new ActivationController();
            $activationController->sendActivationEmail($user);

            session(['activation_email' => $user->email]);

            return to_route('activation.pending');
        }

        return to_route('login')->with('success', 'Registration successful! Please log in with your credentials.');
    }
}
