<?php 
// Start session
if (!isset($_SESSION)) session_start();

// Check if form is submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Retrieve form fields
    $name = trim($_POST['name']);
    $email = trim($_POST['email']);
    $phone = trim($_POST['phone']);
    $message = trim($_POST['message']);
    
    // Initialize error variable
    $error = "";

    // Validate form fields
    if (empty($name)) {
        $error .= "Name is required.<br>";
    }
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error .= "A valid email address is required.<br>";
    }
    if (empty($phone) || !preg_match('/^\d{10}$/', $phone)) {
        $error .= "A valid 10-digit phone number is required.<br>";
    }
    if (empty($message)) {
        $error .= "Message is required.<br>";
    }

    // Check for errors
    if (!empty($error)) {
        // Return error message
        echo json_encode([
            'status' => 'error',
            'message' => nl2br($error) // Convert newlines to <br>
        ]);
        exit;
    }

    // Prepare email
    $to = "info@mvsoftware.store"; // Replace with your email address  
    $subject = "New Contact Form Submission - $name"; // Sender's name in subject
    $body = "
        <p><strong>Name:</strong> $name</p>
        <p><strong>Email:</strong> $email</p>
        <p><strong>Phone:</strong> $phone</p>
        <p><strong>Message:</strong><br>" . nl2br(htmlspecialchars($message)) . "</p>
    ";
    $headers = "From: $email\r\n";
    $headers .= "Reply-To: $email\r\n";
    $headers .= "Content-Type: text/html; charset=UTF-8\r\n";

   // Send email
    if (mail($to, $subject, $body, $headers)) {
        // Success response with added color
        echo "<div style='font-size:1.3em; font-weight:bold; color:black;'>
                Thank you for contacting. <br> <br>We'll get back to you within 24 hours.<br> <br>
                For immediate assistance, please call our support helpline number.
              </div>";
    } else {
        // Failure response with color
        echo "<div style='font-size:1.3em; font-weight:bold; color:red;'>
                Failed to send your message. Please try again later.
              </div>";
    }
} else {
    // Deny direct access
    echo json_encode([
        'status' => 'error',
        'message' => "Invalid request."
    ]);
}
?>
