<?php
// Only accept POST requests
if ($_SERVER["REQUEST_METHOD"] != "POST") {
    http_response_code(405); // Method Not Allowed
    echo json_encode(["status" => "error", "message" => "Invalid request method"]);
    exit;
}

// Get POST data and sanitize
$fname   = trim(filter_input(INPUT_POST, 'fname', FILTER_SANITIZE_STRING));
$lname   = trim(filter_input(INPUT_POST, 'lname', FILTER_SANITIZE_STRING));
$email   = trim(filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL));
$phone   = trim(filter_input(INPUT_POST, 'phone', FILTER_SANITIZE_STRING));
$message = trim(filter_input(INPUT_POST, 'message', FILTER_SANITIZE_STRING));

// Validate required fields
if (!$fname || !$lname || !$email || !$phone || !$message) {
    http_response_code(400); // Bad Request
    echo json_encode(["status" => "error", "message" => "All fields are required."]);
    exit;
}

// Recipient email
$to = "info@esmnation.org"; // CHANGE THIS to your email
$subject = "New Contact Form Message from $fname $lname";
$body = "Name: $fname $lname\n";
$body .= "Email: $email\n";
$body .= "Phone: $phone\n\n";
$body .= "Message:\n$message";
$headers = "From: $email\r\n";
$headers .= "Reply-To: $email\r\n";

// Send email
if (mail($to, $subject, $body, $headers)) {
    echo json_encode(["status" => "success", "message" => "Message was sent successfully!"]);
} else {
    http_response_code(500); // Internal Server Error
    echo json_encode(["status" => "error", "message" => "Failed to send message. Try again later."]);
}
?>
