<?php
require_once __DIR__ . '/app/bootstrap.php';
$user = require_auth();
$view = ticket_list_view($user, $_GET['view'] ?? null);
$ticketListLabel = ticket_list_label($view);
$pageTitle = $ticketListLabel;
$pageSubtitle = match ($view) {
    'mine' => 'Tiketi koje ste otvorili, koji su vam dodeljeni ili na kojima učestvujete',
    'assigned' => 'Tiketi dodeljeni vama ili vašim dodatnim ulogama',
    'all' => 'Administratorski pregled svih tiketa',
    default => 'Pregled, filtriranje i praćenje tiketa',
};

$status = is_scalar($_GET['status'] ?? '') ? trim((string)$_GET['status']) : '';
$priority = is_scalar($_GET['priority'] ?? '') ? trim((string)$_GET['priority']) : '';
$q = is_scalar($_GET['q'] ?? '') ? mb_substr(trim((string)$_GET['q']), 0, 190) : '';
$ticketPageSizes = [25, 50, 100];
$perPageRaw = is_scalar($_GET['per_page'] ?? null) ? (string)$_GET['per_page'] : '';
$perPage = ctype_digit($perPageRaw) && in_array((int)$perPageRaw, $ticketPageSizes, true) ? (int)$perPageRaw : 25;
$pageRaw = is_scalar($_GET['page'] ?? null) ? (string)$_GET['page'] : '';
$page = ctype_digit($pageRaw) && strlen($pageRaw) <= 9 && (int)$pageRaw >= 1 ? (int)$pageRaw : 1;

[$accessSql, $params] = ticket_list_access_sql($user, $view);
$where = [$accessSql];

if ($status !== '' && array_key_exists($status, status_options())) {
    $where[] = 't.status = ?';
    $params[] = $status;
}

if ($priority !== '' && array_key_exists($priority, priority_options())) {
    $where[] = 't.priority = ?';
    $params[] = $priority;
}

if ($q !== '') {
    $where[] = '(LOCATE(?, t.ticket_no) > 0 OR LOCATE(?, t.title) > 0 OR LOCATE(?, t.description) > 0 OR LOCATE(?, t.category) > 0 OR LOCATE(?, u.name) > 0)';
    array_push($params, $q, $q, $q, $q, $q);
}

$whereSql = implode(' AND ', $where);
$countSql = 'SELECT COUNT(*)
        FROM tickets t
        JOIN users u ON u.id = t.user_id
        WHERE ' . $whereSql;
$countStmt = db()->prepare($countSql);
$countStmt->execute($params);
$totalTickets = (int)$countStmt->fetchColumn();
$totalPages = max(1, (int)ceil($totalTickets / $perPage));
$page = min($page, $totalPages);
$offset = ($page - 1) * $perPage;

$sql = 'SELECT t.*, u.name AS requester_name, 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 ' . $whereSql . '
        ORDER BY FIELD(t.status, "open", "in_progress", "waiting", "resolved", "closed"), t.updated_at DESC
        LIMIT ? OFFSET ?';
$stmt = db()->prepare($sql);
foreach ($params as $index => $value) {
    $stmt->bindValue($index + 1, $value, is_int($value) ? PDO::PARAM_INT : PDO::PARAM_STR);
}
$stmt->bindValue(count($params) + 1, $perPage, PDO::PARAM_INT);
$stmt->bindValue(count($params) + 2, $offset, PDO::PARAM_INT);
$stmt->execute();
$tickets = $stmt->fetchAll();
$paginationParams = [
    'view' => $view,
    'q' => $q,
    'status' => $status,
    'priority' => $priority,
    'per_page' => $perPage,
];

require_once __DIR__ . '/app/header.php';
?>
<form method="get" class="filters">
    <input type="hidden" name="view" value="<?= e($view) ?>">
    <label>Pretraga
        <input type="search" name="q" value="<?= e($q) ?>" placeholder="Broj tiketa, naslov, kategorija, podnosilac...">
    </label>
    <label>Status
        <select name="status">
            <option value="">Svi statusi</option>
            <?php foreach (status_options() as $value => $label): ?>
                <option value="<?= e($value) ?>" <?= safe_selected($status, $value) ?>><?= e($label) ?></option>
            <?php endforeach; ?>
        </select>
    </label>
    <label>Prioritet
        <select name="priority">
            <option value="">Svi prioriteti</option>
            <?php foreach (priority_options() as $value => $label): ?>
                <option value="<?= e($value) ?>" <?= safe_selected($priority, $value) ?>><?= e($label) ?></option>
            <?php endforeach; ?>
        </select>
    </label>
    <label>Po stranici
        <select name="per_page">
            <?php foreach ($ticketPageSizes as $pageSize): ?>
                <option value="<?= (int)$pageSize ?>" <?= safe_selected($perPage, $pageSize) ?>><?= (int)$pageSize ?></option>
            <?php endforeach; ?>
        </select>
    </label>
    <div class="filter-actions">
        <button class="button button-blue" type="submit">Primeni</button>
        <a class="button button-light" href="<?= e(url('tickets.php?view=' . rawurlencode($view))) ?>">Resetuj</a>
    </div>
</form>

