<?php
require_once '../init.php';

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

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

if ($action === 'add') {
    $productId  = intval($_POST['product_id'] ?? 0);
    $name       = $_POST['product_name'] ?? '';
    $sku        = $_POST['sku'] ?? '';
    $unitPrice  = floatval($_POST['unit_price'] ?? 0);

    if (!$productId || $unitPrice <= 0) {
        echo json_encode(['success' => false, 'message' => 'Data produk tidak valid']);
        exit;
    }

    if (!isset($_SESSION['cart'][$productId])) {
        $_SESSION['cart'][$productId] = [
            'product_id'   => $productId,
            'product_name' => $name,
            'sku'          => $sku,
            'quantity'     => 1,
            'unit_price'   => $unitPrice,
            'subtotal'     => $unitPrice,
        ];
    } else {
        $_SESSION['cart'][$productId]['quantity']++;
        $_SESSION['cart'][$productId]['subtotal'] =
            $_SESSION['cart'][$productId]['quantity'] * $unitPrice;
    }

} elseif ($action === 'remove') {
    $productId = intval($_POST['product_id'] ?? 0);
    unset($_SESSION['cart'][$productId]);

} elseif ($action === 'remove_one') {
    $productId = intval($_POST['product_id'] ?? 0);
    if (isset($_SESSION['cart'][$productId])) {
        $_SESSION['cart'][$productId]['quantity']--;
        if ($_SESSION['cart'][$productId]['quantity'] <= 0) {
            unset($_SESSION['cart'][$productId]);
        } else {
            $_SESSION['cart'][$productId]['subtotal'] =
                $_SESSION['cart'][$productId]['quantity'] * $_SESSION['cart'][$productId]['unit_price'];
        }
    }

} elseif ($action === 'clear') {
    $_SESSION['cart'] = [];

} else {
    echo json_encode(['success' => false, 'message' => 'Aksi tidak dikenal']);
    exit;
}

$cart  = $_SESSION['cart'] ?? [];
$total = array_sum(array_column($cart, 'subtotal'));

echo json_encode([
    'success' => true,
    'cart'    => array_values($cart),
    'total'   => $total,
    'count'   => count($cart),
]);
