<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../model/users.php'; // Ensure the User class is available

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

if (!isset($_SESSION['cart']) || empty($_SESSION['cart'])) {
    echo json_encode(['success' => false, 'message' => 'Cart is empty. Cannot add to queue.']);
    exit;
}

$userEmail = $_SESSION['user_email'] ?? null;
$userName = 'Guest'; // Default name
$userId = null;

if ($userEmail) {
    $userModel = new User(); // Instantiate the User model
    $userDetails = $userModel->getUserDetailsByEmail($userEmail);
    if ($userDetails) {
        $userName = $userDetails['Name'];
        $userId = $userDetails['ID'];
    }
    // $userModel->closeConnection(); // Optional: close connection if User model doesn't do it in destructor
}

// Initialize queue number if not set
if (!isset($_SESSION['last_queue_number'])) {
    $_SESSION['last_queue_number'] = 0;
}

// Increment for a new queue number
$_SESSION['last_queue_number']++;
$queueNumber = $_SESSION['last_queue_number'];

// Store the current cart (the order) with its queue number and user details
if (!isset($_SESSION['queued_orders'])) {
    $_SESSION['queued_orders'] = [];
}

$_SESSION['queued_orders'][$queueNumber] = [
    'user_id' => $userId,
    'user_name' => $userName,
    'user_email' => $userEmail,
    'queue_number' => $queueNumber, // Storing queue number here too for easy access
    'cart_items' => $_SESSION['cart'] 
];

// Optionally, clear the main cart from session after queueing if it's not needed there anymore
// unset($_SESSION['cart']); 

echo json_encode(['success' => true, 'queueNumber' => $queueNumber, 'message' => 'Order added to queue.']);
?> 