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

if (!isLoggedIn()) {
    redirect(BASE_URL . 'login.php');
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    redirect(BASE_URL . 'packages.php');
}

$packageId = intval($_POST['package_id'] ?? 0);
$travelDate = sanitize($_POST['travel_date'] ?? '');
$numPeople = intval($_POST['num_people'] ?? 1);
$specialRequests = sanitize($_POST['special_requests'] ?? '');
$totalAmount = floatval($_POST['total_amount'] ?? 0);

// Validate
$db = getDBConnection();
$stmt = $db->prepare("SELECT * FROM packages WHERE id = ? AND status = 'active'");
$stmt->execute([$packageId]);
$package = $stmt->fetch();

if (!$package) {
    setFlash('danger', 'Invalid package selected.');
    redirect(BASE_URL . 'packages.php');
}

$effectivePrice = $package['offer_price'] ?: $package['price_per_person'];
$calculatedTotal = $effectivePrice * $numPeople;
$discount = ($package['price_per_person'] - $effectivePrice) * $numPeople;

// Generate booking ID
$bookingId = generateBookingId();

try {
    $stmt = $db->prepare("
        INSERT INTO bookings (booking_id, user_id, package_id, num_people, travel_date, total_amount, discount_amount, final_amount, special_requests, status, payment_status)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', 'pending')
    ");
    $stmt->execute([
        $bookingId,
        $_SESSION['user_id'],
        $packageId,
        $numPeople,
        $travelDate,
        $package['price_per_person'] * $numPeople,
        $discount,
        $calculatedTotal,
        $specialRequests
    ]);
    
    $newBookingId = $db->lastInsertId();
    logActivity($_SESSION['user_id'], 'booking_created', "Booking $bookingId created for " . $package['title']);
    
    // Redirect to payment page
    setFlash('success', 'Booking created successfully! Please complete the payment.');
    redirect(BASE_URL . 'payment.php?booking=' . $newBookingId);
    
} catch (Exception $e) {
    setFlash('danger', 'Booking failed. Please try again.');
    redirect(BASE_URL . 'package.php?slug=' . $package['slug']);
}
