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

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

function table_exists(mysqli $mysqli, string $table): bool {
    $safe = $mysqli->real_escape_string($table);
    $res = $mysqli->query("SHOW TABLES LIKE '{$safe}'");
    return $res && $res->num_rows > 0;
}

$name = trim($_POST['name'] ?? '');
$unit = trim($_POST['unit'] ?? '');
$group_id = (int)($_POST['item_group_id'] ?? 0);
$subgroup_id = (int)($_POST['item_subgroup_id'] ?? 0);
$hasSubgroups = table_exists($mysqli, 'item_subgroups');

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

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

if ($hasSubgroups && $group_id > 0 && $subgroup_id > 0) {
    $stmt = $mysqli->prepare('INSERT INTO items (code, name, unit, item_group_id, item_subgroup_id) VALUES (?,?,?,?,?)');
    $stmt->bind_param('sssii', $code, $name, $unit, $group_id, $subgroup_id);
} elseif ($group_id > 0) {
    $stmt = $mysqli->prepare('INSERT INTO items (code, name, unit, item_group_id) VALUES (?,?,?,?)');
    $stmt->bind_param('sssi', $code, $name, $unit, $group_id);
} else {
    $stmt = $mysqli->prepare('INSERT INTO items (code, name, unit) VALUES (?,?,?)');
    $stmt->bind_param('sss', $code, $name, $unit);
}

if (!$stmt || !$stmt->execute()) {
    echo json_encode(['success' => false, 'error' => 'Spremanje nije uspjelo.']);
    exit;
}

$item_id = $stmt->insert_id;
$stmt->close();

echo json_encode([
    'success' => true,
    'item' => [
        'id' => $item_id,
        'code' => $code,
        'name' => $name,
        'unit' => $unit,
        'item_group_id' => $group_id,
        'item_subgroup_id' => $hasSubgroups ? $subgroup_id : null,
    ]
]);
