<?php
session_start();

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

$cart = &$_SESSION['cart'];

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

if ($index !== null && isset($cart[$index])) {
  switch ($action) {
    case 'increase':
      $cart[$index]['quantity'] += 1;
      break;

    case 'decrease':
      if ($cart[$index]['quantity'] > 1) {
        $cart[$index]['quantity'] -= 1;
      } else {
        unset($cart[$index]);
        $cart = array_values($cart); // reindex array
      }
      break;

    case 'remove':
      unset($cart[$index]);
      $cart = array_values($cart); // reindex array
      break;
  }
}

header('Location: cart.php');
exit();
