<?php

namespace App\Http\Controllers;

use App\Mail\ContactMessageNotification;
use App\Models\ContactMessage;
use App\Services\CaptchaService;
use App\Services\MailService;
use Illuminate\Http\Request;

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

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

        $message = ContactMessage::create($validated);

        $mailService = app(MailService::class);
        if ($mailService->isConfigured()) {
            foreach ($mailService->getNotificationRecipientEmails() as $recipientEmail) {
                $mailService->send(new ContactMessageNotification($message, $recipientEmail));
            }
        }

        return back()->with('contact_success', 'Votre message a bien été envoyé. Nous vous répondrons rapidement.');
    }
}
