<?php
header("Content-Type: application/json");

if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    echo json_encode(["status" => "error", "message" => "Invalid request"]);
    exit;
}

$name     = htmlspecialchars($_POST["name"] ?? "");
$email    = htmlspecialchars($_POST["email"] ?? "");
$phone    = htmlspecialchars($_POST["phone"] ?? "");
$purpose  = htmlspecialchars($_POST["purpose"] ?? "");
$checkin  = htmlspecialchars($_POST["checkin"] ?? "");
$checkout = htmlspecialchars($_POST["checkout"] ?? "");
$message  = htmlspecialchars($_POST["message"] ?? "");

if (!$name || !$email || !$phone || !$checkin || !$checkout) {
    echo json_encode(["status" => "error", "message" => "Missing required fields"]);
    exit;
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo json_encode(["status" => "error", "message" => "Invalid email"]);
    exit;
}

$to      = "chozha05@gmail.com, sevenstonestays@gmail.com";
$subject = "New Contact Form Submission";

$body  = "Name: $name\n";
$body .= "Email: $email\n";
$body .= "Phone: $phone\n";
$body .= "Purpose: $purpose\n";
$body .= "Check-in: $checkin\n";
$body .= "Check-out: $checkout\n";
$body .= "Message: $message\n";

$headers = "From: Seven Stones Stays <no-reply@sevenstonesstays.in>\r\n";
$headers .= "Reply-To: $email\r\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\r\n";

if (mail($to, $subject, $body, $headers)) {
    echo json_encode(["status" => "success"]);
} else {
    echo json_encode(["status" => "error", "message" => "Mail failed"]);
}
