<?php
require_once '../includes/config.php';

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

// Check if user is logged in
if (!isUserLoggedIn()) {
    echo json_encode(['success' => false, 'message' => 'Silakan login terlebih dahulu']);
    exit;
}

// Check if request is POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

// Get product ID
$product_id = isset($_POST['product_id']) ? (int)$_POST['product_id'] : 0;

// Validate product ID
if ($product_id <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid product ID']);
    exit;
}

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

// Check if product in cart
if (isset($_SESSION['cart'][$product_id])) {
    // Remove product from cart
    unset($_SESSION['cart'][$product_id]);
    
    // Calculate new total
    $totalAmount = 0;
    $isEmpty = true;
    
    if (!empty($_SESSION['cart'])) {
        try {
            $conn = connectDB();
            foreach ($_SESSION['cart'] as $id => $qty) {
                $stmt = $conn->prepare("SELECT price FROM products WHERE product_id = :id");
                $stmt->bindParam(':id', $id);
                $stmt->execute();
                $productPrice = $stmt->fetch(PDO::FETCH_ASSOC);
                $totalAmount += $qty * $productPrice['price'];
            }
            $isEmpty = false;
        } catch (PDOException $e) {
            echo json_encode(['success' => false, 'message' => 'Terjadi kesalahan: ' . $e->getMessage()]);
            exit;
        }
    }
    
    echo json_encode([
        'success' => true, 
        'message' => 'Produk berhasil dihapus dari keranjang',
        'total' => $totalAmount,
        'isEmpty' => $isEmpty
    ]);
} else {
    echo json_encode(['success' => false, 'message' => 'Produk tidak ada dalam keranjang']);
}
?> 