<?php
session_start();

// Database connection
include('shikanisha.kts.php');

// Check if POST data is available
if (isset($_POST['id']) && isset($_POST['change']) && isset($_POST['session'])) {
    $id = intval($_POST['id']);
    $change = intval($_POST['change']);
    $sessionType = $_POST['session']; // "dispose" or "request"

    // Determine session variable name based on session type
    if ($sessionType === 'dispose') {
        $sessionVar = 'dispose_items';
    } elseif ($sessionType === 'request') {
        $sessionVar = 'request';
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Invalid session type.']);
        exit;
    }

    // Initialize session variable if not set
    if (!isset($_SESSION[$sessionVar])) {
        $_SESSION[$sessionVar] = [];
    }

    // Update item quantity in session
    $itemFound = false;
    foreach ($_SESSION[$sessionVar] as &$item) {
        if ($item['id'] === $id) {
            $item['quantity'] += $change;
            if ($item['quantity'] <= 0) {
                // Remove item if quantity is zero or less
                $item = null;
            }
            $itemFound = true;
            break;
        }
    }

    if (!$itemFound) {
        // If item is not found in session, you may want to add it with the specified quantity
        $_SESSION[$sessionVar][] = ['id' => $id, 'quantity' => max($change, 0)];
    }

    // Remove null values
    $_SESSION[$sessionVar] = array_filter($_SESSION[$sessionVar]);

    // Send success response
    $response = ['status' => 'success'];
    echo json_encode($response);
} else {
    // Send error response
    $response = ['status' => 'error', 'message' => 'Invalid input data.'];
    echo json_encode($response);
}
?>
