<?php
ob_start();

// Mapeamento de status
$statusClasses = [
    'Aberto' => 'primary',
    'Em Análise' => 'info',
    'Programação' => 'danger',
    'Pendente' => 'warning',
    'Retorno' => 'success',
    'Concluído' => 'dark'
];

$prioridades = [
    'baixa' => ['label' => 'Baixa', 'class' => 'secondary'],
    'normal' => ['label' => 'Normal', 'class' => 'primary'],
    'alta' => ['label' => 'Alta', 'class' => 'warning'],
    'urgente' => ['label' => 'Urgente', 'class' => 'danger']
];

$modulos = [
    'cadastros' => ['label' => 'Cadastros', 'class' => 'info'],
    'venda' => ['label' => 'Venda', 'class' => 'primary'],
    'nota_fiscal' => ['label' => 'Nota Fiscal', 'class' => 'success'],
    'estoque' => ['label' => 'Estoque', 'class' => 'warning'],
    'relatorios' => ['label' => 'Relatórios', 'class' => 'info']
];
?>

<div class="row mb-4">
    <div class="col-md-12">
        <h2><i class="bi bi-eye me-2"></i> Acompanhar Tickets</h2>
        <p class="text-muted">Visualize o status dos seus chamados</p>
    </div>
</div>

<!-- Filtros -->
<div class="card mb-4">
    <div class="card-body">
        <div class="row g-3">
            <div class="col-md-4">
                <input type="text" class="form-control" id="search-tickets" placeholder="Buscar tickets..."
                    onkeyup="filtrarTickets()">
            </div>
            <div class="col-md-2">
                <select class="form-select" id="filter-status" onchange="filtrarTickets()">
                    <option value="">Todos os Status</option>
                    <option value="Aberto">Aberto</option>
                    <option value="Em Análise">Em Análise</option>
                    <option value="Programação">Programação</option>
                    <option value="Pendente">Pendente</option>
                    <option value="Retorno">Retorno</option>
                    <option value="Concluído">Concluído</option>
                </select>
            </div>
            <div class="col-md-2">
                <select class="form-select" id="filter-prioridade" onchange="filtrarTickets()">
                    <option value="">Todas as Prioridades</option>
                    <option value="baixa">Baixa</option>
                    <option value="normal">Normal</option>
                    <option value="alta">Alta</option>
                    <option value="urgente">Urgente</option>
                </select>
            </div>
            <div class="col-md-2">
                <button class="btn btn-outline-secondary w-100" onclick="limparFiltros()">
                    <i class="bi bi-x-circle me-1"></i> Limpar
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Listagem -->
<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <span><i class="bi bi-list-ul me-2"></i> Meus Tickets</span>
        <span class="badge bg-primary"><?= count($tickets ?? []) ?> ticket(s)</span>
    </div>
    <div class="card-body p-0">
        <?php if (!empty($tickets)): ?>
            <div class="table-responsive">
                <table class="table table-hover mb-0" id="tickets-table">
                    <thead>
                        <tr>
                            <th width="100">Número</th>
                            <th>Título</th>
                            <th width="120">Módulo</th>
                            <th width="100">Prioridade</th>
                            <th width="120">Status</th>
                            <th width="100">Data</th>
                            <th width="80">Comentários</th>
                            <th width="80" class="text-center">Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($tickets as $ticket): ?>
                            <tr data-ticket-id="<?= $ticket['id'] ?>"
                                data-status="<?= htmlspecialchars($ticket['status']) ?>"
                                data-prioridade="<?= htmlspecialchars($ticket['prioridade']) ?>"
                                data-categoria="<?= htmlspecialchars($ticket['categoria']) ?>">
                                <td>
                                    <strong>#<?= htmlspecialchars($ticket['numero_ticket']) ?></strong>
                                </td>
                                <td>
                                    <a href="<?= url('/tickets/acompanhar/visualizar?id=' . $ticket['id']) ?>"
                                       class="text-decoration-none">
                                        <?= htmlspecialchars($ticket['titulo']) ?>
                                    </a>
                                </td>
                                <td>
                                    <?php
                                    $categoriaTicket = $ticket['categoria'];
                                    if (strpos($categoriaTicket, 'outros: ') === 0) {
                                        $moduloTexto = substr($categoriaTicket, 8);
                                        $modulo = ['label' => 'Outros: ' . htmlspecialchars($moduloTexto), 'class' => 'secondary'];
                                    } else {
                                        $modulo = $modulos[$categoriaTicket] ?? ['label' => htmlspecialchars($categoriaTicket), 'class' => 'secondary'];
                                    }
                                    ?>
                                    <span class="badge bg-<?= $modulo['class'] ?>"><?= $modulo['label'] ?></span>
                                </td>
                                <td>
                                    <?php
                                    $pri = $prioridades[$ticket['prioridade']] ?? ['label' => $ticket['prioridade'], 'class' => 'secondary'];
                                    ?>
                                    <span class="badge bg-<?= $pri['class'] ?>"><?= $pri['label'] ?></span>
                                </td>
                                <td>
                                    <?php
                                    $statusClass = $statusClasses[$ticket['status']] ?? 'secondary';
                                    ?>
                                    <span class="badge bg-<?= $statusClass ?>"><?= htmlspecialchars($ticket['status']) ?></span>
                                </td>
                                <td>
                                    <small><?= date('d/m/Y', strtotime($ticket['data_abertura'])) ?></small>
                                </td>
                                <td>
                                    <span class="badge bg-secondary">
                                        <i class="bi bi-chat-dots"></i> <?= $ticket['total_comentarios'] ?? 0 ?>
                                    </span>
                                </td>
                                <td class="text-center">
                                    <a href="<?= url('/tickets/acompanhar/visualizar?id=' . $ticket['id']) ?>"
                                       class="btn btn-sm btn-outline-primary" title="Visualizar">
                                        <i class="bi bi-eye"></i>
                                    </a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php else: ?>
            <div class="text-center py-5">
                <i class="bi bi-inbox" style="font-size: 3rem; color: #ccc;"></i>
                <p class="text-muted mt-3">Nenhum ticket encontrado</p>
                <a href="<?= url('/tickets/abrir') ?>" class="btn btn-primary">
                    <i class="bi bi-plus-circle me-2"></i> Abrir Novo Ticket
                </a>
            </div>
        <?php endif; ?>
    </div>
