<?php
ob_start();
?>

<div class="row mb-4">
    <div class="col-md-6">
        <h2><i class="bi bi-people me-2"></i> Usuários</h2>
        <p class="text-muted">Gerencie os usuários do sistema</p>
    </div>
    <div class="col-md-6 text-end">
        <a href="<?= url('/usuarios/criar') ?>" class="btn btn-primary">
            <i class="bi bi-plus-circle me-2"></i> Novo Usuário
        </a>
    </div>
</div>

<!-- Filtros -->
<div class="card mb-4">
    <div class="card-body">
        <div class="row g-3">
            <div class="col-md-8">
                <input type="text" class="form-control" id="search-usuarios" placeholder="Buscar por nome, email..."
                    onkeyup="filterTable('usuarios-table', this.value)">
            </div>
            <div class="col-md-4">
                <select class="form-select" id="filter-role" onchange="filterTableByRole('usuarios-table', this.value)">
                    <option value="">Todas as Funções</option>
                    <option value="admin">Administrador</option>
                    <option value="operador">Operador</option>
                    <option value="visualizador">Visualizador</option>
                </select>
            </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> Lista de Usuários</span>
        <span class="badge bg-primary" id="totalRegistros"><?= count($usuarios ?? []) ?> registro(s)</span>
    </div>
    <div class="card-body p-0" id="usuariosContainer">
        <?php if (!empty($usuarios)): ?>
            <div class="table-responsive">
                <table class="table table-hover mb-0" id="usuarios-table">
                    <thead>
                        <tr>
                            <th width="60">ID</th>
                            <th>Nome</th>
                            <th>Email</th>
                            <th>Função</th>
                            <th>Status</th>
                            <th>Último Login</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($usuarios as $usuario): ?>
                            <tr style="cursor: pointer;" data-role="<?= htmlspecialchars($usuario['role'] ?? '') ?>"
                                onclick="abrirOpcoesUsuario(<?= $usuario['id'] ?>, '<?= addslashes(htmlspecialchars($usuario['name'])) ?>', '<?= addslashes(htmlspecialchars($usuario['email'])) ?>')">
                                <td><?= $usuario['id'] ?></td>
                                <td><strong><?= htmlspecialchars($usuario['name']) ?></strong></td>
                                <td><?= htmlspecialchars($usuario['email']) ?></td>
                                <td>
                                    <?php
                                    $roleBadges = [
                                        'admin' => '<span class="badge bg-danger">Administrador</span>',
                                        'operador' => '<span class="badge bg-primary">Operador</span>',
                                        'visualizador' => '<span class="badge bg-info">Visualizador</span>'
                                    ];
                                    echo $roleBadges[$usuario['role']] ?? '-';
                                    ?>
                                </td>
                                <td>
                                    <?php if ($usuario['is_active']): ?>
                                        <span class="badge bg-success">Ativo</span>
                                    <?php else: ?>
                                        <span class="badge bg-secondary">Inativo</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if ($usuario['last_login']): ?>
                                        <small><?= date('d/m/Y H:i', strtotime($usuario['last_login'])) ?></small>
                                    <?php else: ?>
                                        <small class="text-muted">Nunca</small>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php else: ?>
            <div class="text-center py-5" id="emptyState">
                <i class="bi bi-people" style="font-size: 4rem; color: var(--text-secondary);"></i>
                <p class="text-muted mt-3">Nenhum usuário encontrado</p>
                <a href="<?= url('/usuarios/criar') ?>" class="btn btn-primary mt-2">
                    <i class="bi bi-plus-circle me-2"></i> Cadastrar Primeiro Usuário
                </a>
            </div>
        <?php endif; ?>
    </div>
</div>

