<?php
require_once '../config/cors.php';
require_once '../config/database.php';
// require_once '../middleware/auth.php'; // --- REMOVED AUTH MIDDLEWARE ---

$database = new Database();
$db = $database->getConnection();

$method = $_SERVER['REQUEST_METHOD'];

if ($method !== 'GET') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

try {
    // Handle both camelCase (userId) and snake_case (user_id) from URL
    $userId = $_GET['userId'] ?? $_GET['user_id'] ?? null;

    if (!$userId) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'User ID is required']);
        exit;
    }
    
    // If the userId is 'guest', return an empty cart
    if ($userId === 'guest') {
        http_response_code(200);
        echo json_encode([
            'success' => true,
            'items' => [],
            'total' => 0
        ]);
        exit;
    }

    // Check which variant storage method is available
    try {
        $stmt = $db->prepare("SHOW COLUMNS FROM cart_items LIKE 'variant_data'");
        $stmt->execute();
        $hasVariantData = $stmt->rowCount() > 0;
        
        if ($hasVariantData) {
            $stmt = $db->prepare("
                SELECT ci.*, p.name, p.base_price, p.brand, p.stock, pi.url as image_url
                FROM cart_items ci
                JOIN products p ON ci.product_id = p.id
                LEFT JOIN product_images pi ON p.id = pi.product_id AND pi.position = 0
                WHERE ci.user_id = :user_id
                ORDER BY ci.added_at DESC
            ");
        } else {
            $stmt = $db->prepare("
                SELECT ci.*, p.name, p.base_price, p.brand, p.stock, pi.url as image_url,
                       pv.variant_name, pv.price_diff, pv.stock as variant_stock
                FROM cart_items ci
                JOIN products p ON ci.product_id = p.id
                LEFT JOIN product_images pi ON p.id = pi.product_id AND pi.position = 0
                LEFT JOIN product_variants pv ON ci.variant_id = pv.id
                WHERE ci.user_id = :user_id
                ORDER BY ci.added_at DESC
            ");
        }
        
        $stmt->bindParam(':user_id', $userId, PDO::PARAM_STR);
        $stmt->execute();
        
        $items = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Parse variant data for each item
        foreach ($items as &$item) {
            if (isset($item['variant_data']) && $item['variant_data']) {
                $item['variant'] = json_decode($item['variant_data'], true);
            } else if (isset($item['variant_name']) && $item['variant_name']) {
                // Build variant object from joined data
                $item['variant'] = [
                    'id' => $item['variant_id'],
                    'variant_name' => $item['variant_name'],
                    'price_diff' => $item['price_diff'],
                    'stock' => $item['variant_stock']
                ];
            }
        }
    } catch (PDOException $e) {
        // Fallback query
        $stmt = $db->prepare("
            SELECT ci.*, p.name, p.base_price, p.brand, p.stock, pi.url as image_url
            FROM cart_items ci
            JOIN products p ON ci.product_id = p.id
            LEFT JOIN product_images pi ON p.id = pi.product_id AND pi.position = 0
            WHERE ci.user_id = :user_id
            ORDER BY ci.added_at DESC
        ");
        $stmt->bindParam(':user_id', $userId, PDO::PARAM_STR);
        $stmt->execute();
        
        $items = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
    
    $total = array_sum(array_map(function($item) {
        return ((isset($item['price']) ? $item['price'] : $item['base_price']) * $item['quantity']);
    }, $items));

    http_response_code(200);
    echo json_encode([
        'success' => true,
        'items' => $items,
        'total' => $total
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Internal Server Error: ' . $e->getMessage()
    ]);
}
?>