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

header('Content-Type: application/json');

// Test the table update logic
$bookingId = isset($_GET['booking_id']) ? (int)$_GET['booking_id'] : 0;

if ($bookingId === 0) {
    echo json_encode([
        'success' => false,
        'message' => 'Booking ID required'
    ]);
    exit;
}

// Get booking with table info
$sql = "SELECT b.id, b.name, b.email, b.table_id, rt.table_number, rt.status as table_status
        FROM bookings b
        LEFT JOIN restaurant_tables rt ON b.table_id = rt.id
        WHERE b.id = ?";

$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $bookingId);
$stmt->execute();
$result = $stmt->get_result();
$booking = $result->fetch_assoc();
$stmt->close();

if (!$booking) {
    echo json_encode([
        'success' => false,
        'message' => 'Booking not found'
    ]);
    exit;
}

echo json_encode([
    'success' => true,
    'booking_id' => $booking['id'],
    'booking_name' => $booking['name'],
    'table_id' => $booking['table_id'],
    'table_number' => $booking['table_number'],
    'current_table_status' => $booking['table_status'],
    'message' => 'Booking details retrieved'
]);

if (!empty($booking['table_id'])) {
    // Try to update
    $updateSql = "UPDATE restaurant_tables SET status = 'booked' WHERE id = ?";
    $updateStmt = $conn->prepare($updateSql);
    
    if ($updateStmt === false) {
        error_log("Prepare failed: " . $conn->error);
    } else {
        $updateStmt->bind_param("i", $booking['table_id']);
        if ($updateStmt->execute()) {
            error_log("Table updated successfully");
        } else {
            error_log("Execute failed: " . $updateStmt->error);
        }
        $updateStmt->close();
    }
    
    // Check new status
    $checkSql = "SELECT status FROM restaurant_tables WHERE id = ?";
    $checkStmt = $conn->prepare($checkSql);
    $checkStmt->bind_param("i", $booking['table_id']);
    $checkStmt->execute();
    $checkResult = $checkStmt->get_result();
    $tableCheck = $checkResult->fetch_assoc();
    $checkStmt->close();
    
    error_log("Table ID: {$booking['table_id']}, New Status: {$tableCheck['status']}");
}
?>
