<?php
include 'includes/db_connection.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Sanitize and validate input
    $customer_name = filter_var($_POST['customer_name'], FILTER_SANITIZE_STRING);
    $phone_number = filter_var($_POST['phone_number'], FILTER_SANITIZE_STRING);
    $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
    $source = "Website";
    $trip_type = filter_var($_POST['trip_type'], FILTER_SANITIZE_STRING);
    $origin = filter_var($_POST['origin'], FILTER_SANITIZE_STRING);
    $destination = filter_var($_POST['destination'], FILTER_SANITIZE_STRING);
    $departure_date = $_POST['departure_date'];
    $return_date = isset($_POST['return_date']) ? $_POST['return_date'] : null;
    $passengers = intval($_POST['passengers']);
    $message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);

    // Basic validation
    if (empty($customer_name) || empty($phone_number) || empty($email)) {
        echo "<script>alert('Please fill in all required fields.'); window.history.back();</script>";
        exit;
    }

    // Insert into database
    $sql = "INSERT INTO leads (customer_name, phone_number, email, source, trip_type, origin, destination, departure_date, return_date, passengers, message)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

    $stmt = $conn->prepare($sql);

    if ($stmt) {
        $stmt->bind_param("sssssssssis", $customer_name, $phone_number, $email, $source, $trip_type, $origin, $destination, $departure_date, $return_date, $passengers, $message);

        if ($stmt->execute()) {
            echo "<script>alert('Thank you! Your request has been submitted successfully. We will contact you shortly.'); window.location.href='index.php';</script>";
        }
        else {
            echo "Error: " . $sql . "<br>" . $conn->error;
        }
        $stmt->close();
    }
    else {
        echo "Error preparing statement: " . $conn->error;
    }

    $conn->close();
}
else {
    header("Location: index.php");
    exit();
}
?>
