<?php
session_start();
header('Content-Type: application/json');

// Initialize cart session if not exists
if (!isset($_SESSION['cart'])) {
    $_SESSION['cart'] = [];
}

function getCartCount() {
    $count = 0;
    foreach ($_SESSION['cart'] as $item) {
        $count += $item['quantity'];
    }
    return $count;
}

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

if ($action == 'add') {
    $id = intval($_POST['product_id']);
    $price = floatval($_POST['price']);
    $type = $_POST['item_type'] ?? 'product';
    
    if (isset($_SESSION['cart'][$id])) {
        $_SESSION['cart'][$id]['quantity']++;
    } else {
        $_SESSION['cart'][$id] = [
            'id' => $id,
            'type' => $type,
            'quantity' => 1,
            'price' => $price
        ];
    }
    echo json_encode(['success' => true, 'cartCount' => getCartCount()]);
    exit;
}

if ($action == 'remove') {
    $id = intval($_POST['product_id']);
    unset($_SESSION['cart'][$id]);
    echo json_encode(['success' => true, 'cartCount' => getCartCount()]);
    exit;
}

if ($action == 'update') {
    $id = intval($_POST['product_id']);
    $qty = max(1, intval($_POST['quantity']));
    if (isset($_SESSION['cart'][$id])) {
        $_SESSION['cart'][$id]['quantity'] = $qty;
    }
    $itemTotal = $qty * $_SESSION['cart'][$id]['price'];
    $total = 0;
    foreach ($_SESSION['cart'] as $item) {
        $total += $item['quantity'] * $item['price'];
    }
    echo json_encode(['success' => true, 'cartCount' => getCartCount(), 'itemTotal' => $itemTotal, 'total' => $total]);
    exit;
}

if ($action == 'get') {
    echo json_encode(['success' => true, 'cartCount' => getCartCount(), 'items' => array_values($_SESSION['cart'])]);
    exit;
}

echo json_encode(['success' => false, 'message' => 'Invalid action']);