<?php
$activeFiltersCount = 0;
foreach (['search', 'status', 'date_from', 'date_to'] as $filterKey) {
    if (!empty($filters[$filterKey])) {
        $activeFiltersCount++;
    }
}
?>

<div class="d-flex flex-column flex-lg-row justify-content-between align-items-lg-center gap-3 mb-4">
    <div>
        <h1 class="h3 fw-bold mb-1">Fichas de admissão</h1>
        <p class="text-muted mb-0">Consulta, filtro, edição, impressão e acompanhamento do fluxo do RH.</p>
    </div>
    <div class="d-flex flex-wrap gap-2">
        <button type="button" class="btn btn-outline-dark" data-bs-toggle="modal" data-bs-target="#updateNoteModal">
            Nota de atualização 0.2
        </button>
        <a href="<?= e(baseUrl('')) ?>" class="btn btn-primary">Nova ficha pública</a>
    </div>
</div>

<?php if (!empty($success)): ?>
    <div class="alert alert-success rounded-4"><?= e($success) ?></div>
<?php endif; ?>

<?php if (!empty($error)): ?>
    <div class="alert alert-danger rounded-4"><?= e($error) ?></div>
<?php endif; ?>

<div class="modal fade" id="updateNoteModal" tabindex="-1" aria-labelledby="updateNoteModalLabel" aria-hidden="true" data-update-version="0.2">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content update-modal">
            <div class="modal-header border-0 pb-0">
                <div>
                    <span class="update-modal__eyebrow">Painel administrativo</span>
                    <h2 class="modal-title h4 mb-1" id="updateNoteModalLabel">Nota de atualização 0.2</h2>
                    <p class="text-muted mb-0">Resumo das melhorias recentes do sistema.</p>
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Fechar"></button>
            </div>
            <div class="modal-body pt-3">
                <div class="update-modal__block">
                    <ul class="update-modal__list mb-0">
                        <li>Quando houver mais de um dependente, agora existe a possibilidade de subir mais de uma certidão de nascimento.</li>
                        <li>Anexos de carteira de trabalho, certidão de nascimento, certidão de casamento e averbação do divórcio agora podem ser inseridos no formulário.</li>
                        <li>No caso de candidatos a professor, o formulário passa a pedir o anexo do MEI e o CNPJ do candidato.</li>
                        <li>Agora a ficha também solicita o anexo da <strong>declaração de matrícula</strong> quando o colaborador é estudante ou está em vaga de estágio.</li>
                        <li>No painel administrativo, foram adicionados os novos status <strong>Cancelado</strong> e <strong>Demitido</strong>.</li>
                    </ul>
                </div>
            </div>
            <div class="modal-footer border-0 pt-0">
                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Fechar</button>
                <button type="button" class="btn btn-dark" data-update-dismiss>Entendi</button>
            </div>
        </div>
    </div>
</div>

<div class="card border-0 shadow-sm mb-4">
    <div class="card-body">
        <div class="d-flex flex-column flex-lg-row justify-content-between align-items-lg-center gap-2 mb-3">
            <div>
                <h2 class="h5 mb-1">Filtros do admin</h2>
                <p class="text-muted mb-0">A busca por texto é instantânea enquanto você digita. Status e datas continuam como filtros do backend, sem travar a pesquisa ao vivo.</p>
            </div>
            <div class="d-flex flex-wrap gap-2 align-items-center">
                <span class="badge text-bg-light border text-dark" data-admin-results-badge>
                    <span data-admin-results-count><?= count($admissions) ?></span> resultado<span data-admin-results-plural><?= count($admissions) === 1 ? '' : 's' ?></span>
                </span>
                <span class="badge text-bg-light border text-dark">Base carregada: <?= count($admissions) ?></span>
                <?php if ($activeFiltersCount > 0): ?>
                    <span class="badge text-bg-dark"><?= $activeFiltersCount ?> filtro<?= $activeFiltersCount === 1 ? '' : 's' ?> ativo<?= $activeFiltersCount === 1 ? '' : 's' ?></span>
                <?php endif; ?>
            </div>
        </div>

        <form class="row g-3" method="get" action="<?= e(baseUrl('admin/admissoes')) ?>">
            <div class="col-lg-4">
                <label class="form-label">Busca instantânea</label>
                <input
                    type="text"
                    name="search"
                    class="form-control"
                    placeholder="Digite: Mari, CPF, telefone, unidade, cargo, função ou ID"
                    value="<?= e($filters['search']) ?>"
                    autocomplete="off"
                    data-admin-live-search
                >
            </div>
            <div class="col-lg-3">
                <label class="form-label">Status</label>
                <select name="status" class="form-select">
                    <option value="">Todos</option>
                    <?php foreach ($config['statuses'] as $key => $label): ?>
                        <option value="<?= e($key) ?>" <?= selected($filters['status'], $key) ?>><?= e($label) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-lg-2">
                <label class="form-label">Data inicial</label>
                <input type="date" name="date_from" class="form-control" value="<?= e($filters['date_from']) ?>">
            </div>
            <div class="col-lg-2">
                <label class="form-label">Data final</label>
                <input type="date" name="date_to" class="form-control" value="<?= e($filters['date_to']) ?>">
            </div>
            <div class="col-lg-1 d-grid">
                <button class="btn btn-dark" type="submit">Aplicar</button>
            </div>
            <div class="col-12 d-flex flex-wrap gap-2">
                <a href="<?= e(baseUrl('admin/admissoes')) ?>" class="btn btn-outline-secondary">Limpar filtros</a>
            </div>
        </form>
    </div>
