<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreEnquiryRequest;
use App\Mail\EnquiryReceived;
use App\Models\Enquiry;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Throwable;

class EnquiryController extends Controller
{
    public function store(StoreEnquiryRequest $request): RedirectResponse
    {
        $enquiry = Enquiry::create([
            ...$request->safe()->except('website'),
            'status' => 'new',
        ]);

        try {
            Mail::to(config('sarvoknit.enquiry_email'))->send(new EnquiryReceived($enquiry));
        } catch (Throwable $exception) {
            Log::warning('Enquiry saved but notification email could not be sent.', [
                'enquiry_id' => $enquiry->id,
                'exception' => $exception->getMessage(),
            ]);
        }

        return to_route('enquiries.thank-you')->with('success', 'Thank you. Your enquiry has been received.');
    }
}
