<?php
require_once 'config.php';
require_login();
require_permission('items');

header('Content-Type: application/json; charset=utf-8');

$name = trim($_POST['name'] ?? '');
$unit = trim($_POST['unit'] ?? '');
$group_id = (int)($_POST['item_group_id'] ?? 0);

if ($name === '' || $unit === '') {
    echo json_encode(['success' => false, 'error' => 'Naziv i JM su obavezni.']);
    exit;
}

// next code
$res = $mysqli->query("SELECT MAX(CAST(code AS UNSIGNED)) AS maxcode FROM items");
$row = $res->fetch_assoc();
$next = (int)($row['maxcode'] ?? 0) + 1;
$code = (string)$next;

if ($group_id <= 0) {
    $stmt = $mysqli->prepare('INSERT INTO items (code, name, unit) VALUES (?,?,?)');
    $stmt->bind_param('sss', $code, $name, $unit);
} else {
    $stmt = $mysqli->prepare('INSERT INTO items (code, name, unit, item_group_id) VALUES (?,?,?,?)');
    $stmt->bind_param('sssi', $code, $name, $unit, $group_id);
}
$stmt->execute();
$item_id = $stmt->insert_id;
$stmt->close();

echo json_encode([
    'success' => true,
    'item' => [
        'id' => $item_id,
        'code' => $code,
        'name' => $name,
        'unit' => $unit
    ]
]);
