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

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

// Keep table statuses fresh before any listing/action.
releaseExpiredBookings($conn);

$method = $_SERVER['REQUEST_METHOD'];
$action = isset($_GET['action']) ? $_GET['action'] : '';

switch ($action) {
    case 'list':
        listOnlineTables();
        break;
    case 'create':
        createOnlineTable();
        break;
    case 'update':
        updateOnlineTable();
        break;
    case 'delete':
        deleteOnlineTable();
        break;
    case 'get':
        getOnlineTable();
        break;
    case 'get_availability':
        getTableAvailability();
        break;
    case 'allocate_to_booking':
        allocateTableToBooking();
        break;
    case 'release_table':
        releaseTable();
        break;
    case 'release_by_table':
        releaseOnlineTableByContext();
        break;
    case 'assign_server':
        assignServerToOnlineTable();
        break;
    case 'get_sections':
        getSections();
        break;
    case 'get_by_capacity':
        getTablesByCapacity();
        break;
    case 'update_capacity':
        updateTableCapacity();
        break;
    default:
        sendResponse(false, 'Invalid action', null);
}

function hasTableColumn($table, $column) {
    global $conn;
    $tableEsc = $conn->real_escape_string($table);
    $columnEsc = $conn->real_escape_string($column);
    $res = $conn->query("SHOW COLUMNS FROM `" . $tableEsc . "` LIKE '" . $columnEsc . "'");
    return ($res && $res->num_rows > 0);
}

function ensureServerOrderLimitColumn() {
    global $conn;
    if (!hasTableColumn('servers', 'max_active_orders')) {
        @$conn->query("ALTER TABLE servers ADD COLUMN max_active_orders INT NOT NULL DEFAULT 1 AFTER shift_end");
    }
}

