<?php

namespace App\Http\Controllers;

use App\Http\Requests\QuoteRequest;
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 QuoteController extends Controller
{
    public function create()
    {
        return view('pages.quote', [
            'services' => config('brokam.services'),
        ]);
    }

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

        $enquiry = Enquiry::create([
            'type'       => 'rfq',
            'name'       => $data['name'],
            'email'      => $data['email'],
            'phone'      => $data['phone'] ?? null,
            'company'    => $data['company'],
            'country'    => $data['country'] ?? null,
            'service'    => $data['service'],
            'subject'    => 'Request for Quotation — ' . EnquiryRouter::serviceLabel($data['service']),
            'message'    => $data['message'],
            'meta'       => [
                'budget'   => $data['budget'] ?? null,
                'timeline' => $data['timeline'] ?? null,
            ],
            'routed_to'  => $routedTo,
            'ip_address' => $request->ip(),
        ]);

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

        return redirect()
            ->route('quote')
            ->with('status', "Thank you, {$enquiry->name}. Your quote request has been routed to our {$enquiry->service} team — expect a response 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) {
            Log::error('RFQ mail dispatch failed', ['enquiry' => $enquiry->id, 'error' => $e->getMessage()]);
        }
    }
}
