<?php 
require_once 'includes/header.php'; 

$tour_id = filter_input(INPUT_GET, 'tour_id', FILTER_VALIDATE_INT);
if (!$tour_id) {
    die("<div class='container my-5'><div class='alert alert-danger'>Invalid Tour ID.</div></div>");
}

$stmt_tour = $conn->prepare("SELECT id, title, location, price, image_url FROM tours WHERE id = ? AND status = 'published'");
$stmt_tour->bind_param("i", $tour_id);
$stmt_tour->execute();
$tour = $stmt_tour->get_result()->fetch_assoc();
$stmt_tour->close();

if (!$tour) {
    die("<div class='container my-5'><div class='alert alert-warning'>Tour not found.</div></div>");
}
$page_title = 'Book: ' . htmlspecialchars($tour['title']);

$stmt_avail = $conn->prepare("SELECT available_date, slots_available FROM tour_availability WHERE tour_id = ? AND available_date >= CURDATE() AND slots_available > 0 ORDER BY available_date ASC");
$stmt_avail->bind_param("i", $tour_id);
$stmt_avail->execute();
$available_dates = $stmt_avail->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt_avail->close();

$errors = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $booking_date = $_POST['booking_date'] ?? '';
    $num_travelers = filter_input(INPUT_POST, 'num_travelers', FILTER_VALIDATE_INT);
    $full_name = trim($_POST['full_name'] ?? '');
    $email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
    $phone = trim($_POST['phone'] ?? '');

    if (empty($booking_date) || empty($num_travelers) || empty($full_name) || empty($email) || empty($phone)) {
        $errors[] = "Please fill in all required fields.";
    }

    $stmt_check = $conn->prepare("SELECT slots_available FROM tour_availability WHERE tour_id = ? AND available_date = ?");
    $stmt_check->bind_param("is", $tour_id, $booking_date);
    $stmt_check->execute();
    $availability = $stmt_check->get_result()->fetch_assoc();
    $stmt_check->close();

    if (!$availability || $num_travelers > $availability['slots_available']) {
        $errors[] = "Not enough slots available for the selected date.";
    }

    if (empty($errors)) {
        $total_price = $tour['price'] * $num_travelers;
        $booking_ref = 'DXTR-' . date('Ymd') . '-' . strtoupper(bin2hex(random_bytes(3)));
        $user_id_to_save = $_SESSION['user_id'] ?? null;

        $conn->begin_transaction();
        try {
            $stmt_insert = $conn->prepare("INSERT INTO bookings (booking_ref, user_id, tour_id, customer_name, customer_email, customer_phone, booking_date, num_travelers, total_price, payment_status, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'Unpaid', 'Confirmed')");
            $stmt_insert->bind_param("siissssid", $booking_ref, $user_id_to_save, $tour_id, $full_name, $email, $phone, $booking_date, $num_travelers, $total_price);
            $stmt_insert->execute();
            $stmt_insert->close();

            $stmt_update = $conn->prepare("UPDATE tour_availability SET slots_available = slots_available - ? WHERE tour_id = ? AND available_date = ?");
            $stmt_update->bind_param("iis", $num_travelers, $tour_id, $booking_date);
            $stmt_update->execute();
            $stmt_update->close();

            // --- Send Booking Confirmation Email ---
            $subject = "Your Booking is Reserved! (Ref: " . $booking_ref . ")";
            $body = "<h1>Booking Reserved</h1><p>Hello " . htmlspecialchars($full_name) . ",</p><p>Thank you for your booking. Here are your details:</p><ul><li><strong>Reference:</strong> " . $booking_ref . "</li><li><strong>Tour:</strong> " . htmlspecialchars($tour['title']) . "</li><li><strong>Date:</strong> " . date('F j, Y', strtotime($booking_date)) . "</li><li><strong>Travelers:</strong> " . $num_travelers . "</li><li><strong>Total Amount Due:</strong> " . format_price($total_price) . "</li></ul><p>You can complete your payment by visiting the confirmation page on our website.</p>";
            send_email($email, $subject, $body, $full_name);

            $conn->commit();
            header("Location: confirmation.php?booking_ref=" . $booking_ref);
            exit();
        } catch (mysqli_sql_exception $exception) {
            $conn->rollback();
            $errors[] = "A database error occurred. Please try again.";
        }
    }
}
?>
