<?php
session_start();

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

if (!isset($_SESSION['cart'])) {
    $_SESSION['cart'] = [];
}

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

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

switch ($action) {
    case 'add':
        $id = $_POST['id'] ?? null;
        $name = $_POST['name'] ?? '';
        $price = $_POST['price'] ?? 0;
        $image = $_POST['image'] ?? '';
        
        if ($id) {
            if (isset($_SESSION['cart'][$id])) {
                $_SESSION['cart'][$id]['quantity']++;
            } else {
                $_SESSION['cart'][$id] = [
                    'id' => $id,
                    'name' => $name,
                    'price' => (float)$price,
                    'image' => $image,
                    'quantity' => 1
                ];
            }
            echo json_encode(['success' => true, 'cart_count' => getCartCount()]);
        } else {
            echo json_encode(['success' => false, 'error' => 'Invalid product']);
        }
        break;

    case 'remove':
        $id = $_POST['id'] ?? null;
        if ($id && isset($_SESSION['cart'][$id])) {
            unset($_SESSION['cart'][$id]);
            echo json_encode(['success' => true, 'cart_count' => getCartCount()]);
        } else {
            echo json_encode(['success' => false, 'error' => 'Product not in cart']);
        }
        break;

    case 'update':
        $id = $_POST['id'] ?? null;
        $quantity = (int)($_POST['quantity'] ?? 1);
        if ($id && isset($_SESSION['cart'][$id])) {
            if ($quantity <= 0) {
                unset($_SESSION['cart'][$id]);
            } else {
                $_SESSION['cart'][$id]['quantity'] = $quantity;
            }
            echo json_encode(['success' => true, 'cart_count' => getCartCount()]);
        } else {
            echo json_encode(['success' => false, 'error' => 'Product not in cart']);
        }
        break;

    case 'get':
        echo json_encode(['success' => true, 'cart' => array_values($_SESSION['cart']), 'cart_count' => getCartCount()]);
        break;

    default:
        echo json_encode(['success' => false, 'error' => 'Invalid action']);
        break;
}