<?php
/**
 * Tom's Java Jive - Cart API
 */

require_once __DIR__ . '/../includes/functions.php';

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

$input = json_decode(file_get_contents('php://input'), true);
$action = $input['action'] ?? $_POST['action'] ?? '';

switch ($action) {
    case 'add':
        $productId = $input['product_id'] ?? '';
        $quantity = intval($input['quantity'] ?? 1);
        
        if (!$productId) {
            jsonResponse(['error' => 'Product ID required'], 400);
        }
        
        // Verify product exists and is active
        $product = db()->fetch(
            "SELECT product_id, stock FROM products WHERE product_id = :id AND is_active = 1",
            ['id' => $productId]
        );
        
        if (!$product) {
            jsonResponse(['error' => 'Product not found'], 404);
        }
        
        if ($product['stock'] < $quantity) {
            jsonResponse(['error' => 'Not enough stock'], 400);
        }
        
        addToCart($productId, $quantity);
        
        jsonResponse([
            'success' => true,
            'cart_count' => getCartCount(),
            'message' => 'Item added to cart'
        ]);
        break;
        
    case 'update':
        $productId = $input['product_id'] ?? '';
        $quantity = intval($input['quantity'] ?? 0);
        
        if (!$productId) {
            jsonResponse(['error' => 'Product ID required'], 400);
        }
        
        updateCartItem($productId, $quantity);
        
        jsonResponse([
            'success' => true,
            'cart_count' => getCartCount(),
            'subtotal' => getCartTotal()
        ]);
        break;
        
    case 'remove':
        $productId = $input['product_id'] ?? '';
        
        if (!$productId) {
            jsonResponse(['error' => 'Product ID required'], 400);
        }
        
        removeFromCart($productId);
        
        jsonResponse([
            'success' => true,
            'cart_count' => getCartCount(),
            'subtotal' => getCartTotal()
        ]);
        break;
        
    case 'clear':
        clearCart();
        jsonResponse(['success' => true, 'cart_count' => 0]);
        break;
        
    case 'get':
        $cart = getCart();
        $items = [];
        $subtotal = 0;
        
        foreach ($cart as $productId => $quantity) {
            $product = db()->fetch(
                "SELECT product_id, name, price, sale_price, stock, images FROM products WHERE product_id = :id",
                ['id' => $productId]
            );
            
            if ($product) {
                $images = json_decode($product['images'] ?? '[]', true);
                $unitPrice = $product['sale_price'] ?? $product['price'];
                $total = $unitPrice * $quantity;
                $subtotal += $total;
                
                $items[] = [
                    'product_id' => $product['product_id'],
                    'name' => $product['name'],
                    'price' => $unitPrice,
                    'quantity' => $quantity,
                    'total' => $total,
                    'image' => !empty($images) ? $images[0] : null,
                    'stock' => $product['stock']
                ];
            }
        }
        
        jsonResponse([
            'items' => $items,
            'count' => getCartCount(),
            'subtotal' => $subtotal
        ]);
        break;
        
    default:
        jsonResponse(['error' => 'Invalid action'], 400);
}
