<?php
// This is a logic-only file. It processes the booking form and redirects.
require_once 'includes/db.php';
require_once 'includes/email-sender.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header("Location: index.php");
    exit();
}

// --- DATA COLLECTION AND SANITIZATION ---
$user_id = isset($_SESSION['user_id']) ? intval($_SESSION['user_id']) : null;
$tour_id = intval($_POST['tour_id']);
$customer_title = trim(strip_tags($_POST['customer_title']));
$customer_name = trim(strip_tags($_POST['customer_name']));
$customer_suffix = trim(strip_tags($_POST['customer_suffix']));
$customer_email = trim(filter_var($_POST['customer_email'], FILTER_SANITIZE_EMAIL));
$customer_phone = trim(strip_tags($_POST['customer_phone']));
$booking_date = $_POST['booking_date'];
$num_travelers = intval($_POST['num_travelers']);

// --- SERVER-SIDE VALIDATION ---
if (empty($customer_name) || !filter_var($customer_email, FILTER_VALIDATE_EMAIL) || empty($booking_date) || $num_travelers <= 0 || $tour_id <= 0) {
    header("Location: service-details.php?id=$tour_id&error=invalid_input");
    exit();
}

// --- DATABASE TRANSACTION FOR BOOKING ---
$conn->begin_transaction();
try {
    // 1. Fetch tour/service details from the database to prevent manipulation.
    $stmt_item = $conn->prepare("SELECT title, price, category FROM tours WHERE id = ?");
    $stmt_item->bind_param("i", $tour_id);
    $stmt_item->execute();
    $item = $stmt_item->get_result()->fetch_assoc();
    if (!$item) { throw new Exception("Item not found."); }
    $total_price = floatval($item['price']) * $num_travelers;
    $item_title = $item['title'];

    // 2. For tours, check for available slots and lock the row to prevent race conditions.
    if ($item['category'] == 'Tour') {
        $stmt_check = $conn->prepare("SELECT slots_available FROM tour_availability WHERE tour_id = ? AND available_date = ? FOR UPDATE");
        $stmt_check->bind_param("is", $tour_id, $booking_date);
        $stmt_check->execute();
        $availability = $stmt_check->get_result()->fetch_assoc();

        if (!$availability || $availability['slots_available'] < $num_travelers) {
            throw new Exception('Not enough slots available for the selected date.');
        }

        // 3. If slots are available, deduct the booked slots.
        $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();
    }

    // 4. Insert the final booking record.
    $stmt_insert = $conn->prepare("INSERT INTO bookings (user_id, tour_id, customer_title, customer_name, customer_suffix, customer_email, customer_phone, booking_date, num_travelers, total_price) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt_insert->bind_param("iissssssid", $user_id, $tour_id, $customer_title, $customer_name, $customer_suffix, $customer_email, $customer_phone, $booking_date, $num_travelers, $total_price);
    $stmt_insert->execute();
    $booking_id = $stmt_insert->insert_id;

    // If all queries succeed, commit the transaction.
    $conn->commit();

    // 5. Send notification email to admin AFTER a successful commit.
    $subject = "New " . $item['category'] . " Booking (#" . $booking_id . ")";
    $message_body = "A new booking has been made by <strong>" . htmlspecialchars($customer_name) . "</strong> for " . htmlspecialchars($item_title) . ".";
    sendAdminNotification($conn, $subject, $message_body);
    
    // Redirect to the appropriate success page.
    if ($user_id) {
        header("Location: dashboard/my-tour-bookings.php?booking=success");
    } else {
        header("Location: confirmation.php?status=success");
    }
    exit();

} catch (Exception $e) {
    // If any step fails, roll back all database changes.
    $conn->rollback();
    $error_reason = ($e->getMessage() === 'Not enough slots available for the selected date.') ? 'fully_booked' : 'db_error';
    header("Location: service-details.php?id=$tour_id&error=$error_reason");
    exit();
}
?>
