<?php
/**
 * Cart / Quote API endpoint
 */
header('Content-Type: application/json');
require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/includes/functions.php';
startSecureSession();

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

try {
    verifyCsrf();
    
    switch ($action) {
        case 'add':
            $productId = (int)($input['product_id'] ?? 0);
            $qty       = max(1, (int)($input['quantity'] ?? 1));
            $notes     = sanitize($input['notes'] ?? '');

            if (!$productId) {
                echo json_encode(['success' => false, 'error' => 'Invalid product.']);
                exit;
            }
            $product = Database::fetchOne("SELECT id FROM products WHERE id=? AND is_active=1", [$productId]);
            if (!$product) {
                echo json_encode(['success' => false, 'error' => 'Product not found.']);
                exit;
            }
            addToCart($productId, $qty, $notes);
            echo json_encode(['success' => true, 'count' => getCartCount(), 'message' => 'Added to RFQ cart.']);
            break;

        case 'remove':
            $itemId = (int)($input['item_id'] ?? $_POST['item_id'] ?? 0);
            removeFromCart($itemId);
            echo json_encode(['success' => true, 'count' => getCartCount()]);
            break;

        case 'count':
            echo json_encode(['count' => getCartCount()]);
            break;

        case 'items':
            echo json_encode(['items' => getCartItems(), 'count' => getCartCount()]);
            break;

        case 'clear':
            clearCart();
            echo json_encode(['success' => true]);
            break;

        default:
            echo json_encode(['error' => 'Invalid action.']);
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => 'System error: ' . $e->getMessage()]);
}
