<?php
/**
 * Add to Cart - AJAX Handler
 * Digital Product Store
 */

require_once __DIR__ . '/config/database.php';

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

$response = ['success' => false, 'message' => '', 'cart_count' => 0];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $product_id = (int)($_POST['product_id'] ?? 0);
    $quantity = max(1, (int)($_POST['quantity'] ?? 1));
    
    if ($product_id <= 0) {
        $response['message'] = 'Invalid product.';
    } else {
        $product = get_product_by_id($product_id);
        
        if (!$product) {
            $response['message'] = 'Product not found.';
        } elseif ($product['status'] !== 'active') {
            $response['message'] = 'Product is not available.';
        } else {
            if (add_to_cart($product_id, $quantity)) {
                $response['success'] = true;
                $response['message'] = 'Product added to cart!';
                $response['cart_count'] = get_cart_count();
            } else {
                $response['message'] = 'Failed to add to cart.';
            }
        }
    }
} else {
    $response['message'] = 'Invalid request.';
}

echo json_encode($response);
