<?php
require_once __DIR__ . '/app/bootstrap.php';
$user = require_system_admin();
$pageTitle = 'Podešavanje zahteva';
$pageSubtitle = 'Kategorije, prioriteti, lokacije i njihov redosled';
$errors = [];

function ticket_setting_key(string $name): string
{
    $ascii = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $name);
    $key = strtolower((string)$ascii);
    $key = trim((string)preg_replace('/[^a-z0-9]+/', '_', $key), '_');
    return mb_substr($key !== '' ? $key : 'prioritet', 0, 32);
}

function unique_priority_key(PDO $pdo, string $name): string
{
    $base = ticket_setting_key($name);
    $candidate = $base;
    $suffix = 2;
    $stmt = $pdo->prepare('SELECT id FROM ticket_priorities WHERE priority_key = ? LIMIT 1');
    while (true) {
        $stmt->execute([$candidate]);
        if (!$stmt->fetch()) {
            return $candidate;
        }
        $candidate = mb_substr($base, 0, 35) . '_' . $suffix;
        $suffix++;
    }
}

function ensure_active_setting(PDO $pdo, string $table, int $id, int $newActive): void
{
    if ($newActive === 1) {
        return;
    }
    $allowed = ['ticket_categories', 'ticket_priorities', 'ticket_locations'];
    if (!in_array($table, $allowed, true)) {
        throw new RuntimeException('Nevalidna grupa podešavanja.');
    }
    $stmt = $pdo->prepare("SELECT is_active FROM $table WHERE id = ? LIMIT 1");
    $stmt->execute([$id]);
    $current = $stmt->fetchColumn();
    if ((int)$current !== 1) {
        return;
    }
    $activeCount = (int)$pdo->query("SELECT COUNT(*) FROM $table WHERE is_active = 1")->fetchColumn();
    if ($activeCount <= 1) {
        throw new RuntimeException('Najmanje jedna stavka u ovoj grupi mora ostati aktivna.');
    }
}

