<?php
// add-to-cart.php
require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/facebook-pixel.php'; // Add this line

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

$product_id = intval($_POST['product_id'] ?? 0);
$quantity = intval($_POST['quantity'] ?? 1);

// Collect variants
$variants = [];
foreach ($_POST as $key => $value) {
    if (strpos($key, 'variant') === 0) {
        $attr_name = str_replace('variant', '', $key);
        $variants[$attr_name] = $value;
    }
}

if ($product_id <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid product']);
    exit;
}

// Get product details
$product = getProduct($pdo, $product_id);
if (!$product) {
    echo json_encode(['success' => false, 'message' => 'Product not found']);
    exit;
}

// Add to cart
$result = addToCart($pdo, $product_id, $quantity, $variants);

if ($result) {
    // ========================================
    // TRACK ADD TO CART EVENT
    // ========================================
    if (!empty(FACEBOOK_PIXEL_ID)) {
        $cart_data = [
            'currency' => 'BDT',
            'value' => ($product['sale_price'] ?: $product['price']) * $quantity,
            'content_name' => $product['name'],
            'content_id' => $product_id,
            'content_type' => 'product',
            'content_category' => $product['category_name'] ?? 'General',
            'num_items' => $quantity
        ];
        
        $user_data = [
            'url' => (isset($_SERVER['HTTPS']) ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']
        ];
        
        trackFacebookEvent('AddToCart', $cart_data, $user_data);
    }
    
    echo json_encode([
        'success' => true,
        'message' => 'Added to cart successfully',
        'cart_count' => getCartCount()
    ]);
} else {
    echo json_encode([
        'success' => false,
        'message' => 'Failed to add to cart'
    ]);
}
?>