<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\CaptchaSetting;
use App\Models\CaptchaStatistic;
use App\Models\CaptchaRateLimit;
use App\Services\Captcha\CaptchaService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class CaptchaController extends Controller
{
    protected CaptchaService $captchaService;

    public function __construct(CaptchaService $captchaService)
    {
        $this->captchaService = $captchaService;
    }

    /**
     * Display CAPTCHA settings
     */
    public function index()
    {
        $settings = CaptchaSetting::first() ?? new CaptchaSetting();
        $providers = CaptchaSetting::getProviderOptions();
        $locations = CaptchaSetting::getLocationOptions();

        // Get statistics
        $stats = $this->captchaService->getStatistics(7);
        $blockedCount = CaptchaRateLimit::getBlockedCount();

        return view('admin.captcha.index', compact('settings', 'providers', 'locations', 'stats', 'blockedCount'));
    }

    /**
     * Update CAPTCHA settings
     */
    public function update(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'provider' => 'required|in:hcaptcha,recaptcha_v2,recaptcha_v2_invisible,recaptcha_v3,turnstile,trustip',
            'enabled' => 'boolean',
            'site_key' => 'nullable|string|max:255',
            'secret_key' => 'nullable|string|max:255',
            'api_key' => 'nullable|string|max:255',
            'recaptcha_v3_threshold' => 'nullable|numeric|min:0|max:1',
            'enabled_login' => 'boolean',
            'enabled_register' => 'boolean',
            'enabled_forgot_password' => 'boolean',
            'enabled_contact' => 'boolean',
            'enabled_api' => 'boolean',
            'whitelist_ips' => 'nullable|string',
            'testing_mode' => 'boolean',
            'fallback_provider' => 'nullable|in:none,hcaptcha,recaptcha_v2,recaptcha_v2_invisible,recaptcha_v3,turnstile,trustip',
            'fallback_site_key' => 'nullable|string|max:255',
            'fallback_secret_key' => 'nullable|string|max:255',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        $data = $validator->validated();

        // Process whitelist IPs
        if (isset($data['whitelist_ips'])) {
            $ips = array_map('trim', explode(',', $data['whitelist_ips']));
            $data['whitelist_ips'] = array_filter($ips);
        }

        $settings = CaptchaSetting::first();

        if ($settings) {
            $settings->update($data);
        } else {
            $settings = CaptchaSetting::create($data);
        }

        // Clear cache
        $this->captchaService->clearCache();

        return redirect()->route('admin.captcha.index')
            ->with('success', 'CAPTCHA settings updated successfully!');
    }

    /**
     * Test CAPTCHA configuration
     */
    public function test(Request $request)
    {
        $provider = $request->input('provider');
        $siteKey = $request->input('site_key');
        $secretKey = $request->input('secret_key');
        $apiKey = $request->input('api_key');

        try {
            $config = [
                'site_key' => $siteKey,
                'secret_key' => $secretKey,
                'api_key' => $apiKey,
            ];

            $providerInstance = \App\Services\Captcha\CaptchaFactory::make($provider, $config);

            if (!$providerInstance->isConfigured()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Provider is not properly configured. Please check your keys.',
                ]);
            }

            return response()->json([
                'success' => true,
                'message' => 'Configuration looks good! Provider is ready to use.',
                'provider' => $providerInstance->getName(),
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error: ' . $e->getMessage(),
            ]);
        }
    }

    /**
     * Get statistics
     */
    public function statistics(Request $request)
    {
        $days = $request->input('days', 7);

        $stats = $this->captchaService->getStatistics($days);
        $locationStats = CaptchaStatistic::getLocationStats($days);

        return response()->json([
            'success' => true,
            'statistics' => $stats,
            'location_stats' => $locationStats,
        ]);
    }

    /**
     * Clear rate limits
     */
    public function clearRateLimits()
    {
        CaptchaRateLimit::truncate();

        return redirect()->route('admin.captcha.index')
            ->with('success', 'All rate limits have been cleared!');
    }

    /**
     * Clean old statistics
     */
    public function cleanStatistics(Request $request)
    {
        $days = $request->input('days', 90);
        $deleted = CaptchaStatistic::cleanOldRecords($days);

        return redirect()->route('admin.captcha.index')
            ->with('success', "Deleted {$deleted} old statistics records!");
    }
}
