<?php

namespace App\Http\Controllers;

use App\Http\Requests\ContactRequest;
use App\Mail\EnquiryConfirmation;
use App\Mail\EnquiryReceived;
use App\Models\Enquiry;
use App\Support\EnquiryRouter;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;

class ContactController extends Controller
{
    public function create()
    {
        return view('pages.contact', [
            'services' => config('brokam.services'),
        ]);
    }

    public function store(ContactRequest $request)
    {
        $data = $request->validated();
        $routedTo = EnquiryRouter::mailbox($data['service'] ?? null);

        $enquiry = Enquiry::create([
            'type'       => 'contact',
            'name'       => $data['name'],
            'email'      => $data['email'],
            'phone'      => $data['phone'] ?? null,
            'company'    => $data['company'] ?? null,
            'country'    => $data['country'] ?? null,
            'service'    => $data['service'] ?? null,
            'subject'    => $data['subject'] ?? null,
            'message'    => $data['message'],
            'routed_to'  => $routedTo,
            'ip_address' => $request->ip(),
        ]);

        $this->dispatchMail($enquiry, $routedTo);

        return redirect()
            ->route('contact')
            ->with('status', "Thank you, {$enquiry->name}. Your message has reached our team and we'll be in touch shortly.");
    }

    private function dispatchMail(Enquiry $enquiry, string $routedTo): void
    {
        try {
            Mail::to($routedTo)->send(new EnquiryReceived($enquiry));
            Mail::to($enquiry->email)->send(new EnquiryConfirmation($enquiry));
        } catch (\Throwable $e) {
            // Never lose the enquiry over a transient mail failure — it is persisted.
            Log::error('Enquiry mail dispatch failed', ['enquiry' => $enquiry->id, 'error' => $e->getMessage()]);
        }
    }
}
