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

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

// Ensure user is logged in and necessary session variables are set
if (!isset($_SESSION['user_email']) || !isset($_SESSION['user_full_name']) || !isset($_SESSION['user_id'])) {
    header('Location: ../view/user/cart.php?error=session_expired');
    exit();
}

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

// Create a User model instance
$userModel = new User();

// Get cart items from the session
$cartItems = $userModel->getActiveCart($userId);

// If no valid cart items found, redirect back
if (empty($cartItems)) {
    header('Location: ../view/user/cart.php?error=empty_cart');
    exit();
}

// Format cart items for the createOrder function
$orderItems = [];
foreach ($cartItems as $item) {
    $orderItems[] = [
        'product_id' => $item['product_id'],
        'quantity' => $item['quantity']
    ];
}

// Process the order with cart items
$orderResult = $userModel->createOrder($userId, $orderItems);

// If order was successful, clear the cart
if ($orderResult['success']) {
    $userModel->clearCart($userId);
}

$userModel->closeConnection();

if ($orderResult['success']) {
    // Redirect to queue display page
    header('Location: ../view/admin/generate.php?order_id=' . $orderResult['order_id']);
    exit();
} else {
    // Failed to create order
    $errorMessage = isset($orderResult['message']) ? urlencode($orderResult['message']) : 'order_creation_failed';
    header('Location: ../view/user/cart.php?error=' . $errorMessage);
    exit();
}
?>