<?php
header('Content-Type: application/json');
// Correctly include the database configuration file.
// The path is relative to the current file's location.
include("config/db.php");

$response = ['status' => 'error', 'message' => 'Invalid request.'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Check for the expected POST variables from a booking form.
    if(isset($_POST['name'], $_POST['phone'], $_POST['boat_type'])){

        $name = $_POST['name'];
        $mobile = $_POST['phone'];
        $boat_type = $_POST['boat_type'];
        $email = $_POST['email'] ?? ''; // Email is optional

        $subject = "New Houseboat Booking Inquiry";
        $message = "A new booking inquiry has been received.\n\n"
                 . "Name: " . htmlspecialchars($name) . "\n"
                 . "Phone: " . htmlspecialchars($mobile) . "\n"
                 . "Email: " . htmlspecialchars($email) . "\n"
                 . "Interested In: " . htmlspecialchars($boat_type) . " Houseboat";

        $sql = "INSERT INTO contact_messages(name, email, mobile, subject, message) VALUES (?, ?, ?, ?, ?)";
        
        $stmt = mysqli_prepare($conn, $sql);
        mysqli_stmt_bind_param($stmt, "sssss", $name, $email, $mobile, $subject, $message);

        if(mysqli_stmt_execute($stmt)){
            $response['status'] = 'success';
            $response['message'] = 'Thank you for your booking inquiry! We will contact you shortly.';
        } else {
            $response['message'] = 'Error: Could not save your inquiry to the database.';
        }
        mysqli_stmt_close($stmt);
    } else {
        $response['message'] = 'Required booking fields are missing.';
    }
}

mysqli_close($conn);
echo json_encode($response);
?>