<?php

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}


function add_to_cart($product_id, $quantity = 1) {
    if (!isset($_SESSION['cart'])) {
        $_SESSION['cart'] = [];
    }
    if (isset($_SESSION['cart'][$product_id])) {
        $_SESSION['cart'][$product_id] += $quantity;
    } else {
        $_SESSION['cart'][$product_id] = $quantity;
    }
}


function remove_from_cart($product_id) {
    if (isset($_SESSION['cart'][$product_id])) {
        unset($_SESSION['cart'][$product_id]);
    }
}


function update_cart($product_id, $quantity) {
    if (isset($_SESSION['cart'][$product_id])) {
        if ($quantity <= 0) {
            remove_from_cart($product_id);
        } else {
            $_SESSION['cart'][$product_id] = $quantity;
        }
    }
}


function total_items() {
    return isset($_SESSION['cart']) ? array_sum($_SESSION['cart']) : 0;
}


function total_price($conn) {
    $total = 0;
    if (isset($_SESSION['cart']) && count($_SESSION['cart']) > 0) {
        $ids = implode(',', array_keys($_SESSION['cart']));
        $query = "SELECT id, harga FROM produk WHERE id IN ($ids)";
        $result = mysqli_query($conn, $query);
        while ($row = mysqli_fetch_assoc($result)) {
            $pid = $row['id'];
            $total += $row['harga'] * $_SESSION['cart'][$pid];
        }
    }
    return $total;
}
?>