<nav class="ticket-view-switch" aria-label="Izbor prikaza tiketa">
    <a class="button <?= $view === 'mine' ? 'button-blue' : 'button-light' ?>" href="<?= e(url('tickets.php?view=mine')) ?>" <?= $view === 'mine' ? 'aria-current="page"' : '' ?>>Moji tiketi</a>
    <?php if (user_has_additional_role($user)): ?>
        <a class="button <?= $view === 'assigned' ? 'button-blue' : 'button-light' ?>" href="<?= e(url('tickets.php?view=assigned')) ?>" <?= $view === 'assigned' ? 'aria-current="page"' : '' ?>>Tiketi za koje sam zadužen</a>
    <?php endif; ?>
    <?php if (is_system_admin($user)): ?>
        <a class="button <?= $view === 'all' ? 'button-blue' : 'button-light' ?>" href="<?= e(url('tickets.php?view=all')) ?>" <?= $view === 'all' ? 'aria-current="page"' : '' ?>>Svi zahtevi</a>
    <?php endif; ?>
</nav>

<section class="card card-pad">
    <div class="section-heading">
        <div>
            <span class="badge">Lista</span>
            <h2><?= e($ticketListLabel) ?></h2>
            <p><?php if ($view === 'mine'): ?>Prikazani su tiketi koje ste otvorili, koji su direktno dodeljeni vama ili na kojima ste učesnik.<?php elseif ($view === 'assigned'): ?>Prikazani su tiketi direktno dodeljeni vama ili dodatnim ulogama koje imate.<?php else: ?>Prikazani su svi tiketi dostupni sistemskom administratoru.<?php endif; ?></p>
        </div>
        <?php if (can_create_ticket($user)): ?><a class="button button-primary" href="<?= e(url('ticket_create.php')) ?>">Novi zahtev</a><?php endif; ?>
    </div>

    <?php if (!$tickets): ?>
        <p class="empty-state">Nema zahteva koji odgovaraju izabranim filterima.</p>
    <?php else: ?>
        <div class="table-wrap">
            <table>
                <thead>
                <tr>
                    <th>Broj</th>
                    <th>Zahtev</th>
                    <th>Status</th>
                    <th>Prioritet</th>
                    <th>Podnosilac</th>
                    <th>Dodeljeno</th>
                    <th>Izmenjeno</th>
                </tr>
                </thead>
                <tbody>
                <?php foreach ($tickets as $ticket): ?>
                    <tr>
                        <td><a href="<?= e(url('ticket_view.php?id=' . (int)$ticket['id'])) ?>"><?= e($ticket['ticket_no']) ?></a></td>
                        <td class="ticket-title">
                            <strong><?= e($ticket['title']) ?></strong>
                            <small><?= e($ticket['category']) ?> · <?= e($ticket['responsible_role_code']) ?> · <?= e(limit_text($ticket['description'], 90)) ?></small>
                        </td>
                        <td><span class="pill <?= e(status_class($ticket['status'])) ?>"><?= e(status_label($ticket['status'])) ?></span></td>
                        <td><span class="pill <?= e(priority_class($ticket['priority'])) ?>"><?= e(priority_label($ticket['priority'])) ?></span></td>
                        <td><?= e($ticket['requester_name']) ?></td>
                        <td><?= e($ticket['assigned_name'] ?: 'Nije dodeljeno') ?></td>
                        <td><?= e(format_datetime($ticket['updated_at'])) ?></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>

    <?php
        $rangeStart = $totalTickets > 0 ? $offset + 1 : 0;
        $rangeEnd = min($totalTickets, $offset + count($tickets));
    ?>
    <div class="pagination-summary">Prikaz <?= (int)$rangeStart ?>–<?= (int)$rangeEnd ?> od <?= (int)$totalTickets ?> zahteva prema aktivnim filterima.</div>
    <?php if ($totalPages > 1): ?>
        <nav class="pagination" aria-label="Paginacija tiketa">
            <?php if ($page > 1): ?>
                <a class="pagination-link" href="<?= e(page_url('tickets.php', array_merge($paginationParams, ['page' => $page - 1]))) ?>">← Prethodna</a>
            <?php else: ?>
                <span class="pagination-link is-disabled" aria-disabled="true">← Prethodna</span>
            <?php endif; ?>
            <div class="pagination-pages">
                <?php foreach (pagination_page_numbers($page, $totalPages) as $pageNumber): ?>
                    <?php if ($pageNumber === null): ?>
                        <span class="pagination-ellipsis">…</span>
                    <?php elseif ($pageNumber === $page): ?>
                        <span class="pagination-link is-current" aria-current="page"><?= (int)$pageNumber ?></span>
                    <?php else: ?>
                        <a class="pagination-link" href="<?= e(page_url('tickets.php', array_merge($paginationParams, ['page' => $pageNumber]))) ?>"><?= (int)$pageNumber ?></a>
                    <?php endif; ?>
                <?php endforeach; ?>
            </div>
            <?php if ($page < $totalPages): ?>
                <a class="pagination-link" href="<?= e(page_url('tickets.php', array_merge($paginationParams, ['page' => $page + 1]))) ?>">Sledeća →</a>
            <?php else: ?>
                <span class="pagination-link is-disabled" aria-disabled="true">Sledeća →</span>
            <?php endif; ?>
        </nav>
    <?php endif; ?>
</section>
<?php require_once __DIR__ . '/app/footer.php'; ?>
