<?php
session_start();

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

$pid    = $_POST['product_id'];
$name   = $_POST['product_name'];
$weight = $_POST['weight'];
$price  = $_POST['price'];
$image  = $_POST['image'];

$key = $pid . "_" . $weight;

if (isset($_SESSION['cart'][$key])) {
    $_SESSION['cart'][$key]['qty'] += 1;
} else {
    $_SESSION['cart'][$key] = [
        'product_id' => $pid,
        'name' => $name,
        'weight' => $weight,
        'price' => $price,
        'qty' => 1,
        'image' => $image
    ];
}

/* return total qty for header */
echo array_sum(array_column($_SESSION['cart'], 'qty'));
