<?php

namespace App\Http\Controllers;

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

class ContactController extends Controller
{
    public function sendEmail(Request $request)
    {           
        // 1. Validation
        $validatedData = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|max:255',
            'service' => 'required|string|max:255', 
            'phone_number' => 'nullable|string|max:255',
            'consultation_mode' => 'nullable|string|max:255',
            'company_name' => 'nullable|string|max:255',
            'country' => 'nullable|string|max:255',
            'message_text' => 'required|string',
            'g-recaptcha-response' => 'required|captcha',
        ]);        
        
        // 2. Mail Dispatch
        try {
            //$recipientEmail = 'info@dxpassociates.com'; 
            $mailData = $validatedData;
            $recipientEmail = 'info@dxpassociates.com'; 
            
            Mail::to($recipientEmail)->send(new ContactMail($mailData));
            
            // 3. Redirection
            return back()->with('success', 'Your message has been sent successfully!');
        } catch (\Exception $e) {
            $e->getMessage();
            // Log the error for debugging
            \Log::error("Mail sending failed: " . $e->getMessage()); 
            
            return back()->with('error', 'There was an issue sending your message. Please try again.');
        }
    }
}
