<?php

namespace App\Http\Controllers;

use App\Models\ContactMessage;
use App\Mail\ContactConfirmation;
use App\Mail\ContactNotification;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Log;

class ContactController extends Controller
{
    /**
     * Store a new contact message.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|max:255',
            'phone' => 'nullable|string|max:20',
            'subject' => 'nullable|string|max:255',
            'message' => 'required|string',
        ]);

        $contactMessage = ContactMessage::create($validated);

        try {
            // Send email to User
            Mail::to($contactMessage->email)->send(new ContactConfirmation($contactMessage));

            // Send email to Admin
            // Admin email is the one sending the emails, or we can use a specific admin email.
            // Using the FROM address or a specific admin address.
            // User requested: "to admin from email info@rapiddropcourierlog.co.uk"
            // So we send TO info@rapiddropcourierlog.co.uk FROM info@rapiddropcourierlog.co.uk?
            // Usually we send TO the admin email.
            $adminEmail = config('mail.from.address'); 
            if ($adminEmail) {
                Mail::to($adminEmail)->send(new ContactNotification($contactMessage));
            }
        } catch (\Exception $e) {
            Log::error('Failed to send contact emails: ' . $e->getMessage());
            // We still return success as the message is saved
        }

        return response()->json([
            'success' => true,
            'message' => 'Message sent successfully',
            'data' => $contactMessage
        ], 201);
    }
}