</div>

<div class="card border-0 shadow-sm">
    <div class="card-body">
        <?php if (empty($admissions)): ?>
            <div class="text-center text-muted py-5">Nenhuma ficha encontrada.</div>
        <?php else: ?>
            <div class="table-responsive" data-admin-live-container>
                <table class="table align-middle" id="admissions-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Colaborador</th>
                            <th>CPF</th>
                            <th>Unidade</th>
                            <th>Cargo / função</th>
                            <th>Status</th>
                            <th>Enviado em</th>
                            <th class="text-end">Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($admissions as $admission): ?>
                            <?php
                            $searchIndex = implode(' ', array_filter([
                                '#' . (string) ($admission['id'] ?? ''),
                                (string) ($admission['full_name'] ?? ''),
                                (string) ($admission['personal_email'] ?? ''),
                                (string) ($admission['phone'] ?? ''),
                                (string) ($admission['cpf'] ?? ''),
                                (string) ($admission['unit_name'] ?? ''),
                                (string) ($admission['job_title'] ?? ''),
                                (string) ($admission['employment_function'] ?? ''),
                                (string) ($config['statuses'][$admission['status']] ?? ($admission['status'] ?? '')),
                            ]));
                            $searchIndexDigits = preg_replace('/\D/', '', $searchIndex) ?? '';
                            ?>
                            <tr
                                data-search-index="<?= e($searchIndex) ?>"
                                data-search-digits="<?= e($searchIndexDigits) ?>"
                            >
                                <td>#<?= e((string) $admission['id']) ?></td>
                                <td>
                                    <div class="fw-semibold"><?= e($admission['full_name'] ?? '-') ?></div>
                                    <?php if (!empty($admission['personal_email'])): ?>
                                        <div class="text-muted small"><?= e($admission['personal_email']) ?></div>
                                    <?php endif; ?>
                                    <?php if (!empty($admission['phone'])): ?>
                                        <div class="text-muted small">Tel: <?= e($admission['phone']) ?></div>
                                    <?php endif; ?>
                                </td>
                                <td><?= e($admission['cpf'] ?? '-') ?></td>
                                <td><?= e($admission['unit_name'] ?? '-') ?></td>
                                <td>
                                    <div><?= e($admission['job_title'] ?? '-') ?></div>
                                    <?php if (!empty($admission['employment_function'])): ?>
                                        <div class="text-muted small"><?= e($admission['employment_function']) ?></div>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <span class="badge status-badge status-<?= e((string) ($admission['status'] ?? '')) ?>">
                                        <?= e($config['statuses'][$admission['status']] ?? ($admission['status'] ?? '-')) ?>
                                    </span>
                                </td>
                                <td>
                                    <?php if (!empty($admission['created_at'])): ?>
                                        <?= e(formatDate(substr((string) $admission['created_at'], 0, 10))) ?>
                                    <?php else: ?>
                                        -
                                    <?php endif; ?>
                                </td>
                                <td class="text-end">
                                    <div class="d-flex justify-content-end flex-wrap gap-2">
                                        <a href="<?= e(baseUrl('admin/admissoes/' . $admission['id'])) ?>" class="btn btn-sm btn-outline-dark">Detalhes</a>
                                        <a href="<?= e(baseUrl('admin/admissoes/' . $admission['id'] . '/editar')) ?>" class="btn btn-sm btn-outline-secondary">Editar</a>
                                        <a href="<?= e(baseUrl('admin/admissoes/' . $admission['id'] . '/imprimir')) ?>" target="_blank" class="btn btn-sm btn-outline-primary">Imprimir</a>
                                        <a href="<?= e(baseUrl('admin/admissoes/' . $admission['id'] . '/excluir')) ?>" class="btn btn-sm btn-outline-danger">Excluir</a>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <div class="text-center text-muted py-5 d-none" data-admin-live-empty-state>Nenhuma ficha encontrada para a busca digitada.</div>
        <?php endif; ?>
    </div>
</div>
