<?php
// unit/get_inventory.php
ob_start();
session_start();

require_once(__DIR__ . '/../config.php');
require_once(__DIR__ . '/../functions.php');

header('Content-Type: application/json');

if (!check_login()) {
  echo json_encode(['success' => false, 'error' => 'auth']);
  exit;
}

$uid = isset($_GET['uid']) ? intval($_GET['uid']) : (isset($_POST['uid']) ? intval($_POST['uid']) : 0);
if ($uid <= 0) {
  echo json_encode(['success' => false, 'error' => 'invalid_uid']);
  exit;
}

$items = [];
$stmt = $link->prepare("SELECT id, item_name, item_quantity FROM unit_inventory WHERE uid = ? ORDER BY id ASC");
$stmt->bind_param("i", $uid);
$stmt->execute();
$res = $stmt->get_result();
while ($row = $res->fetch_assoc()) {
  $items[] = [
    'id' => (int)$row['id'],
    'item_name' => $row['item_name'],
    'item_quantity' => (int)$row['item_quantity']
  ];
}
$stmt->close();

echo json_encode([
  'success' => true,
  'count'   => count($items),
  'items'   => $items
]);
