<?php

namespace App\Http\Controllers;

use App\Mail\ContactSubmitMail;
use Illuminate\Support\Facades\Mail;
use Illuminate\Http\Request;

class ContactController extends Controller
{
    public function submit(Request $request){
        try{
            $validated = $request->validate([
                'name' => 'required|string|max:255',
                'email' => 'required|email|max:255',
                'message' => 'required|string|max:5000',
                'phone' => 'nullable|string|max:20',
            ]);

            $data = [
                'name' => $validated['name'],
                'email' => $validated['email'],
                'message' => $validated['message'],
                'phone' => $validated['phone'] ?? null,
            ];

            Mail::to(env('MAIL_TO_ADDRESS'))->send(new ContactSubmitMail($data));

            return redirect()->back()->with('success', 'Your message has been sent successfully! We will get back to you soon.');


        } catch (\Exception $e) {
            return response()->json([
                'error' => 'An error occurred while submitting your message.',
                'message' => $e->getMessage()
            ], 500);
        }
    }
}
