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

require_once __DIR__ . '/../model/users.php';

// Get cart data from POST submitted by cart.php
$cartItemsJsonFromCheckout = isset($_POST['cart_items_json']) ? $_POST['cart_items_json'] : '[]';
$_SESSION['last_checkout_cart_json'] = $cartItemsJsonFromCheckout; // Store it in session

// Ensure user is logged in and necessary session variables are set
if (!isset($_SESSION['user_email']) || !isset($_SESSION['user_full_name'])) {
    // Not logged in or session data missing, redirect to login or cart
    // It might be better to redirect to an error page or back to cart with a message
    header('Location: ../view/user/cart.php?error=session_expired');
    exit();
}

$userEmail = $_SESSION['user_email'];
$userName = $_SESSION['user_full_name'];

$userModel = new User();
$assignedQueueNumber = $userModel->addUserToQueue($userName, $userEmail);
$userModel->closeConnection();

if ($assignedQueueNumber !== false) {
    $_SESSION['assigned_queue_number'] = $assignedQueueNumber;
    // Optionally, clear the cart session data here if it's stored server-side
    // Since cart is localStorage, client-side will handle it.
    header('Location: generate.php?new_queue_entry=true'); // Redirect to queue display
    exit();
} else {
    // Failed to add to queue
    unset($_SESSION['last_checkout_cart_json']); // Clear cart from session if queueing failed
    // Redirect back to cart with an error message
    header('Location: ../view/user/cart.php?error=queue_failed');
    exit();
}
?>