<?php

namespace App\Http\Controllers\Public;

use App\Http\Controllers\Controller;
use App\Models\RgpdRequest;
use App\Mail\RgpdRequestNotification;
use App\Services\TurnstileService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;

class RgpdController extends Controller
{
    public function show()
    {
        return view('public.rgpd', [
            'tipos' => RgpdRequest::TIPOS,
            'turnstile_key' => config('services.turnstile.site_key'),
        ]);
    }

    public function submit(Request $request)
    {
        if (!TurnstileService::verify($request->input('cf-turnstile-response'))) {
            return back()->withErrors(['captcha' => 'Verificação de segurança falhou.'])->withInput();
        }

        $validated = $request->validate([
            'nome_completo' => 'required|string|max:255',
            'email' => 'required|email|max:255',
            'nif' => 'nullable|string|max:9',
            'tipo_pedido' => 'required|in:' . implode(',', array_keys(RgpdRequest::TIPOS)),
            'descricao' => 'required|string|max:2000',
        ]);

        $rgpdRequest = RgpdRequest::create($validated);

        // Notificar RH
        try {
            $rhEmail = env('MAIL_FROM_ADDRESS', 'noreply@segunor.pt');
            Mail::to($rhEmail)->send(new RgpdRequestNotification($rgpdRequest));
        } catch (\Exception $e) {
            \Log::warning('Failed to send RGPD notification: ' . $e->getMessage());
        }

        return redirect()->route('rgpd.success');
    }

    public function success()
    {
        return view('public.rgpd-success');
    }

    public function legal()
    {
        return view('public.legal');
    }
}
