<?php

namespace App\Http\Controllers;

use App\Mail\LeadNotification;
use App\Models\Lead;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;

class LeadController extends Controller
{
    public function store(Request $request)
    {
        $validated = $request->validate([
            'full_name' => ['required', 'string', 'max:255'],
            'phone' => ['required', 'regex:/^\+?[0-9]{7,15}$/'],
            'cod_fiscal' => ['required', 'digits:13'],
            'email' => ['nullable', 'email', 'max:255'],
            'message' => ['nullable', 'string'],
        ], [
            'full_name.required' => __('home.validation.full_name.required'),
            'full_name.max' => __('home.validation.full_name.max'),
            'phone.required' => __('home.validation.phone.required'),
            'phone.regex' => __('home.validation.phone.regex'),
            'cod_fiscal.required' => __('home.validation.cod_fiscal.required'),
            'cod_fiscal.digits' => __('home.validation.cod_fiscal.digits'),
            'email.email' => __('home.validation.email.email'),
            'email.max' => __('home.validation.email.max'),
            'message.string' => __('home.validation.message.string'),
        ]);

        $lead = Lead::create($validated);
        try {
            Mail::to('contact@radiere-srl.md')->send(new LeadNotification($lead));
        } catch (\Throwable $error) {
            report($error);
        }

        $locale = $request->route('locale') ?? app()->getLocale();
        $thankYouUrl = route('thank-you', ['locale' => $locale]);

        if ($request->expectsJson()) {
            return response()->json([
                'message' => __('home.form.success_message'),
                'redirect' => $thankYouUrl,
            ]);
        }

        return redirect($thankYouUrl);
    }
}
