<?php
require_once __DIR__ . '/app/bootstrap.php';
$user = require_auth();
$ticketId = (int)($_GET['id'] ?? 0);

$stmt = db()->prepare('SELECT t.*, u.name AS requester_name, u.email AS requester_email, a.name AS assigned_name
    FROM tickets t
    JOIN users u ON u.id = t.user_id
    LEFT JOIN users a ON a.id = t.assigned_to
    WHERE t.id = ? LIMIT 1');
$stmt->execute([$ticketId]);
$ticket = $stmt->fetch();

if (!$ticket || !can_view_ticket($ticket, $user)) {
    require __DIR__ . '/404.php';
    exit;
}

$canManage = can_manage_ticket($ticket, $user);
$canManageParticipants = can_manage_ticket_participants($ticket, $user);
$ticketOrganizationUnit = ticket_organization_unit($ticket) ?? 'F';
$errors = [];
$selectedParticipantUsers = $canManageParticipants
    ? participant_users_by_ids(normalize_participant_ids($_POST['participant_ids'] ?? []))
    : [];
$manageablePriorities = ticket_form_priority_options();
if (!array_key_exists((string)$ticket['priority'], $manageablePriorities)) {
    $manageablePriorities[(string)$ticket['priority']] = priority_label((string)$ticket['priority']);
}
$manageableCategories = category_options();
if (!array_key_exists((string)$ticket['category'], $manageableCategories)) {
    $manageableCategories[(string)$ticket['category']] = (string)$ticket['category'];
}

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

    if ($action === 'delete_ticket' && is_system_admin($user)) {
        try {
            $attachmentStmt = db()->prepare('SELECT stored_name FROM ticket_attachments WHERE ticket_id = ?');
            $attachmentStmt->execute([$ticketId]);
            $attachmentFiles = $attachmentStmt->fetchAll();
            db()->beginTransaction();

            $stmt = db()->prepare('DELETE FROM notifications WHERE link_url = ? OR link_url LIKE ?');
            $stmt->execute(['ticket_view.php?id=' . $ticketId, '%ticket_view.php?id=' . $ticketId]);

            $stmt = db()->prepare('DELETE FROM ticket_comments WHERE ticket_id = ?');
            $stmt->execute([$ticketId]);

            $stmt = db()->prepare('DELETE FROM ticket_events WHERE ticket_id = ?');
            $stmt->execute([$ticketId]);

            $stmt = db()->prepare('DELETE FROM tickets WHERE id = ?');
            $stmt->execute([$ticketId]);

            db()->commit();
            foreach ($attachmentFiles as $attachmentFile) {
                $attachmentPath = __DIR__ . '/uploads/tickets/' . basename((string)$attachmentFile['stored_name']);
                if (is_file($attachmentPath)) {
                    unlink($attachmentPath);
                }
            }
            flash('success', 'Tiket ' . $ticket['ticket_no'] . ' je trajno obrisan iz sistema. Više nije vidljiv ni korisniku.');
            redirect('tickets.php');
        } catch (Throwable $e) {
            if (db()->inTransaction()) {
                db()->rollBack();
            }
            $errors[] = 'Tiket nije mogao biti obrisan. Proverite bazu i pokušajte ponovo.';
        }
    }

    if ($action === 'add_participant') {
        if (!$canManageParticipants) {
            security_log_event('ticket_participant_add_forbidden', [
                'ticket_id' => $ticketId,
                'user_id' => (int)$user['id'],
            ]);
            http_response_code(403);
            exit('Nemate pravo da dodajete učesnike na ovaj tiket.');
        }
        $participantIds = normalize_participant_ids($_POST['participant_ids'] ?? []);
        if (!$participantIds) {
            $errors[] = 'Pretražite i izaberite najmanje jednog učesnika.';
        }
        if (!$errors) {
            try {
                db()->beginTransaction();
                $addedParticipants = add_ticket_participants(db(), $ticketId, (int)$user['id'], (int)$ticket['user_id'], $participantIds);
                foreach ($addedParticipants as $participant) {
                    audit_ticket_event($ticketId, (int)$user['id'], 'participant_added', null, (string)$participant['name']);
                }
                db()->commit();

                if (!$addedParticipants) {
                    flash('info', 'Izabrani korisnici su već učesnici ili je izabran podnosilac tiketa.');
                } else {
                    foreach ($addedParticipants as $participant) {
                        notify_user((int)$participant['id'], 'Dodati ste kao učesnik', $user['name'] . ' vas je dodao/la kao učesnika na zahtev ' . $ticket['ticket_no'] . ': ' . $ticket['title'], 'ticket_view.php?id=' . $ticketId);
                    }
                    flash('success', count($addedParticipants) === 1 ? 'Učesnik je dodat.' : 'Učesnici su dodati.');
                }
                redirect('ticket_view.php?id=' . $ticketId);
            } catch (Throwable $e) {
                if (db()->inTransaction()) {
                    db()->rollBack();
                }
                $errors[] = 'Učesnike nije moguće sačuvati. Proverite da li je importovan upgrade_v3_15.sql.';
            }
        }
    }

    if ($action === 'comment') {
        $comment = trim((string)($_POST['comment'] ?? ''));
        $isInternal = $canManage && !empty($_POST['is_internal']) ? 1 : 0;
        $commentAttachments = normalized_uploaded_files('attachments');
        $errors = array_merge($errors, validate_ticket_attachments($commentAttachments));

        if ($comment !== '' && mb_strlen($comment) < 2) {
            $errors[] = 'Komentar mora imati najmanje 2 karaktera.';
        }
        if ($comment === '' && !$commentAttachments) {
            $errors[] = 'Unesite komentar ili dodajte najmanje jedan prilog.';
        }

        if (!$errors) {
            $savedPaths = [];
            try {
                db()->beginTransaction();
                if ($comment !== '') {
                    $stmt = db()->prepare('INSERT INTO ticket_comments (ticket_id, user_id, comment, is_internal, created_at) VALUES (?, ?, ?, ?, NOW())');
                    $stmt->execute([$ticketId, $user['id'], $comment, $isInternal]);
                    audit_ticket_event($ticketId, (int)$user['id'], 'comment', null, $isInternal ? 'internal' : 'public');
                }
                if ($commentAttachments) {
                    $savedPaths = store_ticket_attachments(db(), $ticketId, (int)$user['id'], $commentAttachments, $isInternal);
                    audit_ticket_event($ticketId, (int)$user['id'], 'attachment_added', $isInternal ? 'internal' : 'public', (string)count($commentAttachments));
                }
                $ticketReopened = !$canManage && (string)$ticket['status'] === 'closed';
                if ($ticketReopened) {
                    $stmt = db()->prepare('UPDATE tickets SET status = "open", closed_at = NULL, updated_at = NOW() WHERE id = ?');
                    audit_ticket_event($ticketId, (int)$user['id'], 'status_changed', 'closed', 'open');
                } else {
                    $stmt = db()->prepare('UPDATE tickets SET updated_at = NOW() WHERE id = ?');
                }
                $stmt->execute([$ticketId]);
                db()->commit();

                try {
                    if (!$isInternal) {
                        $notifTitle = 'Nova dopuna zahteva ' . $ticket['ticket_no'];
                        $notifMessage = $user['name'] . ' je dodao/la komentar ili prilog na zahtev: ' . $ticket['title'];
                        if ($ticketReopened) {
                            $notifTitle = 'Tiket ponovo otvoren ' . $ticket['ticket_no'];
                            $notifMessage .= ' Zatvoreni tiket je automatski ponovo otvoren.';
                        }
                        if ((int)$ticket['user_id'] !== (int)$user['id']) {
                            notify_user((int)$ticket['user_id'], $notifTitle, $notifMessage, 'ticket_view.php?id=' . $ticketId);
                        }
                        if (!empty($ticket['assigned_to']) && (int)$ticket['assigned_to'] !== (int)$user['id'] && (int)$ticket['assigned_to'] !== (int)$ticket['user_id']) {
                            notify_user((int)$ticket['assigned_to'], $notifTitle, $notifMessage, 'ticket_view.php?id=' . $ticketId);
                        }
                        notify_responsible_role((string)$ticket['responsible_role_code'], $notifTitle, $notifMessage, 'ticket_view.php?id=' . $ticketId, [
                            (int)$user['id'],
                            (int)$ticket['user_id'],
                            (int)($ticket['assigned_to'] ?? 0),
                        ]);
                        notify_ticket_participants($ticketId, $notifTitle, $notifMessage, 'ticket_view.php?id=' . $ticketId, [
                            (int)$user['id'],
                            (int)$ticket['user_id'],
                            (int)($ticket['assigned_to'] ?? 0),
                        ]);
                    }
                } catch (Throwable $e) {
                }
                $successMessage = $comment !== '' && $commentAttachments ? 'Komentar i prilozi su dodati.' : ($commentAttachments ? 'Prilozi su dodati.' : 'Komentar je dodat.');
                if ($ticketReopened) {
                    $successMessage .= ' Zatvoreni tiket je automatski ponovo otvoren.';
                }
                flash('success', $successMessage);
                redirect('ticket_view.php?id=' . $ticketId);
            } catch (Throwable $e) {
                if (db()->inTransaction()) {
                    db()->rollBack();
                }
                foreach ($savedPaths as $path) {
                    if (is_file($path)) {
                        unlink($path);
                    }
                }
                $errors[] = 'Komentar ili prilog nije moguće sačuvati. Pokušajte ponovo.';
            }
        }
    }

    if ($action === 'claim' && $canManage) {
        if (!user_has_role($user, (string)$ticket['responsible_role_code'])) {
            $errors[] = 'Tiket može preuzeti samo korisnik sa odgovarajućom poslovnom ulogom.';
        }
        if (!$errors) {
            $oldAssigned = (string)($ticket['assigned_to'] ?? '');
            $stmt = db()->prepare('UPDATE tickets SET assigned_to = ?, updated_at = NOW() WHERE id = ?');
            $stmt->execute([(int)$user['id'], $ticketId]);
            if ($oldAssigned !== (string)$user['id']) {
                audit_ticket_event($ticketId, (int)$user['id'], 'assigned_changed', $oldAssigned, (string)$user['id']);
                audit_ticket_event($ticketId, (int)$user['id'], 'ticket_claimed', null, (string)$user['id']);
            }
            flash('success', 'Tiket je preuzet i dodeljen vama.');
            redirect('ticket_view.php?id=' . $ticketId);
        }
    }

    if ($action === 'update' && $canManage) {
        $newStatus = (string)($_POST['status'] ?? $ticket['status']);
        $newPriority = (string)($_POST['priority'] ?? $ticket['priority']);
        $newCategory = trim((string)($_POST['category'] ?? $ticket['category']));
        $newResponsibleRole = category_responsible_role_code($newCategory, $ticketOrganizationUnit);
        $assignedTo = ($_POST['assigned_to'] ?? '') === '' ? null : (int)$_POST['assigned_to'];

        if (!array_key_exists($newStatus, status_options())) {
            $errors[] = 'Izabran je nevalidan status.';
        }
        if (!array_key_exists($newPriority, $manageablePriorities)) {
            $errors[] = 'Izabran je nevalidan prioritet.';
        }
        if (!array_key_exists($newCategory, $manageableCategories)) {
            $errors[] = 'Izabrana je nevalidna kategorija.';
        }
        if ($assignedTo !== null) {
            $assignedCheck = db()->prepare('SELECT 1
                FROM users u
                JOIN user_roles ur ON ur.user_id = u.id
                JOIN roles r ON r.id = ur.role_id AND r.is_active = 1
                WHERE u.id = ? AND u.is_active = 1 AND r.role_code = ?
                LIMIT 1');
            $assignedCheck->execute([$assignedTo, $newResponsibleRole]);
            if (!$assignedCheck->fetchColumn()) {
                if ($newResponsibleRole !== (string)$ticket['responsible_role_code']) {
                    $assignedTo = null;
                } else {
                    $errors[] = 'Izabrani korisnik nije aktivan ili nema odgovarajuću poslovnu ulogu.';
                }
            }
        }

        if (!$errors) {
            $closedAtSql = ($newStatus === 'closed' && $ticket['status'] !== 'closed') ? ', closed_at = NOW()' : '';
            if ($newStatus !== 'closed') {
                $closedAtSql = ', closed_at = NULL';
            }
            $stmt = db()->prepare("UPDATE tickets SET status = ?, priority = ?, category = ?, responsible_role_code = ?, assigned_to = ?, updated_at = NOW() $closedAtSql WHERE id = ?");
            $stmt->execute([$newStatus, $newPriority, $newCategory, $newResponsibleRole, $assignedTo, $ticketId]);

            if ($ticket['status'] !== $newStatus) {
                audit_ticket_event($ticketId, (int)$user['id'], 'status_changed', $ticket['status'], $newStatus);
            }
            if ($ticket['priority'] !== $newPriority) {
                audit_ticket_event($ticketId, (int)$user['id'], 'priority_changed', $ticket['priority'], $newPriority);
            }
            if ((string)$ticket['assigned_to'] !== (string)$assignedTo) {
                audit_ticket_event($ticketId, (int)$user['id'], 'assigned_changed', (string)$ticket['assigned_to'], (string)$assignedTo);
            }
            if ((string)$ticket['category'] !== $newCategory) {
                audit_ticket_event($ticketId, (int)$user['id'], 'category_changed', (string)$ticket['category'], $newCategory);
            }
            if ((string)$ticket['responsible_role_code'] !== $newResponsibleRole) {
                audit_ticket_event($ticketId, (int)$user['id'], 'responsible_role_changed', (string)$ticket['responsible_role_code'], $newResponsibleRole);
                notify_responsible_role($newResponsibleRole, 'Tiket prosleđen vašem timu ' . $ticket['ticket_no'], $user['name'] . ' je prosledio/la tiket kategoriji „' . $newCategory . '”.', 'ticket_view.php?id=' . $ticketId, [
                    (int)$user['id'],
                    (int)($assignedTo ?? 0),
                ]);
            }

            $updateMessage = 'Zahtev ' . $ticket['ticket_no'] . ' je ažuriran. Status: ' . status_label($newStatus) . ', prioritet: ' . priority_label($newPriority) . '.';
            if ((int)$ticket['user_id'] !== (int)$user['id']) {
                notify_user((int)$ticket['user_id'], 'Ažuriran je vaš zahtev', $updateMessage, 'ticket_view.php?id=' . $ticketId);
            }
            if (!empty($assignedTo) && (int)$assignedTo !== (int)$user['id'] && (int)$assignedTo !== (int)$ticket['user_id']) {
                notify_user((int)$assignedTo, 'Dodeljen ili ažuriran zahtev', $updateMessage, 'ticket_view.php?id=' . $ticketId);
            }
            if ($ticket['status'] !== $newStatus) {
                $statusMessage = $user['name'] . ' je promenio/la status zahteva ' . $ticket['ticket_no'] . ' sa „' . status_label((string)$ticket['status']) . '” na „' . status_label($newStatus) . '”.';
                notify_ticket_participants($ticketId, 'Promenjen status zahteva ' . $ticket['ticket_no'], $statusMessage, 'ticket_view.php?id=' . $ticketId, [
                    (int)$user['id'],
                    (int)$ticket['user_id'],
                    (int)($assignedTo ?? 0),
                ]);
            }

            flash('success', 'Tiket je ažuriran.');
            if (!is_system_admin($user) && !user_has_role($user, $newResponsibleRole) && (int)$ticket['user_id'] !== (int)$user['id']) {
                redirect('tickets.php');
            }
            redirect('ticket_view.php?id=' . $ticketId);
        }
    }
}

$commentSql = 'SELECT c.*, u.name AS author_name, u.is_system_admin AS author_is_system_admin,
        GROUP_CONCAT(DISTINCT r.role_code ORDER BY r.sort_order SEPARATOR ",") AS author_role_codes
    FROM ticket_comments c
    JOIN users u ON u.id = c.user_id
    LEFT JOIN user_roles ur ON ur.user_id = u.id
    LEFT JOIN roles r ON r.id = ur.role_id
    WHERE c.ticket_id = ?';
$commentParams = [$ticketId];
if (!$canManage) {
    $commentSql .= ' AND c.is_internal = 0';
}
$commentSql .= ' GROUP BY c.id ORDER BY c.created_at ASC';
$stmt = db()->prepare($commentSql);
$stmt->execute($commentParams);
$comments = $stmt->fetchAll();

$attachmentsSql = 'SELECT id, original_name, file_size, is_internal, created_at FROM ticket_attachments WHERE ticket_id = ?';
if (!$canManage) {
    $attachmentsSql .= ' AND is_internal = 0';
}
$attachmentsSql .= ' ORDER BY created_at ASC, id ASC';
$attachmentsStmt = db()->prepare($attachmentsSql);
$attachmentsStmt->execute([$ticketId]);
$attachments = $attachmentsStmt->fetchAll();
$participants = ticket_participants($ticketId);

$agents = [];
if ($canManage) {
    $agents = eligible_assignees((string)$ticket['responsible_role_code']);
}

$eventsSql = 'SELECT e.*, u.name AS actor_name FROM ticket_events e JOIN users u ON u.id = e.user_id WHERE e.ticket_id = ?';
if (!$canManage) {
    $eventsSql .= " AND NOT ((e.event_type = 'comment' AND e.new_value = 'internal') OR (e.event_type = 'attachment_added' AND e.old_value = 'internal'))";
}
$eventsSql .= ' ORDER BY e.created_at DESC, e.id DESC';
$eventsStmt = db()->prepare($eventsSql);
$eventsStmt->execute([$ticketId]);
$events = $eventsStmt->fetchAll();
$assignmentUserIds = [];
foreach ($events as $event) {
    if ((string)$event['event_type'] !== 'assigned_changed') {
        continue;
    }
    foreach ([$event['old_value'], $event['new_value']] as $assignmentValue) {
        if ($assignmentValue !== null && ctype_digit((string)$assignmentValue)) {
            $assignmentUserIds[(int)$assignmentValue] = (int)$assignmentValue;
        }
    }
}
$assignmentUserNames = [];
if ($assignmentUserIds) {
    $assignmentIds = array_values($assignmentUserIds);
    $assignmentPlaceholders = implode(',', array_fill(0, count($assignmentIds), '?'));
    $assignmentStmt = db()->prepare("SELECT id, name FROM users WHERE id IN ($assignmentPlaceholders)");
    $assignmentStmt->execute($assignmentIds);
    foreach ($assignmentStmt->fetchAll() as $assignmentUser) {
        $assignmentUserNames[(int)$assignmentUser['id']] = (string)$assignmentUser['name'];
    }
}

$pageTitle = 'Zahtev ' . $ticket['ticket_no'];
$pageSubtitle = limit_text($ticket['title'], 80);

require_once __DIR__ . '/app/header.php';
?>
<section class="ticket-layout">
    <article class="card ticket-main">
        <div class="ticket-title-row">
            <div>
                <span class="badge"><?= e($ticket['ticket_no']) ?></span>
                <h2><?= e($ticket['title']) ?></h2>
            </div>
            <div class="ticket-badges">
                <span class="pill <?= e(status_class($ticket['status'])) ?>"><?= e(status_label($ticket['status'])) ?></span>
                <span class="pill <?= e(priority_class($ticket['priority'])) ?>"><?= e(priority_label($ticket['priority'])) ?></span>
            </div>
        </div>

        <dl class="meta-grid">
            <div><dt>Podnosilac</dt><dd><?= e($ticket['requester_name']) ?> · <?= e($ticket['requester_email']) ?></dd></div>
            <div><dt>Kategorija</dt><dd><?= e($ticket['category']) ?></dd></div>
            <div><dt>Odgovorna uloga</dt><dd><?= e(role_label((string)$ticket['responsible_role_code'])) ?> (<?= e($ticket['responsible_role_code']) ?>)</dd></div>
            <?php if (!empty($ticket['department_location'])): ?><div><dt>Odeljenje / Lokacija</dt><dd><?= e($ticket['department_location']) ?></dd></div><?php endif; ?>
            <?php if (!empty($ticket['issue_location'])): ?><div><dt>Mesto kvara</dt><dd><?= e($ticket['issue_location']) ?></dd></div><?php endif; ?>
            <?php if (!empty($ticket['asset_inventory_no'])): ?><div><dt>Inventarski broj uređaja / osnovnog sredstva</dt><dd><?= e($ticket['asset_inventory_no']) ?></dd></div><?php endif; ?>
            <div><dt>Dodeljeno</dt><dd><?= e($ticket['assigned_name'] ?: 'Nije dodeljeno') ?></dd></div>
            <div><dt>Kreirano</dt><dd><?= e(format_datetime($ticket['created_at'])) ?></dd></div>
        </dl>

        <div class="description-box"><?= nl2br(e($ticket['description'])) ?></div>

        <?php if ($attachments): ?>
            <section class="ticket-attachments">
                <h3>Prilozi <span class="badge"><?= count($attachments) ?></span></h3>
                <ul class="attachment-list">
                    <?php foreach ($attachments as $attachment): ?>
                        <li>
                            <a href="<?= e(url('attachment_download.php?id=' . (int)$attachment['id'])) ?>"><?= e($attachment['original_name']) ?></a>
                            <span><?= e(format_file_size((int)$attachment['file_size'])) ?> · <?= e(format_datetime($attachment['created_at'])) ?><?= (int)$attachment['is_internal'] === 1 ? ' · Interno' : '' ?></span>
                        </li>
                    <?php endforeach; ?>
                </ul>
            </section>
        <?php endif; ?>

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

        <div class="comments">
            <?php if (!$comments): ?>
                <p class="empty-state">Još uvek nema komentara.</p>
            <?php endif; ?>
            <?php foreach ($comments as $comment): ?>
                <div class="comment <?= (int)$comment['is_internal'] === 1 ? 'comment-internal' : '' ?>">
                    <div class="comment-header">
                        <strong><?= e($comment['author_name']) ?></strong>
                        <?php
                        $authorRoleCodes = array_values(array_filter(explode(',', (string)($comment['author_role_codes'] ?? ''))));
                        $authorRoleLabels = array_map('role_label', $authorRoleCodes);
                        if ((int)($comment['author_is_system_admin'] ?? 0) === 1) {
                            $authorRoleLabels[] = 'Sistemski administrator';
                        }
                        ?>
                        <span><?= e($authorRoleLabels ? implode(', ', $authorRoleLabels) : 'Bez dodeljene uloge') ?> · <?= e(format_datetime($comment['created_at'])) ?></span>
                        <?php if ((int)$comment['is_internal'] === 1): ?><em>Interna beleška</em><?php endif; ?>
                    </div>
                    <p><?= nl2br(e($comment['comment'])) ?></p>
                </div>
            <?php endforeach; ?>
        </div>

        <form method="post" enctype="multipart/form-data" class="comment-form">
            <?= csrf_field() ?>
            <input type="hidden" name="action" value="comment">
            <label>Dodaj komentar
                <textarea name="comment" rows="5" placeholder="Unesite komentar ili dopunu zahteva."></textarea>
            </label>
            <div class="ticket-form-group">
                <span class="ticket-form-label">Dodaj priloge</span>
                <div class="ticket-file-dropzone ticket-file-dropzone-compact" data-ticket-dropzone tabindex="0" role="button" aria-label="Izaberite dodatne priloge">
                    <strong>Prevucite fajlove ovde</strong><span> ili kliknite da izaberete</span>
                    <small>Do 10 fajlova, ukupno najviše 50 MB. JPG, JPEG, PNG, PDF, XLS, XLSX i TXT.</small>
                    <input type="file" name="attachments[]" hidden multiple accept=".jpg,.jpeg,.png,.pdf,.xls,.xlsx,.txt" data-ticket-attachments data-max-files="<?= ticket_attachment_max_files() ?>" data-max-bytes="<?= ticket_attachment_max_total_bytes() ?>">
                </div>
                <div class="ticket-file-list" data-ticket-file-list aria-live="polite"></div>
                <span class="attachment-selection" data-attachment-selection aria-live="polite"></span>
            </div>
            <?php if ($canManage): ?>
                <label class="inline-check"><input type="checkbox" name="is_internal" value="1"> Interna beleška, vidljiva samo odgovornim timovima i sistemskim administratorima</label>
            <?php endif; ?>
            <button class="button button-primary" type="submit">Dodaj komentar</button>
        </form>
    </article>

    <aside class="side-stack">
        <section class="card participant-card">
            <span class="badge">Učesnici</span>
            <h3>Učesnici tiketa</h3>
            <?php if ($participants): ?>
                <ul class="participant-list">
                    <?php foreach ($participants as $participant): ?>
                        <li><strong><?= e($participant['name']) ?></strong><span><?= e($participant['email']) ?></span></li>
                    <?php endforeach; ?>
                </ul>
            <?php else: ?>
                <p class="empty-state">Nema dodatih učesnika.</p>
            <?php endif; ?>
            <?php if ($canManageParticipants): ?>
                <form method="post" class="stacked-form compact-form participant-add-form">
                    <?= csrf_field() ?>
                    <input type="hidden" name="action" value="add_participant">
                    <div class="participant-picker" data-participant-picker data-search-url="<?= e(url('participant_search.php?ticket_id=' . $ticketId)) ?>">
                        <label for="participant-search-existing">Dodaj učesnika</label>
                        <div class="participant-search-wrap">
                            <input id="participant-search-existing" type="search" autocomplete="off" data-participant-search placeholder="Ime ili email" aria-autocomplete="list" aria-expanded="false">
                            <div class="participant-results" data-participant-results role="listbox" hidden></div>
                        </div>
                        <div class="participant-selected" data-participant-selected aria-live="polite">
                            <?php foreach ($selectedParticipantUsers as $participant): ?>
                                <span class="participant-chip" data-participant-id="<?= (int)$participant['id'] ?>">
                                    <span><?= e($participant['name']) ?> · <?= e($participant['email']) ?></span>
                                    <button type="button" data-remove-participant aria-label="Ukloni učesnika <?= e($participant['name']) ?>">×</button>
                                    <input type="hidden" name="participant_ids[]" value="<?= (int)$participant['id'] ?>">
                                </span>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <button class="button button-blue" type="submit">Dodaj učesnika</button>
                </form>
            <?php endif; ?>
        </section>
        <?php if ($canManage): ?>
            <section class="card">
                <span class="badge">Obrada</span>
                <h3>Ažuriranje tiketa</h3>
                <div class="ticket-processing-forms">
                    <form method="post" class="stacked-form compact-form">
                        <?= csrf_field() ?>
                        <input type="hidden" name="action" value="update">
                        <label>Status
                            <select name="status">
                                <?php foreach (status_options() as $value => $label): ?>
                                    <option value="<?= e($value) ?>" <?= safe_selected($ticket['status'], $value) ?>><?= e($label) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </label>
                        <label>Prioritet
                            <select name="priority">
                                <?php foreach ($manageablePriorities as $value => $label): ?>
                                    <option value="<?= e($value) ?>" <?= safe_selected($ticket['priority'], $value) ?>><?= e($label) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </label>
                        <label>Kategorija / odgovorni tim
                            <select name="category">
                                <?php foreach ($manageableCategories as $value => $label): ?>
                                    <option value="<?= e($value) ?>" <?= safe_selected($ticket['category'], $value) ?>><?= e($label) ?> · <?= e(category_responsible_role_code((string)$value, $ticketOrganizationUnit)) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </label>
                        <label>Dodeli korisniku odgovornog tima
                            <select name="assigned_to">
                                <option value="">Nije dodeljeno</option>
                                <?php foreach ($agents as $agent): ?>
                                    <option value="<?= (int)$agent['id'] ?>" <?= ((string)$ticket['assigned_to'] === (string)$agent['id']) ? 'selected' : '' ?>><?= e($agent['name']) ?> · <?= e($agent['email']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </label>
                        <button class="button button-blue" type="submit">Sačuvaj izmene</button>
                    </form>
                    <?php if (user_has_role($user, (string)$ticket['responsible_role_code']) && (int)($ticket['assigned_to'] ?? 0) !== (int)$user['id']): ?>
                        <form method="post" class="stacked-form compact-form">
                            <?= csrf_field() ?>
                            <input type="hidden" name="action" value="claim">
                            <button class="button button-primary" type="submit">Preuzmi tiket</button>
                        </form>
                    <?php endif; ?>
                </div>
            </section>

            <?php if (is_system_admin($user)): ?>
                <section class="card danger-zone-card ticket-danger-card">
                    <span class="badge badge-danger">Opasna zona</span>
                    <h3>Brisanje tiketa</h3>
                    <p>Trajno briše zahtev, komentare, događaje i povezana obaveštenja. Nakon brisanja tiket više nije vidljiv korisniku.</p>
                    <form method="post" data-confirm="Trajno brisanje tiketa uklanja zahtev iz sistema i korisnik ga više neće videti. Da li ste sigurni?">
                        <?= csrf_field() ?>
                        <input type="hidden" name="action" value="delete_ticket">
                        <button class="button button-danger" type="submit">Trajno obriši tiket</button>
                    </form>
                </section>
            <?php endif; ?>
        <?php endif; ?>

        <section class="card ticket-evidence-card">
            <span class="badge">Evidencija</span>
            <h3>Poslednji događaji</h3>
            <?php if (!$events): ?>
                <p class="empty-state">Nema evidentiranih događaja.</p>
            <?php else: ?>
                <ul class="timeline ticket-events-timeline" tabindex="0" aria-label="Poslednji događaji">
                    <?php foreach ($events as $event): ?>
                        <li>
                            <strong><?= e(event_label($event['event_type'])) ?></strong>
                            <span><?= e($event['actor_name']) ?> · <?= e(format_datetime($event['created_at'])) ?></span>
                            <?php if ($event['event_type'] === 'created' && $event['new_value'] !== null): ?>
                                <span><?= e(format_event_value($event['new_value'], 'status_changed')) ?></span>
                            <?php elseif ($event['event_type'] === 'responsible_role_set' && $event['new_value'] !== null): ?>
                                <span><?= e(format_event_value($event['new_value'], 'responsible_role_set')) ?></span>
                            <?php elseif ($event['event_type'] === 'comment' && $event['new_value'] !== null): ?>
                                <span><?= e(format_event_value($event['new_value'], 'comment')) ?></span>
                            <?php elseif ($event['event_type'] === 'attachment_added' && $event['new_value'] !== null): ?>
                                <?php $attachmentCount = max(1, (int)$event['new_value']); ?>
                                <span><?= $attachmentCount ?> <?= $attachmentCount === 1 ? 'prilog' : 'priloga' ?></span>
                            <?php elseif ($event['event_type'] === 'participant_added' && $event['new_value'] !== null): ?>
                                <span><?= e($event['new_value']) ?></span>
                            <?php elseif ($event['event_type'] === 'ticket_claimed' && $event['new_value'] !== null): ?>
                                <span><?= e(format_event_value($event['new_value'], 'ticket_claimed')) ?></span>
                            <?php elseif ($event['event_type'] === 'assigned_changed'): ?>
                                <?php
                                $oldAssignmentId = ctype_digit((string)$event['old_value']) ? (int)$event['old_value'] : 0;
                                $newAssignmentId = ctype_digit((string)$event['new_value']) ? (int)$event['new_value'] : 0;
                                $oldAssignmentLabel = $oldAssignmentId > 0 ? ($assignmentUserNames[$oldAssignmentId] ?? 'Korisnik #' . $oldAssignmentId) : 'Nije dodeljeno';
                                $newAssignmentLabel = $newAssignmentId > 0 ? ($assignmentUserNames[$newAssignmentId] ?? 'Korisnik #' . $newAssignmentId) : 'Nije dodeljeno';
                                ?>
                                <span><?= e($oldAssignmentLabel) ?> → <?= e($newAssignmentLabel) ?></span>
                            <?php elseif ($event['old_value'] !== null || $event['new_value'] !== null): ?>
                                <span><?= e(format_event_value($event['old_value'], $event['event_type'])) ?> → <?= e(format_event_value($event['new_value'], $event['event_type'])) ?></span>
                            <?php endif; ?>
                        </li>
                    <?php endforeach; ?>
                </ul>
            <?php endif; ?>
        </section>
    </aside>
</section>
<?php require_once __DIR__ . '/app/footer.php'; ?>
