<?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');
}

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

// Insert booking
$stmt = $conn->prepare("INSERT INTO bookings (user_id, name, email, phone, booking_date, booking_time, guests, occasion, 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();
?>
