<?php
// Enable error reporting for debugging
ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once 'QueueController.php';

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

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

$action = $_POST['action'] ?? null;

if ($action === 'increase') { // Corresponds to the 'Next' button
    if (isset($_SESSION['queued_orders']) && !empty($_SESSION['queued_orders'])) {
        // Find the order with the minimum queue number
        $minQueueNum = PHP_INT_MAX;
        $nextOrderKey = null;

        foreach ($_SESSION['queued_orders'] as $key => $order) {
            if (isset($order['queue_number']) && $order['queue_number'] < $minQueueNum) {
                $minQueueNum = $order['queue_number'];
                $nextOrderKey = $key; // The key is the queue number itself if stored that way originally
            }
        }

        if ($nextOrderKey !== null) {
            // Remove the order with the minimum queue number
            unset($_SESSION['queued_orders'][$nextOrderKey]);
            
            // Optional: Re-index or clean up session array if necessary, though not strictly needed for unsetting by key.
            // If $_SESSION['last_queue_number'] represents the highest issued, it doesn't need to change here.
            // If you want to reset the current displayed queue number if the queue becomes empty:
            // if(empty($_SESSION['queued_orders'])) { unset($_SESSION['current_display_queue_num']); }

            echo json_encode(['success' => true, 'message' => 'Queue advanced.']);
        } else {
            // This case should ideally not be hit if !empty check passed and orders have queue_number
            echo json_encode(['success' => false, 'message' => 'Error: Could not determine next queue item.']);
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'Error: No records in queue to update.']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid action.']);
}
?> 