if (is_post()) {
    validate_csrf();
    $action = (string)($_POST['action'] ?? '');
    $pdo = db();

    try {
        if ($action === 'create_category') {
            $name = trim((string)($_POST['name'] ?? ''));
            $ticketCode = (string)($_POST['ticket_code'] ?? '4');
            $responsibleRoleCode = role_code_for_unit(strtoupper(trim((string)($_POST['responsible_role_code'] ?? 'OTHF'))), 'F');
            $sortOrder = (int)($_POST['sort_order'] ?? 100);
            if (mb_strlen($name) < 2 || mb_strlen($name) > 120 || !in_array($ticketCode, ['1', '2', '3', '4'], true) || !in_array($responsibleRoleCode, category_processing_role_codes(), true)) {
                throw new RuntimeException('Unesite validan naziv, oznaku i odgovornu ulogu kategorije.');
            }
            $stmt = $pdo->prepare('INSERT INTO ticket_categories (name, ticket_code, responsible_role_code, sort_order, is_active, created_at, updated_at) VALUES (?, ?, ?, ?, 1, NOW(), NOW())');
            $stmt->execute([$name, $ticketCode, $responsibleRoleCode, $sortOrder]);
            flash('success', 'Kategorija je dodata.');
        } elseif ($action === 'update_category') {
            $id = (int)($_POST['id'] ?? 0);
            $name = trim((string)($_POST['name'] ?? ''));
            $ticketCode = (string)($_POST['ticket_code'] ?? '4');
            $responsibleRoleCode = role_code_for_unit(strtoupper(trim((string)($_POST['responsible_role_code'] ?? 'OTHF'))), 'F');
            $sortOrder = (int)($_POST['sort_order'] ?? 100);
            $isActive = !empty($_POST['is_active']) ? 1 : 0;
            if ($id < 1 || mb_strlen($name) < 2 || mb_strlen($name) > 120 || !in_array($ticketCode, ['1', '2', '3', '4'], true) || !in_array($responsibleRoleCode, category_processing_role_codes(), true)) {
                throw new RuntimeException('Podaci kategorije nisu validni.');
            }
            ensure_active_setting($pdo, 'ticket_categories', $id, $isActive);
            $oldStmt = $pdo->prepare('SELECT name, responsible_role_code FROM ticket_categories WHERE id = ? LIMIT 1');
            $oldStmt->execute([$id]);
            $oldCategory = $oldStmt->fetch();
            if (!$oldCategory) {
                throw new RuntimeException('Kategorija nije pronađena.');
            }
            $oldName = (string)$oldCategory['name'];
            $oldResponsibleRole = role_code_for_unit((string)$oldCategory['responsible_role_code'], 'F');
            $pdo->beginTransaction();
            if ($oldName !== $name) {
                $eventStmt = $pdo->prepare("INSERT INTO ticket_events (ticket_id, user_id, event_type, old_value, new_value, created_at)
                    SELECT id, ?, 'category_changed', ?, ?, NOW() FROM tickets WHERE category = ?");
                $eventStmt->execute([(int)$user['id'], $oldName, $name, $oldName]);
            }
            if ($oldResponsibleRole !== $responsibleRoleCode) {
                foreach (array_keys(organization_unit_definitions()) as $organizationUnit) {
                    $oldRoleForUnit = role_code_for_unit($oldResponsibleRole, $organizationUnit);
                    $newRoleForUnit = role_code_for_unit($responsibleRoleCode, $organizationUnit);
                    $eventStmt = $pdo->prepare("INSERT INTO ticket_events (ticket_id, user_id, event_type, old_value, new_value, created_at)
                        SELECT id, ?, 'responsible_role_changed', ?, ?, NOW()
                        FROM tickets
                        WHERE category = ? AND responsible_role_code = ?");
                    $eventStmt->execute([(int)$user['id'], $oldRoleForUnit, $newRoleForUnit, $oldName, $oldRoleForUnit]);

                    $eventStmt = $pdo->prepare("INSERT INTO ticket_events (ticket_id, user_id, event_type, old_value, new_value, created_at)
                        SELECT id, ?, 'assigned_changed', CAST(assigned_to AS CHAR), NULL, NOW()
                        FROM tickets
                        WHERE category = ? AND responsible_role_code = ? AND assigned_to IS NOT NULL");
                    $eventStmt->execute([(int)$user['id'], $oldName, $oldRoleForUnit]);
                }
            }

            $stmt = $pdo->prepare('UPDATE ticket_categories SET name = ?, ticket_code = ?, responsible_role_code = ?, sort_order = ?, is_active = ?, updated_at = NOW() WHERE id = ?');
            $stmt->execute([$name, $ticketCode, $responsibleRoleCode, $sortOrder, $isActive, $id]);

            if ($oldResponsibleRole !== $responsibleRoleCode) {
                foreach (array_keys(organization_unit_definitions()) as $organizationUnit) {
                    $oldRoleForUnit = role_code_for_unit($oldResponsibleRole, $organizationUnit);
                    $newRoleForUnit = role_code_for_unit($responsibleRoleCode, $organizationUnit);
                    $stmt = $pdo->prepare('UPDATE tickets
                        SET responsible_role_code = ?, assigned_to = NULL, updated_at = NOW()
                        WHERE category = ? AND responsible_role_code = ?');
                    $stmt->execute([$newRoleForUnit, $oldName, $oldRoleForUnit]);
                }
            }
            if ($oldName !== $name) {
                $stmt = $pdo->prepare('UPDATE tickets SET category = ?, assigned_to = NULL, updated_at = NOW() WHERE category = ?');
                $stmt->execute([$name, $oldName]);
            }
            $pdo->commit();
            flash('success', 'Kategorija je sačuvana.');
        } elseif ($action === 'delete_category') {
            $id = (int)($_POST['id'] ?? 0);
            $stmt = $pdo->prepare('SELECT name FROM ticket_categories WHERE id = ? LIMIT 1');
            $stmt->execute([$id]);
            $name = trim((string)$stmt->fetchColumn());
            if ($name === '') {
                throw new RuntimeException('Kategorija nije pronađena.');
            }
            $usageStmt = $pdo->prepare('SELECT COUNT(*) FROM tickets WHERE category = ?');
            $usageStmt->execute([$name]);
            if ((int)$usageStmt->fetchColumn() > 0) {
                throw new RuntimeException('Kategorija se koristi na postojećim tiketima i ne može biti obrisana. Deaktivirajte je da se više ne nudi u novim zahtevima.');
            }
            ensure_active_setting($pdo, 'ticket_categories', $id, 0);
            $stmt = $pdo->prepare('DELETE FROM ticket_categories WHERE id = ?');
            $stmt->execute([$id]);
            flash('success', 'Kategorija je obrisana.');
        } elseif ($action === 'create_priority') {
            $name = trim((string)($_POST['name'] ?? ''));
            $description = trim((string)($_POST['description'] ?? ''));
            $sortOrder = (int)($_POST['sort_order'] ?? 100);
            if (mb_strlen($name) < 2 || mb_strlen($name) > 120 || mb_strlen($description) > 190) {
                throw new RuntimeException('Unesite validan naziv i opis prioriteta.');
            }
            $key = unique_priority_key($pdo, $name);
            $stmt = $pdo->prepare('INSERT INTO ticket_priorities (priority_key, name, description, sort_order, is_active, created_at, updated_at) VALUES (?, ?, ?, ?, 1, NOW(), NOW())');
            $stmt->execute([$key, $name, $description !== '' ? $description : null, $sortOrder]);
            flash('success', 'Prioritet je dodat.');
        } elseif ($action === 'update_priority') {
            $id = (int)($_POST['id'] ?? 0);
            $name = trim((string)($_POST['name'] ?? ''));
            $description = trim((string)($_POST['description'] ?? ''));
            $sortOrder = (int)($_POST['sort_order'] ?? 100);
            $isActive = !empty($_POST['is_active']) ? 1 : 0;
            if ($id < 1 || mb_strlen($name) < 2 || mb_strlen($name) > 120 || mb_strlen($description) > 190) {
                throw new RuntimeException('Podaci prioriteta nisu validni.');
            }
            ensure_active_setting($pdo, 'ticket_priorities', $id, $isActive);
            $stmt = $pdo->prepare('UPDATE ticket_priorities SET name = ?, description = ?, sort_order = ?, is_active = ?, updated_at = NOW() WHERE id = ?');
            $stmt->execute([$name, $description !== '' ? $description : null, $sortOrder, $isActive, $id]);
            flash('success', 'Prioritet je sačuvan.');
        } elseif ($action === 'delete_priority') {
            $id = (int)($_POST['id'] ?? 0);
            $stmt = $pdo->prepare('SELECT priority_key, name FROM ticket_priorities WHERE id = ? LIMIT 1');
            $stmt->execute([$id]);
            $priority = $stmt->fetch();
            if (!$priority) {
                throw new RuntimeException('Prioritet nije pronađen.');
            }
            $usageStmt = $pdo->prepare('SELECT COUNT(*) FROM tickets WHERE priority = ?');
            $usageStmt->execute([(string)$priority['priority_key']]);
            if ((int)$usageStmt->fetchColumn() > 0) {
                throw new RuntimeException('Prioritet se koristi na postojećim tiketima i ne može biti obrisan. Deaktivirajte ga da se više ne nudi u novim zahtevima.');
            }
            ensure_active_setting($pdo, 'ticket_priorities', $id, 0);
            $stmt = $pdo->prepare('DELETE FROM ticket_priorities WHERE id = ?');
            $stmt->execute([$id]);
            flash('success', 'Prioritet je obrisan.');
        } elseif ($action === 'create_location') {
            $name = trim((string)($_POST['name'] ?? ''));
            $sortOrder = (int)($_POST['sort_order'] ?? 100);
            if (mb_strlen($name) < 2 || mb_strlen($name) > 190) {
                throw new RuntimeException('Unesite validan naziv odeljenja ili lokacije.');
            }
            $stmt = $pdo->prepare('INSERT INTO ticket_locations (name, sort_order, is_active, created_at, updated_at) VALUES (?, ?, 1, NOW(), NOW())');
            $stmt->execute([$name, $sortOrder]);
            flash('success', 'Odeljenje / lokacija je dodato.');
        } elseif ($action === 'update_location') {
            $id = (int)($_POST['id'] ?? 0);
            $name = trim((string)($_POST['name'] ?? ''));
            $sortOrder = (int)($_POST['sort_order'] ?? 100);
            $isActive = !empty($_POST['is_active']) ? 1 : 0;
            if ($id < 1 || mb_strlen($name) < 2 || mb_strlen($name) > 190) {
                throw new RuntimeException('Podaci odeljenja / lokacije nisu validni.');
            }
            ensure_active_setting($pdo, 'ticket_locations', $id, $isActive);
            $oldStmt = $pdo->prepare('SELECT name FROM ticket_locations WHERE id = ? LIMIT 1');
            $oldStmt->execute([$id]);
            $oldName = (string)$oldStmt->fetchColumn();
            if ($oldName === '') {
                throw new RuntimeException('Odeljenje / lokacija nije pronađeno.');
            }
            $pdo->beginTransaction();
            $stmt = $pdo->prepare('UPDATE ticket_locations SET name = ?, sort_order = ?, is_active = ?, updated_at = NOW() WHERE id = ?');
            $stmt->execute([$name, $sortOrder, $isActive, $id]);
            if ($oldName !== $name) {
                $stmt = $pdo->prepare('UPDATE tickets SET department_location = ? WHERE department_location = ?');
                $stmt->execute([$name, $oldName]);
            }
            $pdo->commit();
            flash('success', 'Odeljenje / lokacija je sačuvano.');
        } elseif ($action === 'delete_location') {
            $id = (int)($_POST['id'] ?? 0);
            $stmt = $pdo->prepare('SELECT name FROM ticket_locations WHERE id = ? LIMIT 1');
            $stmt->execute([$id]);
            $name = trim((string)$stmt->fetchColumn());
            if ($name === '') {
                throw new RuntimeException('Odeljenje / lokacija nije pronađeno.');
            }
            $usageStmt = $pdo->prepare('SELECT COUNT(*) FROM tickets WHERE department_location = ?');
            $usageStmt->execute([$name]);
            if ((int)$usageStmt->fetchColumn() > 0) {
                throw new RuntimeException('Odeljenje / lokacija se koristi na postojećim tiketima i ne može biti obrisano. Deaktivirajte ga da se više ne nudi u novim zahtevima.');
            }
            ensure_active_setting($pdo, 'ticket_locations', $id, 0);
            $stmt = $pdo->prepare('DELETE FROM ticket_locations WHERE id = ?');
            $stmt->execute([$id]);
            flash('success', 'Odeljenje / lokacija je obrisano.');
        } else {
            throw new RuntimeException('Nepoznata akcija.');
        }
        redirect('ticket_settings.php');
    } catch (Throwable $e) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        if ($e instanceof PDOException) {
            $errors[] = (string)$e->getCode() === '23000' ? 'Stavka sa tim nazivom već postoji.' : 'Podešavanje nije sačuvano zbog greške baze podataka.';
        } else {
            $errors[] = $e->getMessage();
        }
    }
}

$categories = ticket_category_records(false);
$priorities = ticket_priority_records(false);
$locations = ticket_location_records(false);
require_once __DIR__ . '/app/header.php';
?>
<section class="settings-intro card card-pad">
    <span class="badge">Administracija</span>
    <h2>Podešavanje zahteva</h2>
    <p>Aktivne stavke se prikazuju korisnicima prema broju u polju „Redosled”. Manji broj se prikazuje ranije.</p>
</section>

<?php foreach ($errors as $error): ?><div class="alert alert-danger"><?= e($error) ?></div><?php endforeach; ?>

<section class="ticket-settings-grid">
    <article class="card card-pad settings-panel admin-request-categories">
        <div class="section-heading compact-heading"><div><span class="badge">01</span><h2>Kategorije</h2><p>Oznaka određuje prvu cifru u broju tiketa.</p></div></div>
        <form method="post" class="settings-create-form">
            <?= csrf_field() ?><input type="hidden" name="action" value="create_category">
            <label>Naziv<input type="text" name="name" required maxlength="120" placeholder="Nova kategorija"></label>
            <label>Oznaka<select name="ticket_code"><option value="1">1 · ICT</option><option value="2">2 · Prostor</option><option value="3">3 · Vozila</option><option value="4">4 · Ostalo</option></select></label>
            <label>Odgovorna funkcija<select name="responsible_role_code"><?php foreach (category_processing_role_codes() as $code): ?><option value="<?= e($code) ?>"><?= e(functional_role_label($code)) ?></option><?php endforeach; ?></select><small>Fondacija/DS varijanta se bira automatski prema organizacionoj pripadnosti tiketa.</small></label>
            <label>Redosled<input type="number" name="sort_order" value="100" step="10"></label>
            <button class="button button-primary" type="submit">Dodaj kategoriju</button>
        </form>
        <div class="settings-items">
            <?php foreach ($categories as $item): ?>
                <form method="post" class="settings-item-form">
                    <?= csrf_field() ?><input type="hidden" name="id" value="<?= (int)$item['id'] ?>">
                    <label>Naziv<input type="text" name="name" required maxlength="120" value="<?= e($item['name']) ?>"></label>
                    <label>Oznaka<select name="ticket_code"><?php foreach (['1' => '1 · ICT', '2' => '2 · Prostor', '3' => '3 · Vozila', '4' => '4 · Ostalo'] as $code => $label): ?><option value="<?= $code ?>" <?= safe_selected($item['ticket_code'], $code) ?>><?= e($label) ?></option><?php endforeach; ?></select></label>
                    <label>Odgovorna funkcija<select name="responsible_role_code"><?php foreach (category_processing_role_codes() as $code): ?><option value="<?= e($code) ?>" <?= safe_selected(role_code_for_unit((string)($item['responsible_role_code'] ?? 'OTHF'), 'F'), $code) ?>><?= e(functional_role_label($code)) ?></option><?php endforeach; ?></select><small>Fondacija/DS varijanta se bira automatski prema organizacionoj pripadnosti tiketa.</small></label>
                    <label>Redosled<input type="number" name="sort_order" value="<?= (int)$item['sort_order'] ?>" step="10"></label>
                    <label class="settings-active"><input type="checkbox" name="is_active" value="1" <?= (int)$item['is_active'] === 1 ? 'checked' : '' ?>> Aktivna</label>
                    <div class="settings-row-actions">
                        <button class="button button-light" type="submit" name="action" value="update_category">Sačuvaj</button>
                        <button class="button button-danger" type="submit" name="action" value="delete_category" formnovalidate data-confirm="Da li ste sigurni da želite trajno da obrišete ovu kategoriju?">Obriši</button>
                    </div>
                </form>
            <?php endforeach; ?>
        </div>
    </article>

    <article class="card card-pad settings-panel admin-request-priorities">
        <div class="section-heading compact-heading"><div><span class="badge">02</span><h2>Prioriteti</h2><p>Opis se prikazuje korisniku u padajućoj listi.</p></div></div>
        <form method="post" class="settings-create-form settings-priority-form">
            <?= csrf_field() ?><input type="hidden" name="action" value="create_priority">
            <label>Naziv<input type="text" name="name" required maxlength="120" placeholder="Novi prioritet"></label>
            <label>Opis / rok<input type="text" name="description" maxlength="190" placeholder="npr. rešava se u roku od 3 dana"></label>
            <label>Redosled<input type="number" name="sort_order" value="100" step="10"></label>
            <button class="button button-primary" type="submit">Dodaj prioritet</button>
        </form>
        <div class="settings-items">
            <?php foreach ($priorities as $item): ?>
                <form method="post" class="settings-item-form settings-priority-form">
                    <?= csrf_field() ?><input type="hidden" name="id" value="<?= (int)$item['id'] ?>">
                    <label>Naziv<input type="text" name="name" required maxlength="120" value="<?= e($item['name']) ?>"></label>
                    <label>Opis / rok<input type="text" name="description" maxlength="190" value="<?= e($item['description'] ?? '') ?>"></label>
                    <label>Redosled<input type="number" name="sort_order" value="<?= (int)$item['sort_order'] ?>" step="10"></label>
                    <label class="settings-active"><input type="checkbox" name="is_active" value="1" <?= (int)$item['is_active'] === 1 ? 'checked' : '' ?>> Aktivna</label>
                    <div class="settings-row-actions">
                        <button class="button button-light" type="submit" name="action" value="update_priority">Sačuvaj</button>
                        <button class="button button-danger" type="submit" name="action" value="delete_priority" formnovalidate data-confirm="Da li ste sigurni da želite trajno da obrišete ovaj prioritet?">Obriši</button>
                    </div>
                </form>
            <?php endforeach; ?>
        </div>
    </article>

    <article class="card card-pad settings-panel settings-panel-wide">
        <div class="section-heading compact-heading"><div><span class="badge">03</span><h2>Odeljenja / Lokacije</h2><p>Naziv i adresa prikazuju se u formi novog zahteva.</p></div></div>
        <form method="post" class="settings-create-form settings-location-form">
            <?= csrf_field() ?><input type="hidden" name="action" value="create_location">
            <label>Naziv i adresa<input type="text" name="name" required maxlength="190" placeholder="Nova lokacija"></label>
            <label>Redosled<input type="number" name="sort_order" value="100" step="10"></label>
            <button class="button button-primary" type="submit">Dodaj lokaciju</button>
        </form>
        <div class="settings-items">
            <?php foreach ($locations as $item): ?>
                <form method="post" class="settings-item-form settings-location-form">
                    <?= csrf_field() ?><input type="hidden" name="id" value="<?= (int)$item['id'] ?>">
                    <label>Naziv i adresa<input type="text" name="name" required maxlength="190" value="<?= e($item['name']) ?>"></label>
                    <label>Redosled<input type="number" name="sort_order" value="<?= (int)$item['sort_order'] ?>" step="10"></label>
                    <label class="settings-active"><input type="checkbox" name="is_active" value="1" <?= (int)$item['is_active'] === 1 ? 'checked' : '' ?>> Aktivna</label>
                    <div class="settings-row-actions">
                        <button class="button button-light" type="submit" name="action" value="update_location">Sačuvaj</button>
                        <button class="button button-danger" type="submit" name="action" value="delete_location" formnovalidate data-confirm="Da li ste sigurni da želite trajno da obrišete ovo odeljenje / lokaciju?">Obriši</button>
                    </div>
                </form>
            <?php endforeach; ?>
        </div>
    </article>
</section>
<?php require_once __DIR__ . '/app/footer.php'; ?>
