<?php

namespace App\Http\Controllers;

use App\Models\NewsletterSubscriber;
use App\Services\CaptchaService;
use Illuminate\Http\Request;

class NewsletterController extends Controller
{
    public function subscribe(Request $request)
    {
        $captcha = app(CaptchaService::class);
        if ($captcha->shouldVerify(CaptchaService::CONTEXT_NEWSLETTER)) {
            $result = $captcha->verifyRequest($request);
            if (! $result['ok']) {
                return back()->withErrors(['captcha' => $result['error'] ?? 'Captcha invalide.'])->withInput();
            }
        }

        $validated = $request->validate([
            'email' => 'required|email',
            'name' => 'nullable|string|max:255',
        ]);

        $existing = NewsletterSubscriber::where('email', $validated['email'])->first();
        if ($existing) {
            if ($existing->is_active) {
                return back()->with('newsletter_info', 'Vous êtes déjà inscrit à notre newsletter.');
            }
            $existing->update([
                'name' => $validated['name'] ?? $existing->name,
                'is_active' => true,
                'subscribed_at' => now(),
            ]);
        } else {
            NewsletterSubscriber::create([
                'email' => $validated['email'],
                'name' => $validated['name'] ?? null,
                'is_active' => true,
                'subscribed_at' => now(),
            ]);
        }

        return back()->with('newsletter_success', 'Merci ! Vous êtes inscrit à notre newsletter.');
    }
}
