<?php
session_start();
include 'config.php';

// Release any expired bookings first
releaseExpiredBookings($conn);

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendResponse(false, 'Invalid request method');
}

$rawInput = file_get_contents("php://input");
$data = json_decode($rawInput, true);

error_log("Booking request received: " . print_r($data, true));

// Validate required fields
$required = ['booking_name', 'booking_email', 'booking_phone', 'booking_date', 'booking_time', 'booking_guests'];
foreach ($required as $field) {
    if (!isset($data[$field]) || empty($data[$field])) {
        sendResponse(false, ucfirst(str_replace('_', ' ', $field)) . ' is required');
    }
}

$userId = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : null;
$name = trim($data['booking_name']);
$email = trim($data['booking_email']);
$phone = trim($data['booking_phone']);
$bookingDate = $data['booking_date'];
$bookingTime = $data['booking_time'];
$guests = (int)$data['booking_guests'];
$occasion = isset($data['booking_occasion']) && !empty($data['booking_occasion']) ? trim($data['booking_occasion']) : null;
$tableType = isset($data['booking_table_type']) && !empty($data['booking_table_type']) ? trim($data['booking_table_type']) : null;
$dietaryNeeds = isset($data['booking_dietary']) && !empty($data['booking_dietary']) ? trim($data['booking_dietary']) : null;
$specialRequests = isset($data['booking_special_requests']) && !empty($data['booking_special_requests']) ? trim($data['booking_special_requests']) : null;

// Validate email
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    sendResponse(false, 'Invalid email format');
}

// Validate phone
if (!preg_match('/^[0-9+\-\s()]+$/', $phone) || strlen(preg_replace('/[^0-9]/', '', $phone)) < 10) {
    sendResponse(false, 'Invalid phone number');
}

// Validate date (must be today or in future)
$bookingDateTime = strtotime($bookingDate . ' ' . $bookingTime);
$now = strtotime('now');
$today = strtotime('today');

if ($bookingDateTime < $today) {
    sendResponse(false, 'Booking date and time must be in the future');
}

// Validate guests
if ($guests < 1 || $guests > 100) {
    sendResponse(false, 'Number of guests must be between 1 and 100');
}

// Validate slot capacity (prevent overbooking)
if (!empty($occasion)) {
    $capacitySql = "SELECT ts.max_capacity
                    FROM time_slots ts
                    INNER JOIN meal_types mt ON ts.meal_type_id = mt.id
                    WHERE ts.status = 'active'
                    AND LOWER(TRIM(mt.name)) = LOWER(TRIM(?))
                    AND TIME(ts.start_time) = TIME(?)
                    LIMIT 1";
    $capacityStmt = $conn->prepare($capacitySql);

    if ($capacityStmt) {
        $capacityStmt->bind_param("ss", $occasion, $bookingTime);
        $capacityStmt->execute();
        $capacityResult = $capacityStmt->get_result();
        $slotConfig = $capacityResult ? $capacityResult->fetch_assoc() : null;
        $capacityStmt->close();

        if ($slotConfig) {
            $maxCapacity = (int)$slotConfig['max_capacity'];

            $countSql = "SELECT COUNT(*) AS booked_count
                         FROM bookings
                         WHERE booking_date = ?
                         AND TIME(slot_time) = TIME(?)
                         AND LOWER(TRIM(meal_type)) = LOWER(TRIM(?))
                         AND LOWER(TRIM(status)) IN ('pending', 'confirmed', 'checked_in')";
            $countStmt = $conn->prepare($countSql);

            if ($countStmt) {
                $countStmt->bind_param("sss", $bookingDate, $bookingTime, $occasion);
                $countStmt->execute();
                $countResult = $countStmt->get_result();
                $bookedCount = (int)($countResult->fetch_assoc()['booked_count'] ?? 0);
                $countStmt->close();

                if ($bookedCount >= $maxCapacity) {
                    sendResponse(false, 'Selected slot is filled. Please choose another time slot.');
                }
            }
        }
    }
}

error_log("Booking validation passed. Inserting into database...");

// Insert booking
$stmt = $conn->prepare("INSERT INTO bookings (user_id, name, email, phone, booking_date, slot_time, guests, meal_type, table_type, dietary_needs, special_requests) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

if (!$stmt) {
    error_log("Prepare failed: " . $conn->error);
    sendResponse(false, 'Database error: ' . $conn->error);
}

$stmt->bind_param(
    "isssssissss",
    $userId,
    $name,
    $email,
    $phone,
    $bookingDate,
    $bookingTime,
    $guests,
    $occasion,
    $tableType,
    $dietaryNeeds,
    $specialRequests
);

if ($stmt->execute()) {
    $bookingId = $conn->insert_id;
    
    error_log("Booking created successfully with ID: " . $bookingId);
    
    // Send confirmation email (optional - implement email sending)
    // sendConfirmationEmail($email, $name, $bookingDate, $bookingTime, $guests);
    
    sendResponse(true, 'Booking confirmed successfully', [
        'booking_id' => $bookingId,
        'booking_date' => $bookingDate,
        'booking_time' => $bookingTime,
        'guests' => $guests,
        'confirmation_message' => "Your table for $guests guest(s) is booked for $bookingDate at $bookingTime. Confirmation details have been sent to $email."
    ]);
} else {
    error_log("Execute failed: " . $stmt->error);
    sendResponse(false, 'Error creating booking: ' . $stmt->error);
}

$stmt->close();
$conn->close();
?>
