<?php
declare(strict_types=1);
require_once __DIR__ . '/_util.php';
date_default_timezone_set('Pacific/Auckland');

$body = json_decode(file_get_contents('php://input') ?: '', true);
if (!$body) json_response(["error"=>"Invalid JSON"], 400);

$category = safe_string($body['category'] ?? '');
$itemId = safe_string($body['itemId'] ?? '');
$delta = (int)($body['delta'] ?? 0);

$map = [
  "supplements" => "supplements.json",
  "groceries" => "groceries.json",
  "wishlist" => "wishlist.json"
];
if (!isset($map[$category])) json_response(["error"=>"Invalid category"], 400);
if ($itemId === '' || $delta === 0) json_response(["error"=>"Missing itemId or delta"], 400);

$path = data_path("inventory/" . $map[$category]);
$inv = read_json($path);
if (!$inv || !isset($inv['items'])) json_response(["error"=>"Inventory file missing"], 500);

$found = false;
foreach ($inv['items'] as &$it) {
  if (($it['id'] ?? '') === $itemId) {
    $it['qty'] = max(0, (int)($it['qty'] ?? 0) + $delta);
    $found = true;
    break;
  }
}
if (!$found) json_response(["error"=>"Item not found"], 404);

write_json_atomic($path, $inv);
json_response(["ok"=>true, "inventory"=>$inv]);