</div>

<style>
#tickets-table tbody tr {
    cursor: pointer;
}

#tickets-table tbody tr:hover {
    background-color: #f8f9fa;
}

#tickets-table tbody tr td a {
    color: #212529;
}

#tickets-table tbody tr:hover td a {
    color: #0d6efd;
}
</style>

<script>
function filtrarTickets() {
    const search = document.getElementById('search-tickets').value.toLowerCase();
    const status = document.getElementById('filter-status').value;
    const prioridade = document.getElementById('filter-prioridade').value;

    const rows = document.querySelectorAll('#tickets-table tbody tr');

    rows.forEach(row => {
        const titulo = row.querySelector('td:nth-child(2)').textContent.toLowerCase();
        const numero = row.querySelector('td:nth-child(1)').textContent.toLowerCase();
        const rowStatus = row.getAttribute('data-status');
        const rowPrioridade = row.getAttribute('data-prioridade');

        let matchSearch = !search || titulo.includes(search) || numero.includes(search);
        let matchStatus = !status || rowStatus === status;
        let matchPrioridade = !prioridade || rowPrioridade === prioridade;

        if (matchSearch && matchStatus && matchPrioridade) {
            row.style.display = '';
        } else {
            row.style.display = 'none';
        }
    });
}

function limparFiltros() {
    document.getElementById('search-tickets').value = '';
    document.getElementById('filter-status').value = '';
    document.getElementById('filter-prioridade').value = '';
    filtrarTickets();
}
</script>

<?php
$content = ob_get_clean();
$activeMenu = 'acompanhar-tickets';
include ROOT_PATH . '/views/layouts/app.php';
?>
