<?php
require_once __DIR__ . '/../functions.php';
header('Content-Type: application/json');

$db = db();
$action = $_POST['action'] ?? $_GET['action'] ?? '';

switch ($action) {
    case 'add':
        $productId = (int)($_POST['product_id'] ?? 0);
        $variantId = !empty($_POST['variant_id']) ? (int)$_POST['variant_id'] : null;
        $quantity = max(1, (int)($_POST['quantity'] ?? 1));
        
        $cartId = getCartId();
        
        // Check existing item
        $existing = $db->prepare("SELECT * FROM cart_items WHERE cart_id = ? AND product_id = ? AND (variant_id = ? OR (variant_id IS NULL AND ? IS NULL))");
        $existing->execute([$cartId, $productId, $variantId, $variantId]);
        $existingItem = $existing->fetch();
        
        if ($existingItem) {
            $db->prepare("UPDATE cart_items SET quantity = quantity + ? WHERE id = ?")->execute([$quantity, $existingItem['id']]);
        } else {
            $product = $db->prepare("SELECT price FROM products WHERE id = ? AND is_active = 1");
            $product->execute([$productId]);
            $product = $product->fetch();
            
            if (!$product) {
                echo json_encode(['success' => false, 'message' => 'Product not found']);
                exit;
            }
            
            $price = $product['price'];
            if ($variantId) {
                $variant = $db->prepare("SELECT price_modifier FROM product_variants WHERE id = ? AND is_active = 1");
                $variant->execute([$variantId]);
                $variant = $variant->fetch();
                if ($variant) $price = (float)$variant['price_modifier'];
            }
            
            $db->prepare("INSERT INTO cart_items (cart_id, product_id, variant_id, quantity, unit_price) VALUES (?, ?, ?, ?, ?)")
                ->execute([$cartId, $productId, $variantId, $quantity, $price]);
        }
        
        echo json_encode(['success' => true, 'cart_count' => getCartCount(), 'message' => 'Added to cart!']);
        break;
    
    case 'update':
        $itemId = (int)($_POST['item_id'] ?? 0);
        $quantity = (int)($_POST['quantity'] ?? 0);
        
        if ($quantity <= 0) {
            $db->prepare("DELETE FROM cart_items WHERE id = ?")->execute([$itemId]);
        } else {
            $db->prepare("UPDATE cart_items SET quantity = ? WHERE id = ?")->execute([$quantity, $itemId]);
        }
        
        echo json_encode(['success' => true, 'cart_count' => getCartCount()]);
        break;
    
    case 'apply_coupon':
        $code = trim($_POST['code'] ?? '');
        $cartId = getCartId();
        
        $coupon = $db->prepare("SELECT * FROM coupons WHERE code = ? AND is_active = 1");
        $coupon->execute([$code]);
        $coupon = $coupon->fetch();
        
        if (!$coupon) {
            flash('error', 'Invalid coupon code.');
        } else {
            $now = date('Y-m-d H:i:s');
            if ($coupon['starts_at'] && $coupon['starts_at'] > $now) {
                flash('error', 'Coupon is not yet valid.');
            } elseif ($coupon['expires_at'] && $coupon['expires_at'] < $now) {
                flash('error', 'Coupon has expired.');
            } elseif ($coupon['max_uses'] && $coupon['used_count'] >= $coupon['max_uses']) {
                flash('error', 'Coupon usage limit reached.');
            } else {
                $subtotal = getCartTotal();
                if ($coupon['min_order_amount'] && $subtotal < $coupon['min_order_amount']) {
                    flash('error', 'Minimum order amount of ' . formatPrice($coupon['min_order_amount']) . ' required.');
                } else {
                    $db->prepare("UPDATE carts SET coupon_id = ? WHERE id = ?")->execute([$coupon['id'], $cartId]);
                    flash('success', 'Coupon applied!');
                }
            }
        }
        header('Location: ../cart.php');
        break;
    
    case 'remove_coupon':
        $cartId = getCartId();
        $db->prepare("UPDATE carts SET coupon_id = NULL, discount_amount = 0 WHERE id = ?")->execute([$cartId]);
        flash('success', 'Coupon removed.');
        header('Location: ../cart.php');
        break;
    
    case 'count':
        echo json_encode(['success' => true, 'count' => getCartCount()]);
        break;
    
    default:
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
}
