<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Collect and sanitize form data
    $name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
    $visitor_email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
    $email_subject = filter_var($_POST['subject'], FILTER_SANITIZE_STRING);
    $visitor_message = htmlspecialchars($_POST['message']);

    // Check if name is valid
    if (empty($name)) {
        $result = array("status" => "0", "message" => "The name is required.");
        echo json_encode($result);
        exit;
    }

    // Check if email is valid
    if (!$visitor_email) {
        $result = array("status" => "0", "message" => "The email address is invalid.");
        echo json_encode($result);
        exit;
    }

    // Check if subject is valid
    if (empty($email_subject)) {
        $result = array("status" => "0", "message" => "The subject is required.");
        echo json_encode($result);
        exit;
    }

    // Check if visitor message is valid
    if (empty($visitor_message)) {
        $result = array("status" => "0", "message" => "The message is required.");
        echo json_encode($result);
        exit;
    }

    // Recipient email address (your email)
    $to = "aravinthecs@gmail.com";

    // Email headers
    $headers = "From: " . $name . " <" . $visitor_email . ">\r\n";
    $headers .= "Reply-To: " . $visitor_email . "\r\n";
    $headers .= "Content-type: text/plain; charset=UTF-8\r\n"; // Sending as plain text for simplicity

    // Email body
    $email_body = "You have received a new message from your contact form.\n\n";
    $email_body .= "Name: $name\n";
    $email_body .= "Email: $visitor_email\n";
    $email_body .= "Subject: $email_subject\n";
    $email_body .= "Message:\n$visitor_message\n";

    // Send the email
    if (mail($to, $email_subject, $email_body, $headers)) {
        $result = array("status" => "1", "message" => "Thank you for contacting us! Your message has been sent.");
        echo json_encode($result);
        exit;
    } else {
        $result = array("status" => "0", "message" => "Sorry, something went wrong. Please try again later.");
        echo json_encode($result);
        exit;
    }
} else {
    $result = array("status" => "0", "message" => "Access denied.");
    echo json_encode($result);
    exit;  
}
?>