<script>
    // Função para filtrar tabela por texto (igual ao módulo de Pessoas)
    function filterTable(tableId, searchText) {
        const table = document.getElementById(tableId);
        if (!table) return;

        const tbody = table.getElementsByTagName('tbody')[0];
        if (!tbody) return;

        const rows = tbody.getElementsByTagName('tr');
        let visibleCount = 0;

        for (let i = 0; i < rows.length; i++) {
            const row = rows[i];
            const text = row.textContent.toLowerCase();

            if (text.includes(searchText.toLowerCase())) {
                row.style.display = '';
                visibleCount++;
            } else {
                row.style.display = 'none';
            }
        }

        // Atualizar contador
        updateCounter(visibleCount);
    }

    // Função para filtrar por role
    function filterTableByRole(tableId, role) {
        const table = document.getElementById(tableId);
        if (!table) return;

        const tbody = table.getElementsByTagName('tbody')[0];
        if (!tbody) return;

        const rows = tbody.getElementsByTagName('tr');
        let visibleCount = 0;

        for (let i = 0; i < rows.length; i++) {
            const row = rows[i];
            const rowRole = row.getAttribute('data-role');

            // Se não há filtro selecionado, mostra todas as linhas
            if (!role || role === '') {
                row.style.display = '';
                visibleCount++;
            } else {
                // Compara o role da linha com o filtro selecionado
                if (rowRole === role) {
                    row.style.display = '';
                    visibleCount++;
                } else {
                    row.style.display = 'none';
                }
            }
        }

        // Atualizar contador
        updateCounter(visibleCount);

        // Aplicar filtro de texto também se houver
        const searchInput = document.getElementById('search-usuarios');
        if (searchInput && searchInput.value) {
            filterTable(tableId, searchInput.value);
        }
    }

    // Função para atualizar contador
    function updateCounter(count) {
        const counter = document.getElementById('totalRegistros');
        if (counter) {
            counter.textContent = count + ' registro(s)';
        }
    }

    // Aplicar ambos os filtros quando houver mudança
    document.addEventListener('DOMContentLoaded', function () {
        const searchInput = document.getElementById('search-usuarios');
        const roleSelect = document.getElementById('filter-role');

        if (searchInput) {
            searchInput.addEventListener('input', function () {
                const role = roleSelect ? roleSelect.value : '';
                if (role) {
                    filterTableByRole('usuarios-table', role);
                } else {
                    filterTable('usuarios-table', this.value);
                }
            });
        }

        if (roleSelect) {
            roleSelect.addEventListener('change', function () {
                const search = searchInput ? searchInput.value : '';
                if (search) {
                    filterTableByRole('usuarios-table', this.value);
                } else {
                    filterTableByRole('usuarios-table', this.value);
                }
            });
        }
    });

    // Função para abrir opções do usuário
    function abrirOpcoesUsuario(id, nome, email) {
        const codigo = String(id).padStart(4, '0');

        const headerHtml = `
            <div style="background: linear-gradient(135deg, #0d6efd 0%, #0b5ed7 100%);
                        margin: -20px -20px 20px -20px;
                        padding: 28px 24px;
                        border-radius: 12px 12px 0 0;
                        color: white;
                        text-align: center;">
                <div style="display: inline-flex; align-items: center; justify-content: center; width: 70px; height: 70px; background: rgba(255,255,255,0.2); border-radius: 50%; margin-bottom: 12px;">
                    <i class="bi bi-person-gear" style="font-size: 2rem;"></i>
                </div>
                <div style="background: rgba(255,255,255,0.15); border-radius: 8px; padding: 12px; margin-top: 8px;">
                    <div style="font-size: 0.75rem; opacity: 0.9; margin-bottom: 4px;">Código: <strong>${codigo}</strong></div>
                    <div style="font-size: 1.1rem; font-weight: 600; margin-bottom: 4px;">${nome}</div>
                    <div style="font-size: 0.85rem; opacity: 0.95;"><i class="bi bi-envelope me-1"></i>${email}</div>
                </div>
                <div style="margin-top: 10px;">
                    <span style="background: rgba(255,255,255,0.25); padding: 4px 12px; border-radius: 20px; font-size: 0.75rem; font-weight: 500;">Usuário</span>
                </div>
            </div>
        `;

        const buttonsHtml = `
            <div class="opcoes-grid-compact">
                <button type="button" class="opcao-btn opcao-btn-primary" onclick="window.location.href=appUrl('/usuarios/editar?id=${id}')">
                    <i class="bi bi-pencil"></i>
                    <span>Alterar</span>
                </button>
                <button type="button" class="opcao-btn opcao-btn-info" onclick="window.location.href=appUrl('/usuarios/editar?id=${id}&tab=funcionario')">
                    <i class="bi bi-person-vcard"></i>
                    <span>Ficha do Funcionário</span>
                </button>
                <button type="button" class="opcao-btn opcao-btn-danger" onclick="Swal.close(); deletarUsuario(${id})">
                    <i class="bi bi-trash"></i>
                    <span>Excluir</span>
                </button>
            </div>
        `;

        Swal.fire({
            html: headerHtml + buttonsHtml,
            showConfirmButton: false,
            showCloseButton: true,
            width: 420,
            padding: '20px',
            customClass: {
                popup: 'swal-opcoes-usuario'
            }
        });
    }

    async function deletarUsuario(id) {
        const confirmed = await confirmDelete('Tem certeza que deseja excluir este usuário?');
        if (confirmed) {
            $.ajax({
                url: appUrl('/usuarios/deletar'),
                type: 'POST',
                data: { id: id },
                dataType: 'json',
                success: function (response) {
                    if (response.success) {
                        Toast.success(response.message);
                        setTimeout(() => location.reload(), 1500);
                    } else {
                        Toast.error(response.message);
                    }
                }
            });
        }
    }
</script>

<style>
    #usuarios-table tbody tr:hover {
        background-color: rgba(13, 110, 253, 0.05);
    }

    /* Estilos para o modal de opções (igual ao módulo de Pessoas) */
    .opcoes-grid-compact {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 10px;
        padding: 0;
    }

    .opcao-btn {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 16px 12px;
        border: none;
        border-radius: 10px;
        cursor: pointer;
        transition: all 0.2s ease;
        gap: 6px;
        min-height: 80px;
        font-family: inherit;
    }

    .opcao-btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    }

    .opcao-btn i {
        font-size: 1.4rem;
    }

    .opcao-btn span {
        font-size: 0.85rem;
        font-weight: 500;
    }

    .opcao-btn-primary {
        background: linear-gradient(135deg, #3b82f6, #1d4ed8);
        color: white;
    }

    .opcao-btn-info {
        background: linear-gradient(135deg, #06b6d4, #0891b2);
        color: white;
    }

    .opcao-btn-danger {
        background: linear-gradient(135deg, #ef4444, #dc2626);
        color: white;
    }
</style>

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