<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Setting;
use App\Services\CaptchaService;
use Illuminate\Http\Request;

class CaptchaProtectionController extends Controller
{
    public function __construct(
        protected CaptchaService $captchaService
    ) {}

    public function settings()
    {
        $values = [
            'captcha_provider' => Setting::get('captcha_provider', 'cloudflare'),
            'captcha_site_key' => Setting::get('captcha_site_key', ''),
            'captcha_secret_key' => Setting::get('captcha_secret_key', ''),
            'captcha_google_type' => Setting::get('captcha_google_type', 'v2'),
            'captcha_score_threshold' => Setting::get('captcha_score_threshold', 0.5),
            'captcha_on_contact' => filter_var(Setting::get('captcha_on_contact', '1'), FILTER_VALIDATE_BOOLEAN),
            'captcha_on_reservation' => filter_var(Setting::get('captcha_on_reservation', '1'), FILTER_VALIDATE_BOOLEAN),
            'captcha_on_newsletter' => filter_var(Setting::get('captcha_on_newsletter', '1'), FILTER_VALIDATE_BOOLEAN),
            'captcha_on_checkout' => filter_var(Setting::get('captcha_on_checkout', '1'), FILTER_VALIDATE_BOOLEAN),
        ];

        return view('admin.captcha-protection.settings', [
            'values' => $values,
            'ready' => $this->captchaService->isReady(),
        ]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'captcha_provider' => 'required|in:cloudflare,google',
            'captcha_site_key' => 'nullable|string|max:500',
            'captcha_secret_key' => 'nullable|string|max:500',
            'captcha_google_type' => 'required|in:v2,v3',
            'captcha_score_threshold' => 'nullable|numeric|min:0|max:1',
        ]);

        Setting::set('captcha_provider', $request->captcha_provider, 'captcha');
        Setting::set('captcha_site_key', trim((string) $request->captcha_site_key), 'captcha');
        $newSecret = trim((string) $request->captcha_secret_key);
        if ($newSecret !== '') {
            Setting::set('captcha_secret_key', $newSecret, 'captcha');
        }
        Setting::set('captcha_google_type', $request->captcha_google_type, 'captcha');
        Setting::set('captcha_score_threshold', (string) ($request->captcha_score_threshold ?? 0.5), 'captcha');
        Setting::set('captcha_on_contact', $request->boolean('captcha_on_contact') ? '1' : '0', 'captcha');
        Setting::set('captcha_on_reservation', $request->boolean('captcha_on_reservation') ? '1' : '0', 'captcha');
        Setting::set('captcha_on_newsletter', $request->boolean('captcha_on_newsletter') ? '1' : '0', 'captcha');
        Setting::set('captcha_on_checkout', $request->boolean('captcha_on_checkout') ? '1' : '0', 'captcha');

        return redirect()->route('admin.captcha-protection.settings')->with('success', 'Réglages enregistrés.');
    }
}