function getServerLoad($server_id) {
    global $conn;

    ensureServerOrderLimitColumn();
    $server_id = intval($server_id);

    $server_res = $conn->query("SELECT COALESCE(max_active_orders, 1) AS max_active_orders, status FROM servers WHERE id = " . $server_id . " LIMIT 1");
    if (!$server_res || $server_res->num_rows === 0) {
        return null;
    }
    $server = $server_res->fetch_assoc();

    $direct_res = $conn->query("SELECT COUNT(*) AS c FROM table_assignments WHERE server_id = " . $server_id . " AND status = 'assigned'");
    $direct_count = $direct_res ? intval($direct_res->fetch_assoc()['c'] ?? 0) : 0;

    $online_count = 0;
    if (hasTableColumn('online_table_bookings', 'assigned_server_id')) {
        $online_res = $conn->query("SELECT COUNT(*) AS c
                                    FROM online_table_bookings otb
                                    LEFT JOIN bookings b ON b.id = otb.booking_id
                                    WHERE otb.assigned_server_id = " . $server_id . "
                                    AND otb.allocation_status = 'allocated'
                                    AND (b.id IS NULL OR b.status IN ('pending', 'confirmed', 'checked_in'))");
        $online_count = $online_res ? intval($online_res->fetch_assoc()['c'] ?? 0) : 0;
    }

    return [
        'status' => strtolower(trim((string)($server['status'] ?? 'available'))),
        'max_active_orders' => max(1, intval($server['max_active_orders'] ?? 1)),
        'active_count' => $direct_count + $online_count
    ];
}

// List all online tables with filters
function listOnlineTables() {
    global $conn;
    ensureOnlineBookingServerColumns();
    
    $floor = isset($_GET['floor']) ? $_GET['floor'] : '';
    $section = isset($_GET['section']) ? $_GET['section'] : '';
    $status = isset($_GET['status']) ? $_GET['status'] : '';
    $date = isset($_GET['date']) ? $_GET['date'] : '';
    $table_type = isset($_GET['table_type']) ? $_GET['table_type'] : '';
    $meal_type = isset($_GET['meal_type']) ? trim($_GET['meal_type']) : '';
    $slot_time = isset($_GET['slot_time']) ? trim($_GET['slot_time']) : '';
    
    $sql = "SELECT * FROM online_tables WHERE 1=1";
    
    if ($floor) {
        $sql .= " AND floor_level = " . intval($floor);
    }
    if ($section) {
        $sql .= " AND section = '" . $conn->real_escape_string($section) . "'";
    }
    if (!$date && $status) {
        $sql .= " AND status = '" . $conn->real_escape_string($status) . "'";
    }
    if ($table_type) {
        $sql .= " AND table_type = '" . $conn->real_escape_string($table_type) . "'";
    }
    
    $sql .= " ORDER BY floor_level, section, table_number";
    
    $result = $conn->query($sql);
    
    if ($result) {
        $tables = [];
        while ($row = $result->fetch_assoc()) {
            $row['active_booking_id'] = null;
            $row['assigned_server_id'] = null;
            $row['assigned_server_name'] = null;

            // If date is provided, recalculate status based on bookings for that date
            if ($date) {
                $date_escaped = $conn->real_escape_string($date);
                
                // Get active booking details for this table/date (optionally meal/slot filtered).
                $booking_check = $conn->query("
                    SELECT b.id AS booking_id, otb.assigned_server_id, s.name AS assigned_server_name
                    FROM online_table_bookings otb
                    INNER JOIN bookings b ON otb.booking_id = b.id
                    LEFT JOIN servers s ON s.id = otb.assigned_server_id
                    WHERE otb.online_table_id = " . intval($row['id']) . "
                    AND b.booking_date = '" . $date_escaped . "'
                    " . ($meal_type !== '' ? "AND LOWER(TRIM(b.meal_type)) = LOWER('" . $conn->real_escape_string($meal_type) . "')" : "") . "
                    " . ($slot_time !== '' ? "AND TIME(b.slot_time) = TIME('" . $conn->real_escape_string($slot_time) . "')" : "") . "
                    AND b.status IN ('pending', 'confirmed', 'checked_in')
                    AND otb.allocation_status = 'allocated'
                    ORDER BY b.slot_time ASC
                    LIMIT 1
                ");
                
                if ($booking_check) {
                    $booking_result = $booking_check->fetch_assoc();
                    $has_booking = !empty($booking_result['booking_id']);
                    // Preserve non-available base statuses (e.g., maintenance)
                    if ($row['status'] === 'available') {
                        $row['status'] = $has_booking ? 'booked' : 'available';
                    }
                    if ($has_booking) {
                        $row['active_booking_id'] = intval($booking_result['booking_id']);
                        $row['assigned_server_id'] = !empty($booking_result['assigned_server_id']) ? intval($booking_result['assigned_server_id']) : null;
                        $row['assigned_server_name'] = !empty($booking_result['assigned_server_name']) ? $booking_result['assigned_server_name'] : null;
                    }
                }
            }

            // Apply requested status filter after date-aware status recalculation
            if ($status && $row['status'] !== $status) {
                continue;
            }

            $tables[] = $row;
        }
        
        sendResponse(true, 'Tables fetched successfully', $tables);
    } else {
        sendResponse(false, 'Error fetching tables: ' . $conn->error, null);
    }
}

function ensureOnlineBookingServerColumns() {
    global $conn;

    $checkServer = $conn->query("SHOW COLUMNS FROM online_table_bookings LIKE 'assigned_server_id'");
    if (!$checkServer || $checkServer->num_rows === 0) {
        @$conn->query("ALTER TABLE online_table_bookings ADD COLUMN assigned_server_id INT NULL AFTER online_table_id");
    }

    $checkManager = $conn->query("SHOW COLUMNS FROM online_table_bookings LIKE 'assigned_manager_id'");
    if (!$checkManager || $checkManager->num_rows === 0) {
        @$conn->query("ALTER TABLE online_table_bookings ADD COLUMN assigned_manager_id INT NULL AFTER assigned_server_id");
    }

    $checkLinked = $conn->query("SHOW COLUMNS FROM online_table_bookings LIKE 'linked_assignment_id'");
    if (!$checkLinked || $checkLinked->num_rows === 0) {
        @$conn->query("ALTER TABLE online_table_bookings ADD COLUMN linked_assignment_id INT NULL AFTER assigned_manager_id");
    }
}

function normalizeTableNumber($tableNumber) {
    $upper = strtoupper(trim((string)$tableNumber));
    return preg_replace('/[^A-Z0-9]/', '', $upper);
}

function extractTableDigits($tableNumber) {
    return preg_replace('/\D+/', '', (string)$tableNumber);
}

function findMappedRestaurantTableId($onlineTableNumber, $floorLevel = null, $section = null) {
    global $conn;

    $onlineRaw = trim((string)$onlineTableNumber);
    if ($onlineRaw === '') {
        return 0;
    }

    $exactSql = "SELECT id FROM restaurant_tables WHERE table_number = '" . $conn->real_escape_string($onlineRaw) . "' LIMIT 1";
    $exactRes = $conn->query($exactSql);
    if ($exactRes && $exactRes->num_rows > 0) {
        return intval($exactRes->fetch_assoc()['id']);
    }

    $normOnline = normalizeTableNumber($onlineRaw);
    $digitsOnline = ltrim(extractTableDigits($onlineRaw), '0');

    $candidateSql = "SELECT id, table_number, floor_level, section FROM restaurant_tables";
    $candidateRes = $conn->query($candidateSql);
    if (!$candidateRes || $candidateRes->num_rows === 0) {
        return 0;
    }

    $bestId = 0;
    $bestScore = -1;
    while ($row = $candidateRes->fetch_assoc()) {
        $candidateNorm = normalizeTableNumber($row['table_number'] ?? '');
        $candidateDigits = ltrim(extractTableDigits($row['table_number'] ?? ''), '0');

        $isMatch = false;
        if ($candidateNorm !== '' && $candidateNorm === $normOnline) {
            $isMatch = true;
        } elseif ($digitsOnline !== '' && $candidateDigits !== '' && $digitsOnline === $candidateDigits) {
            $isMatch = true;
        }

        if (!$isMatch) {
            continue;
        }

        $score = 0;
        if ($floorLevel !== null && intval($row['floor_level']) === intval($floorLevel)) {
            $score += 2;
        }
        if ($section !== null && trim((string)$section) !== '' && strcasecmp(trim((string)$row['section']), trim((string)$section)) === 0) {
            $score += 1;
        }

        if ($score > $bestScore) {
            $bestScore = $score;
            $bestId = intval($row['id']);
        }
    }

    return $bestId;
}

function assignServerToOnlineTable() {
    global $conn;

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

    if (!isset($data['table_id']) || !isset($data['server_id'])) {
        sendResponse(false, 'Table ID and Server ID are required', null);
    }

    $table_id = intval($data['table_id']);
    $server_id = intval($data['server_id']);
    $date = isset($data['date']) && trim($data['date']) !== '' ? trim($data['date']) : date('Y-m-d');
    $meal_type = isset($data['meal_type']) ? trim($data['meal_type']) : '';
    $slot_time = isset($data['slot_time']) ? trim($data['slot_time']) : '';
    $manager_id = isset($_SESSION['manager_id']) ? intval($_SESSION['manager_id']) : null;

    ensureOnlineBookingServerColumns();

    $sql = "SELECT otb.id, otb.assigned_server_id, otb.linked_assignment_id,
                   ot.table_number, ot.floor_level, ot.section,
                   b.guests
            FROM online_table_bookings otb
            INNER JOIN bookings b ON otb.booking_id = b.id
            INNER JOIN online_tables ot ON ot.id = otb.online_table_id
            WHERE otb.online_table_id = " . $table_id . "
            AND b.booking_date = '" . $conn->real_escape_string($date) . "'
            " . ($meal_type !== '' ? "AND LOWER(TRIM(b.meal_type)) = LOWER('" . $conn->real_escape_string($meal_type) . "')" : "") . "
            " . ($slot_time !== '' ? "AND TIME(b.slot_time) = TIME('" . $conn->real_escape_string($slot_time) . "')" : "") . "
            AND b.status IN ('pending', 'confirmed', 'checked_in')
            AND otb.allocation_status = 'allocated'
            ORDER BY b.slot_time ASC";

    $result = $conn->query($sql);
    if (!$result || $result->num_rows === 0) {
        sendResponse(false, 'No active booking found for selected filters', null);
    }

    if ($result->num_rows > 1 && ($meal_type === '' || $slot_time === '')) {
        sendResponse(false, 'Multiple bookings found. Please filter by meal type and slot timing.', null);
    }

    $row = $result->fetch_assoc();
    $allocation_id = intval($row['id']);
    $currently_assigned_server_id = !empty($row['assigned_server_id']) ? intval($row['assigned_server_id']) : 0;
    $linked_assignment_id = !empty($row['linked_assignment_id']) ? intval($row['linked_assignment_id']) : 0;

    $server_load = getServerLoad($server_id);
    if (!$server_load) {
        sendResponse(false, 'Server not found', null);
    }
    if ($server_load['status'] === 'offline' || $server_load['status'] === 'break') {
        sendResponse(false, 'Server is not available for assignment', null);
    }
    $effective_active = $server_load['active_count'];
    if ($currently_assigned_server_id > 0 && $currently_assigned_server_id === $server_id) {
        $effective_active = max(0, $effective_active - 1);
    }
    if ($effective_active >= $server_load['max_active_orders']) {
        sendResponse(false, 'Server has reached active order limit (' . $server_load['max_active_orders'] . ')', null);
    }

    $update = "UPDATE online_table_bookings
               SET assigned_server_id = " . $server_id . ",
                   assigned_manager_id = " . ($manager_id ? $manager_id : "NULL") . "
               WHERE id = " . $allocation_id;

    if ($conn->query($update) !== TRUE) {
        sendResponse(false, 'Error assigning server: ' . $conn->error, null);
    }

    // Keep online and direct dining tables separate: no cross-mapping.
    if ($linked_assignment_id > 0) {
        @$conn->query("UPDATE table_assignments SET status = 'completed', ended_at = NOW() WHERE id = " . $linked_assignment_id . " AND status = 'assigned'");
        @$conn->query("UPDATE online_table_bookings SET linked_assignment_id = NULL WHERE id = " . $allocation_id);
    }

    $conn->query("UPDATE servers SET status = 'busy' WHERE id = " . $server_id);

    sendResponse(true, 'Server assigned successfully', [
        'allocation_id' => $allocation_id,
        'linked_assignment_id' => null,
        'mapped_restaurant_table_id' => null
    ]);
}

function releaseOnlineTableByContext() {
    global $conn;

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

    if (!isset($data['table_id'])) {
        sendResponse(false, 'Table ID is required', null);
    }

    $table_id = intval($data['table_id']);
    $date = isset($data['date']) && trim($data['date']) !== '' ? trim($data['date']) : date('Y-m-d');
    $meal_type = isset($data['meal_type']) ? trim($data['meal_type']) : '';
    $slot_time = isset($data['slot_time']) ? trim($data['slot_time']) : '';

    ensureOnlineBookingServerColumns();

    $findSql = "SELECT otb.id, otb.assigned_server_id, otb.linked_assignment_id
                FROM online_table_bookings otb
                INNER JOIN bookings b ON otb.booking_id = b.id
                WHERE otb.online_table_id = " . $table_id . "
                AND b.booking_date = '" . $conn->real_escape_string($date) . "'
                " . ($meal_type !== '' ? "AND LOWER(TRIM(b.meal_type)) = LOWER('" . $conn->real_escape_string($meal_type) . "')" : "") . "
                " . ($slot_time !== '' ? "AND TIME(b.slot_time) = TIME('" . $conn->real_escape_string($slot_time) . "')" : "") . "
                AND b.status IN ('pending', 'confirmed', 'checked_in')
                AND otb.allocation_status = 'allocated'
                ORDER BY b.slot_time ASC";

    $findResult = $conn->query($findSql);
    if (!$findResult || $findResult->num_rows === 0) {
        sendResponse(false, 'No active booking found to release for selected filters', null);
    }

    if ($findResult->num_rows > 1 && ($meal_type === '' || $slot_time === '')) {
        sendResponse(false, 'Multiple bookings found. Please filter by meal type and slot timing.', null);
    }

    $allocationIds = [];
    $serverIds = [];
    $linkedAssignmentIds = [];
    while ($row = $findResult->fetch_assoc()) {
        $allocationIds[] = intval($row['id']);
        if (!empty($row['assigned_server_id'])) {
            $serverIds[] = intval($row['assigned_server_id']);
        }
        if (!empty($row['linked_assignment_id'])) {
            $linkedAssignmentIds[] = intval($row['linked_assignment_id']);
        }
    }

    $idList = implode(',', $allocationIds);
    $releaseSql = "UPDATE online_table_bookings
                   SET allocation_status = 'released', released_at = NOW()
                   WHERE id IN (" . $idList . ")";

    if ($conn->query($releaseSql) !== TRUE) {
        sendResponse(false, 'Error releasing table: ' . $conn->error, null);
    }

    // Complete any linked direct table assignments created for order flow.
    $linkedAssignmentIds = array_values(array_unique($linkedAssignmentIds));
    if (!empty($linkedAssignmentIds)) {
        $linkedIdsCsv = implode(',', $linkedAssignmentIds);
        @$conn->query("UPDATE table_assignments SET status = 'completed', ended_at = NOW() WHERE id IN (" . $linkedIdsCsv . ") AND status = 'assigned'");
        @$conn->query("UPDATE online_table_bookings SET linked_assignment_id = NULL WHERE id IN (" . $idList . ")");
    }

    // Reset server status only if they are not active on any other assignment.
    $serverIds = array_values(array_unique($serverIds));
    foreach ($serverIds as $sid) {
        $restaurantActive = $conn->query("SELECT COUNT(*) AS c FROM table_assignments WHERE server_id = " . $sid . " AND status = 'assigned'");
        $restaurantCount = $restaurantActive ? intval($restaurantActive->fetch_assoc()['c']) : 0;

        $onlineActive = $conn->query("SELECT COUNT(*) AS c FROM online_table_bookings WHERE assigned_server_id = " . $sid . " AND allocation_status = 'allocated'");
        $onlineCount = $onlineActive ? intval($onlineActive->fetch_assoc()['c']) : 0;

        if (($restaurantCount + $onlineCount) === 0) {
            $conn->query("UPDATE servers SET status = 'available' WHERE id = " . $sid);
        }
    }

    sendResponse(true, 'Table released successfully', null);
}

// Create online table
function createOnlineTable() {
    global $conn;
    
    $data = json_decode(file_get_contents('php://input'), true);
    
    if (!isset($data['table_number']) || !isset($data['capacity'])) {
        sendResponse(false, 'Table number and capacity are required', null);
    }
    
    $table_number = $conn->real_escape_string($data['table_number']);
    $capacity = intval($data['capacity']);
    $floor_level = isset($data['floor_level']) ? intval($data['floor_level']) : 1;
    $section = isset($data['section']) ? $conn->real_escape_string($data['section']) : '';
    $table_type = isset($data['table_type']) ? $conn->real_escape_string($data['table_type']) : 'online';
    $availability_from = isset($data['availability_from']) ? $conn->real_escape_string($data['availability_from']) : '10:00:00';
    $availability_to = isset($data['availability_to']) ? $conn->real_escape_string($data['availability_to']) : '22:00:00';
    $notes = isset($data['notes']) ? $conn->real_escape_string($data['notes']) : '';
    
    // Check if table number already exists
    $check = $conn->query("SELECT id FROM online_tables WHERE table_number = '" . $table_number . "'");
    if ($check->num_rows > 0) {
        sendResponse(false, 'Table number already exists', null);
    }
    
    $sql = "INSERT INTO online_tables (table_number, base_capacity, current_capacity, floor_level, section, table_type, availability_from, availability_to, notes, status) 
            VALUES ('" . $table_number . "', " . $capacity . ", " . $capacity . ", " . $floor_level . ", '" . $section . "', '" . $table_type . "', '" . $availability_from . "', '" . $availability_to . "', '" . $notes . "', 'available')";
    
    if ($conn->query($sql) === TRUE) {
        $table_id = $conn->insert_id;
        $table = $conn->query("SELECT * FROM online_tables WHERE id = " . $table_id);
        $result = $table->fetch_assoc();
        sendResponse(true, 'Online table created successfully', $result);
    } else {
        sendResponse(false, 'Error creating table: ' . $conn->error, null);
    }
}

// Update online table
function updateOnlineTable() {
    global $conn;
    
    $data = json_decode(file_get_contents('php://input'), true);
    
    if (!isset($data['id'])) {
        sendResponse(false, 'Table ID is required', null);
    }
    
    $id = intval($data['id']);
    $updates = [];
    
    if (isset($data['table_number'])) {
        $updates[] = "table_number = '" . $conn->real_escape_string($data['table_number']) . "'";
    }
    if (isset($data['capacity'])) {
        $updates[] = "current_capacity = " . intval($data['capacity']);
        $updates[] = "base_capacity = " . intval($data['capacity']);
    }
    if (isset($data['floor_level'])) {
        $updates[] = "floor_level = " . intval($data['floor_level']);
    }
    if (isset($data['section'])) {
        $updates[] = "section = '" . $conn->real_escape_string($data['section']) . "'";
    }
    if (isset($data['table_type'])) {
        $updates[] = "table_type = '" . $conn->real_escape_string($data['table_type']) . "'";
    }
    if (isset($data['availability_from'])) {
        $updates[] = "availability_from = '" . $conn->real_escape_string($data['availability_from']) . "'";
    }
    if (isset($data['availability_to'])) {
        $updates[] = "availability_to = '" . $conn->real_escape_string($data['availability_to']) . "'";
    }
    if (isset($data['notes'])) {
        $updates[] = "notes = '" . $conn->real_escape_string($data['notes']) . "'";
    }
    
    if (empty($updates)) {
        sendResponse(false, 'No updates provided', null);
    }
    
    $sql = "UPDATE online_tables SET " . implode(", ", $updates) . " WHERE id = " . $id;
    
    if ($conn->query($sql) === TRUE) {
        $table = $conn->query("SELECT * FROM online_tables WHERE id = " . $id);
        $result = $table->fetch_assoc();
        sendResponse(true, 'Online table updated successfully', $result);
    } else {
        sendResponse(false, 'Error updating table: ' . $conn->error, null);
    }
}

// Delete online table
function deleteOnlineTable() {
    global $conn;
    
    $data = json_decode(file_get_contents('php://input'), true);
    
    if (!isset($data['id'])) {
        sendResponse(false, 'Table ID is required', null);
    }
    
    $id = intval($data['id']);
    
    // Check if table has any active allocations
    $check = $conn->query("SELECT COUNT(*) as count FROM online_table_bookings WHERE online_table_id = " . $id . " AND allocation_status = 'allocated'");
    $result = $check->fetch_assoc();
    
    if ($result['count'] > 0) {
        sendResponse(false, 'Cannot delete table with active allocations', null);
    }
    
    $sql = "DELETE FROM online_tables WHERE id = " . $id;
    
    if ($conn->query($sql) === TRUE) {
        sendResponse(true, 'Online table deleted successfully', null);
    } else {
        sendResponse(false, 'Error deleting table: ' . $conn->error, null);
    }
}

// Get single online table
function getOnlineTable() {
    global $conn;
    
    $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
    
    if (!$id) {
        sendResponse(false, 'Table ID is required', null);
    }
    
    $sql = "SELECT * FROM online_tables WHERE id = " . $id;
    $result = $conn->query($sql);
    
    if ($result && $result->num_rows > 0) {
        $table = $result->fetch_assoc();
        sendResponse(true, 'Table fetched successfully', $table);
    } else {
        sendResponse(false, 'Table not found', null);
    }
}

// Get table availability
function getTableAvailability() {
    global $conn;
    
    $capacity = isset($_GET['capacity']) ? intval($_GET['capacity']) : 0;
    $date = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');
    
    if ($capacity <= 0) {
        sendResponse(false, 'Valid capacity is required', null);
    }
    
    $date_escaped = $conn->real_escape_string($date);
    
    $sql = "SELECT ot.* FROM online_tables ot
            WHERE ot.current_capacity >= " . $capacity . " 
            AND ot.status = 'available'
            AND ot.id NOT IN (
                SELECT otb.online_table_id FROM online_table_bookings otb
                INNER JOIN bookings b ON otb.booking_id = b.id
                WHERE b.booking_date = '" . $date_escaped . "'
                AND b.status IN ('pending', 'confirmed', 'checked_in')
                AND otb.allocation_status = 'allocated'
            )
            ORDER BY ot.current_capacity ASC";
    
    $result = $conn->query($sql);
    
    if ($result) {
        $tables = [];
        while ($row = $result->fetch_assoc()) {
            $tables[] = $row;
        }
        sendResponse(true, 'Available tables fetched successfully', $tables);
    } else {
        sendResponse(false, 'Error fetching tables: ' . $conn->error, null);
    }
}

// Allocate table to booking
function allocateTableToBooking() {
    global $conn;
    
    $data = json_decode(file_get_contents('php://input'), true);
    
    if (!isset($data['booking_id']) || !isset($data['online_table_id'])) {
        sendResponse(false, 'Booking ID and Table ID are required', null);
    }
    
    $booking_id = intval($data['booking_id']);
    $online_table_id = intval($data['online_table_id']);
    
    // Check if booking exists
    $booking_check = $conn->query("SELECT id FROM bookings WHERE id = " . $booking_id);
    if ($booking_check->num_rows === 0) {
        sendResponse(false, 'Booking not found', null);
    }
    
    // Check if table exists
    $table_check = $conn->query("SELECT id FROM online_tables WHERE id = " . $online_table_id);
    if ($table_check->num_rows === 0) {
        sendResponse(false, 'Online table not found', null);
    }
    
    // Check if already allocated
    $existing = $conn->query("SELECT id FROM online_table_bookings WHERE booking_id = " . $booking_id . " AND allocation_status = 'allocated'");
    if ($existing->num_rows > 0) {
        sendResponse(false, 'Table already allocated for this booking', null);
    }
    
    $sql = "INSERT INTO online_table_bookings (booking_id, online_table_id, allocation_status) 
            VALUES (" . $booking_id . ", " . $online_table_id . ", 'allocated')";
    
    if ($conn->query($sql) === TRUE) {
        sendResponse(true, 'Table allocated to booking successfully', ['id' => $conn->insert_id]);
    } else {
        sendResponse(false, 'Error allocating table: ' . $conn->error, null);
    }
}

// Release table from booking
function releaseTable() {
    global $conn;
    
    $data = json_decode(file_get_contents('php://input'), true);
    
    if (!isset($data['booking_id'])) {
        sendResponse(false, 'Booking ID is required', null);
    }
    
    $booking_id = intval($data['booking_id']);
    
    // Update to released status
    $sql = "UPDATE online_table_bookings SET allocation_status = 'released', released_at = NOW() 
            WHERE booking_id = " . $booking_id . " AND allocation_status = 'allocated'";
    
    if ($conn->query($sql) === TRUE) {
        sendResponse(true, 'Table released successfully', null);
    } else {
        sendResponse(false, 'Error releasing table: ' . $conn->error, null);
    }
}

// Get sections
function getSections() {
    global $conn;
    
    $sql = "SELECT DISTINCT section FROM online_tables WHERE section IS NOT NULL AND section != '' ORDER BY section";
    
    $result = $conn->query($sql);
    
    if ($result) {
        $sections = [];
        while ($row = $result->fetch_assoc()) {
            $sections[] = $row['section'];
        }
        sendResponse(true, 'Sections fetched successfully', $sections);
    } else {
        sendResponse(false, 'Error fetching sections: ' . $conn->error, null);
    }
}

// Get tables by capacity
function getTablesByCapacity() {
    global $conn;
    
    $capacity = isset($_GET['capacity']) ? intval($_GET['capacity']) : 0;
    
    if ($capacity <= 0) {
        sendResponse(false, 'Valid capacity is required', null);
    }
    
    $sql = "SELECT * FROM online_tables WHERE current_capacity >= " . $capacity . " AND status = 'available' ORDER BY current_capacity ASC";
    
    $result = $conn->query($sql);
    
    if ($result) {
        $tables = [];
        while ($row = $result->fetch_assoc()) {
            $tables[] = $row;
        }
        sendResponse(true, 'Tables fetched successfully', $tables);
    } else {
        sendResponse(false, 'Error fetching tables: ' . $conn->error, null);
    }
}

// Update table capacity
function updateTableCapacity() {
    global $conn;
    
    $data = json_decode(file_get_contents('php://input'), true);
    
    if (!isset($data['id']) || !isset($data['capacity'])) {
        sendResponse(false, 'Table ID and capacity are required', null);
    }
    
    $id = intval($data['id']);
    $capacity = intval($data['capacity']);
    
    $sql = "UPDATE online_tables SET current_capacity = " . $capacity . ", base_capacity = " . $capacity . " WHERE id = " . $id;
    
    if ($conn->query($sql) === TRUE) {
        sendResponse(true, 'Capacity updated successfully', null);
    } else {
        sendResponse(false, 'Error updating capacity: ' . $conn->error, null);
    }
}

?>
