<?php

namespace App\Http\Controllers;

use App\Mail\ContactFormMail;
use App\Models\ContactSubmission;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;

class ContactController extends Controller
{
    public function submit(Request $request)
    {
        $validated = $request->validate([
            'name'     => 'required|string|max:100',
            'email'    => 'required|email|max:150',
            'phone'    => 'nullable|string|max:30',
            'subject'  => 'required|string|in:sales,support,onboarding,billing,partnership,other',
            'business' => 'nullable|string|max:150',
            'message'  => 'required|string|min:10|max:3000',
        ]);

        $subjectLabels = [
            'sales'       => 'Sales Enquiry / Pricing',
            'support'     => 'Technical Support',
            'onboarding'  => 'Onboarding Help',
            'billing'     => 'Billing & Subscription',
            'partnership' => 'Partnership / Reseller',
            'other'       => 'Other',
        ];

        $recipient = config('mail.contact_address', config('mail.from.address'));

        // Persist to database
        ContactSubmission::create([
            'name'        => $validated['name'],
            'email'       => $validated['email'],
            'phone'       => $validated['phone'] ?? null,
            'business'    => $validated['business'] ?? null,
            'subject'     => $subjectLabels[$validated['subject']],
            'subject_key' => $validated['subject'],
            'message'     => $validated['message'],
            'status'      => 'new',
        ]);

        // Send email notification
        try {
            Mail::to($recipient)->send(new ContactFormMail(
                senderName:  $validated['name'],
                senderEmail: $validated['email'],
                subject:     $subjectLabels[$validated['subject']],
                body:        $validated['message'],
                phone:       $validated['phone'] ?? '',
                business:    $validated['business'] ?? '',
            ));
        } catch (\Throwable) {
            // Submission already saved; email failure is non-fatal
        }

        return response()->json(['message' => 'Your message has been sent successfully.']);
    }
}
