<?php
/**
 * Cart API - AJAX Endpoints
 * Digital Marketplace
 */

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

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

$action = $_POST['action'] ?? $_GET['action'] ?? '';

switch ($action) {
    case 'add':
        handle_add_to_cart();
        break;
    
    case 'update':
        handle_update_cart();
        break;
    
    case 'remove':
        handle_remove_from_cart();
        break;
    
    case 'clear':
        handle_clear_cart();
        break;
    
    case 'count':
        handle_get_cart_count();
        break;
    
    case 'items':
        handle_get_cart_items();
        break;
    
    default:
        json_response(['success' => false, 'message' => 'Invalid action']);
}

function handle_add_to_cart() {
    global $pdo;
    
    // Verify CSRF
    if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
        json_response(['success' => false, 'message' => 'Invalid request']);
    }
    
    $product_id = (int)($_POST['product_id'] ?? 0);
    $quantity = max(1, (int)($_POST['quantity'] ?? 1));
    $license_type = sanitize($_POST['license_type'] ?? 'regular');
    
    if (!$product_id) {
        json_response(['success' => false, 'message' => 'Invalid product']);
    }
    
    // Check if product exists and is active
    $product = get_product_by_id($product_id);
    if (!$product || $product['status'] !== 'active') {
        json_response(['success' => false, 'message' => 'Product not available']);
    }
    
    // Add to cart
    if (add_to_cart($product_id, $quantity, $license_type)) {
        json_response([
            'success' => true,
            'message' => 'Added to cart',
            'cart_count' => get_cart_count()
        ]);
    } else {
        json_response(['success' => false, 'message' => 'Failed to add to cart']);
    }
}

function handle_update_cart() {
    global $pdo;
    
    if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
        json_response(['success' => false, 'message' => 'Invalid request']);
    }
    
    $cart_id = (int)($_POST['cart_id'] ?? 0);
    $quantity = max(0, (int)($_POST['quantity'] ?? 1));
    
    if (!$cart_id) {
        json_response(['success' => false, 'message' => 'Invalid cart item']);
    }
    
    if (update_cart_quantity($cart_id, $quantity)) {
        json_response([
            'success' => true,
            'message' => 'Cart updated',
            'cart_count' => get_cart_count(),
            'cart_total' => get_cart_total()
        ]);
    } else {
        json_response(['success' => false, 'message' => 'Failed to update cart']);
    }
}

function handle_remove_from_cart() {
    global $pdo;
    
    if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
        json_response(['success' => false, 'message' => 'Invalid request']);
    }
    
    $cart_id = (int)($_POST['cart_id'] ?? 0);
    
    if (!$cart_id) {
        json_response(['success' => false, 'message' => 'Invalid cart item']);
    }
    
    if (remove_from_cart($cart_id)) {
        json_response([
            'success' => true,
            'message' => 'Item removed',
            'cart_count' => get_cart_count(),
            'cart_total' => get_cart_total()
        ]);
    } else {
        json_response(['success' => false, 'message' => 'Failed to remove item']);
    }
}

function handle_clear_cart() {
    global $pdo;
    
    if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
        json_response(['success' => false, 'message' => 'Invalid request']);
    }
    
    if (clear_cart()) {
        json_response([
            'success' => true,
            'message' => 'Cart cleared',
            'cart_count' => 0,
            'cart_total' => 0
        ]);
    } else {
        json_response(['success' => false, 'message' => 'Failed to clear cart']);
    }
}

function handle_get_cart_count() {
    json_response([
        'success' => true,
        'cart_count' => get_cart_count()
    ]);
}

function handle_get_cart_items() {
    $items = get_cart_items();
    $formatted_items = [];
    
    foreach ($items as $item) {
        $formatted_items[] = [
            'id' => $item['id'],
            'product_id' => $item['product_id'],
            'name' => $item['name'],
            'slug' => $item['slug'],
            'image' => get_product_image_url($item),
            'price' => $item['price'],
            'quantity' => $item['quantity'],
            'subtotal' => $item['price'] * $item['quantity'],
            'license_type' => $item['license_type']
        ];
    }
    
    json_response([
        'success' => true,
        'items' => $formatted_items,
        'cart_count' => get_cart_count(),
        'cart_total' => get_cart_total()
    ]);
}
