<?php
require_once '../config/cors.php';
require_once '../config/database.php';

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

$method = $_SERVER['REQUEST_METHOD'];

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

try {
    $data = json_decode(file_get_contents("php://input"), true);

    // Handle both camelCase (productId) and snake_case (product_id)
    $productId = $data['productId'] ?? $data['product_id'] ?? null;
    if (!$productId) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Product ID is required']);
        exit;
    }

    $quantity = isset($data['quantity']) ? (int)$data['quantity'] : 1;
    // Handle both camelCase (userId) and snake_case (user_id)
    $userId = $data['userId'] ?? $data['user_id'] ?? 'guest';
    
    // Handle variant and final price
    $variant = $data['variant'] ?? null;
    $finalPrice = $data['final_price'] ?? null;
    
    // Debug logging
    error_log("Cart Add Debug - Product ID: $productId, Quantity: $quantity, User ID: $userId");
    if ($variant) {
        error_log("Cart Add Debug - Variant: " . json_encode($variant));
    }

    // For guest users, just return success (frontend handles local storage)
    if ($userId === 'guest') {
        http_response_code(200);
        echo json_encode([
            'success' => true,
            'message' => 'Item added to cart (guest)',
            'items' => [],
            'total' => 0
        ]);
        exit;
    }

    // Check if product exists
    $stmt = $db->prepare("SELECT id, name, base_price, stock FROM products WHERE id = :product_id AND is_active = 1");
    $stmt->bindParam(':product_id', $productId, PDO::PARAM_STR); // Use PARAM_STR for UUID
    $stmt->execute();
    $product = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$product) {
        http_response_code(404);
        echo json_encode(['success' => false, 'message' => 'Product not found or inactive']);
        exit;
    }

    // Check stock based on variant selection
    $availableStock = $product['stock']; // Default to product stock
    $stockContext = 'Product';
    
    if ($variant && isset($variant['id'])) {
        // If variant is selected, check variant stock
        try {
            $stmt = $db->prepare("SELECT stock FROM product_variants WHERE id = :variant_id");
            $stmt->bindParam(':variant_id', $variant['id'], PDO::PARAM_STR);
            $stmt->execute();
            $variantData = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($variantData) {
                $availableStock = $variantData['stock'];
                $stockContext = "Variant '{$variant['variant_name']}'";
            }
        } catch (PDOException $e) {
            // If variant table doesn't exist or error, use variant stock from payload
            if (isset($variant['stock'])) {
                $availableStock = $variant['stock'];
                $stockContext = "Variant '{$variant['variant_name']}'";
            }
        }
    }

    // Debug stock validation
    error_log("Cart Add Debug - Stock validation: Context: $stockContext, Available: $availableStock, Requested: $quantity");
    
    // Validate stock
    if ($availableStock < $quantity) {
        error_log("Cart Add Debug - Stock validation FAILED");
        http_response_code(400);
        echo json_encode([
            'success' => false, 
            'message' => "{$stockContext} has insufficient stock. Available: {$availableStock}, Requested: {$quantity}"
        ]);
        exit;
    }
    
    error_log("Cart Add Debug - Stock validation PASSED");

    // Check if item already exists in cart (with variant support)
    try {
        // First check if variant_data column exists
        $stmt = $db->prepare("SHOW COLUMNS FROM cart_items LIKE 'variant_data'");
        $stmt->execute();
        $hasVariantData = $stmt->rowCount() > 0;
        
        if ($hasVariantData) {
            $variantCondition = $variant ? "AND variant_data = :variant_data" : "AND (variant_data IS NULL OR variant_data = '')";
            $stmt = $db->prepare("SELECT id, quantity, price FROM cart_items WHERE user_id = :user_id AND product_id = :product_id $variantCondition");
            $stmt->bindParam(':user_id', $userId, PDO::PARAM_STR);
            $stmt->bindParam(':product_id', $productId, PDO::PARAM_STR);
            if ($variant) {
                $variantJson = json_encode($variant);
                $stmt->bindParam(':variant_data', $variantJson, PDO::PARAM_STR);
            }
            $stmt->execute();
            $existingItem = $stmt->fetch(PDO::FETCH_ASSOC);
        } else {
            // Fallback to variant_id column if variant_data doesn't exist
            $variantId = $variant ? $variant['id'] : null;
            $variantCondition = $variantId ? "AND variant_id = :variant_id" : "AND variant_id IS NULL";
            $stmt = $db->prepare("SELECT id, quantity FROM cart_items WHERE user_id = :user_id AND product_id = :product_id $variantCondition");
            $stmt->bindParam(':user_id', $userId, PDO::PARAM_STR);
            $stmt->bindParam(':product_id', $productId, PDO::PARAM_STR);
            if ($variantId) {
                $stmt->bindParam(':variant_id', $variantId, PDO::PARAM_STR);
            }
            $stmt->execute();
            $existingItem = $stmt->fetch(PDO::FETCH_ASSOC);
        }
    } catch (PDOException $e) {
        // Final fallback to basic check
        $stmt = $db->prepare("SELECT id, quantity FROM cart_items WHERE user_id = :user_id AND product_id = :product_id");
        $stmt->bindParam(':user_id', $userId, PDO::PARAM_STR);
        $stmt->bindParam(':product_id', $productId, PDO::PARAM_STR);
        $stmt->execute();
        $existingItem = $stmt->fetch(PDO::FETCH_ASSOC);
    }

    if ($existingItem) {
        // Update quantity
        $newQuantity = $existingItem['quantity'] + $quantity;
        $stmt = $db->prepare("UPDATE cart_items SET quantity = :quantity WHERE id = :id");
        $stmt->bindParam(':quantity', $newQuantity);
        $stmt->bindParam(':id', $existingItem['id']);
        $stmt->execute();
    } else {
        // Add new item with variant and custom price
        $itemPrice = $finalPrice ?? $product['base_price'];
        $variantJson = $variant ? json_encode($variant) : null;
        $variantId = $variant ? $variant['id'] : null;
        
        // Check which columns exist and insert accordingly
        try {
            $stmt = $db->prepare("SHOW COLUMNS FROM cart_items LIKE 'variant_data'");
            $stmt->execute();
            $hasVariantData = $stmt->rowCount() > 0;
            
            $stmt = $db->prepare("SHOW COLUMNS FROM cart_items LIKE 'price'");
            $stmt->execute();
            $hasPrice = $stmt->rowCount() > 0;
            
            if ($hasVariantData && $hasPrice) {
                // Use variant_data and price columns
                $stmt = $db->prepare("INSERT INTO cart_items (user_id, product_id, quantity, price, variant_data) VALUES (:user_id, :product_id, :quantity, :price, :variant_data)");
                $stmt->bindParam(':user_id', $userId, PDO::PARAM_STR);
                $stmt->bindParam(':product_id', $productId, PDO::PARAM_STR);
                $stmt->bindParam(':quantity', $quantity);
                $stmt->bindParam(':price', $itemPrice);
                $stmt->bindParam(':variant_data', $variantJson);
                $stmt->execute();
            } else if ($hasPrice) {
                // Use variant_id and price columns
                $stmt = $db->prepare("INSERT INTO cart_items (user_id, product_id, variant_id, quantity, price) VALUES (:user_id, :product_id, :variant_id, :quantity, :price)");
                $stmt->bindParam(':user_id', $userId, PDO::PARAM_STR);
                $stmt->bindParam(':product_id', $productId, PDO::PARAM_STR);
                $stmt->bindParam(':variant_id', $variantId, PDO::PARAM_STR);
                $stmt->bindParam(':quantity', $quantity);
                $stmt->bindParam(':price', $itemPrice);
                $stmt->execute();
            } else {
                // Basic insert with variant_id only
                $stmt = $db->prepare("INSERT INTO cart_items (user_id, product_id, variant_id, quantity) VALUES (:user_id, :product_id, :variant_id, :quantity)");
                $stmt->bindParam(':user_id', $userId, PDO::PARAM_STR);
                $stmt->bindParam(':product_id', $productId, PDO::PARAM_STR);
                $stmt->bindParam(':variant_id', $variantId, PDO::PARAM_STR);
                $stmt->bindParam(':quantity', $quantity);
                $stmt->execute();
            }
        } catch (PDOException $e) {
            // Final fallback to basic insert
            $stmt = $db->prepare("INSERT INTO cart_items (user_id, product_id, quantity) VALUES (:user_id, :product_id, :quantity)");
            $stmt->bindParam(':user_id', $userId, PDO::PARAM_STR);
            $stmt->bindParam(':product_id', $productId, PDO::PARAM_STR);
            $stmt->bindParam(':quantity', $quantity);
            $stmt->execute();
        }
    }

    // Get updated cart with variant support
    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, 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, pi.url as image_url,
                       pv.variant_name, pv.price_diff
                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']
                ];
            }
        }
    } catch (PDOException $e) {
        // Fallback query
        $stmt = $db->prepare("
            SELECT ci.*, p.name, p.base_price, p.brand, 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,
        'message' => 'Item added to cart',
        'items' => $items,
        'total' => $total
    ]);

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