<main class="container-fluid py-4">
    <div class="row g-4">
        <div class="col-lg-3"><?php require APP_PATH . '/Views/admin/_sidebar.php'; ?></div>
        <div class="col-lg-9">
            <div class="d-flex flex-column flex-md-row justify-content-between gap-3 mb-4">
                <div>
                    <h1 class="h3 fw-bold text-cfc-dark mb-1">Alunos Cadastrados</h1>
                    <p class="text-muted mb-0">Cadastre novos alunos pelo painel, finalize cadastros concluídos e acesse o WhatsApp rapidamente.</p>
                </div>
            </div>

            <?php if (!empty($pendingStudents)): ?>
            <div class="card border-0 shadow-soft rounded-4 mb-4 border-warning">
                <div class="card-body p-4">
                    <h2 class="h5 fw-bold mb-1"><i class="bi bi-person-check-fill text-warning"></i> Solicitações de cadastro aguardando aprovação</h2>
                    <p class="text-muted mb-3">Confira a categoria e a quantidade solicitada. Ao aprovar, o pacote é liberado e o aluno poderá entrar no sistema.</p>
                    <div class="row g-3">
                    <?php foreach ($pendingStudents as $pending): ?>
                        <div class="col-lg-6"><div class="border rounded-4 p-3 h-100 bg-warning-subtle">
                            <strong class="d-block"><?= e($pending['name']) ?></strong><small class="text-muted d-block"><?= e($pending['email']) ?> · <?= e(format_whatsapp($pending['whatsapp']??'')) ?></small>
                            <div class="mt-2"><span class="badge text-bg-primary">Categoria <?= e($pending['category']??'-') ?></span>
                            <?php if(($pending['category']??'')==='AB'): ?><span class="badge text-bg-light border text-dark">Moto: <?= (int)$pending['requested_lessons_a'] ?> · Carro: <?= (int)$pending['requested_lessons_b'] ?></span><?php elseif(in_array(($pending['category']??''),['A','B'],true)): ?><span class="badge text-bg-light border text-dark"><?= ($pending['category']==='A'?'Moto':'Carro') ?>: <?= (int)($pending[$pending['category']==='A'?'requested_lessons_a':'requested_lessons_b']??0) ?></span><?php else: ?><span class="badge text-bg-light border text-dark">Aulas: <?= (int)($pending['requested_lessons_other']??0) ?></span><?php endif; ?></div>
                            <small class="d-block text-muted mt-2">Solicitado em <?= !empty($pending['registration_requested_at']) ? e(date('d/m/Y H:i',strtotime($pending['registration_requested_at']))) : '-' ?></small>
                            <form method="post" action="<?= e(url('admin/students/approve')) ?>" class="mt-3" onsubmit="return confirm('Aprovar este cadastro e liberar o pacote de aulas?');"><?= CSRF::input() ?><input type="hidden" name="student_id" value="<?= (int)$pending['id'] ?>"><button class="btn btn-success rounded-pill"><i class="bi bi-check2-circle"></i> Aprovar cadastro</button></form>
                        </div></div>
                    <?php endforeach; ?>
                    </div>
                </div>
            </div>
            <?php endif; ?>

            <div class="card border-0 shadow-soft rounded-4 mb-4">
                <div class="card-body p-4">
                    <div class="d-flex align-items-center gap-3 mb-3">
                        <span class="feature-icon"><i class="bi bi-person-plus"></i></span>
                        <div>
                            <h2 class="h5 fw-bold mb-1">Cadastrar aluno pelo administrador</h2>
                            <p class="text-muted mb-0">Se deixar a senha em branco, o sistema usa os 6 primeiros números do CPF como senha inicial.</p>
                        </div>
                    </div>
                    <form method="post" action="<?= e(url('admin/students/save')) ?>" class="row g-3">
                        <?= CSRF::input() ?>
                        <div class="col-md-6"><label class="form-label">Nome Completo</label><input name="name" class="form-control" required></div>
                        <div class="col-md-3"><label class="form-label">CPF</label><input name="cpf" class="form-control cpf-mask" required inputmode="numeric" maxlength="14" placeholder="000.000.000-00"></div>
                        <div class="col-md-3"><label class="form-label">WhatsApp</label><input name="whatsapp" class="form-control whatsapp-mask" required inputmode="tel" maxlength="15" placeholder="(00) 00000-0000"></div>
                        <div class="col-md-5"><label class="form-label">E-mail / usuário</label><input type="email" name="email" class="form-control" required></div>
                        <div class="col-md-2"><label class="form-label">UF</label><input name="uf" maxlength="2" class="form-control text-uppercase" required></div>
                        <div class="col-md-3"><label class="form-label">Cidade</label><input name="city" class="form-control" required></div>
                        <div class="col-md-2"><label class="form-label">Bairro</label><input name="bairro" class="form-control" required></div>
                        <div class="col-md-4"><label class="form-label">Tipo de habilitação</label><select name="license_process" class="form-select js-license-process" required>
                            <option value="first_license">Primeira habilitação</option><option value="addition">Adição de categoria</option><option value="classification">Classificação / mudança</option>
                        </select></div>
                        <div class="col-md-4 js-process-first"><label class="form-label">Aulas contratadas - A</label><input type="number" name="lessons_a" class="form-control" min="0" value="0"></div>
                        <div class="col-md-4 js-process-first"><label class="form-label">Aulas contratadas - B</label><input type="number" name="lessons_b" class="form-control" min="0" value="0"></div>
                        <div class="col-md-4 js-process-addition d-none"><label class="form-label">Categoria da adição</label><select name="addition_category" class="form-select"><option value="A">A - Moto</option><option value="B">B - Carro</option></select></div>
                        <div class="col-md-4 js-process-addition d-none"><label class="form-label">Aulas contratadas</label><input type="number" name="addition_lessons" class="form-control" min="0" value="0"></div>
                        <div class="col-md-4 js-process-classification d-none"><label class="form-label">Categoria da classificação</label><select name="classification_category" class="form-select"><option value="C">C - Caminhão</option><option value="D">D - Ônibus</option><option value="E">E - Carreta</option></select></div>
                        <div class="col-md-4 js-process-classification d-none"><label class="form-label">Aulas contratadas</label><input type="number" name="classification_lessons" class="form-control" min="0" value="0"></div>
                        <div class="col-md-4"><label class="form-label">Senha inicial</label><input type="text" name="password" class="form-control" minlength="6" placeholder="Opcional"></div>
                        <div class="col-md-4 d-flex align-items-end"><button class="btn btn-success rounded-pill px-4"><i class="bi bi-check2-circle"></i> Cadastrar</button></div>
                    </form>
                </div>
            </div>

            <div class="card border-0 shadow-soft rounded-4"><div class="card-body p-4">
                <div class="table-responsive"><table class="table align-middle"><thead><tr><th>Nome</th><th>CPF</th><th>Contato</th><th>Local</th><th>Categoria</th><th>Nível / Informações</th><th>Status</th><th class="text-end">Ações</th></tr></thead><tbody>
                <?php foreach ($students as $s): ?>
                    <?php
                        $isFinished = (($s['student_status'] ?? 'active') === 'finished'); $isPending = (($s['student_status'] ?? '') === 'pending');
                        $studentWhatsLink = whatsapp_url($s['whatsapp'] ?? '', 'Olá ' . ($s['name'] ?? '') . ', Tudo bem? Aqui é da autoescola.');
                    ?>
                    <tr>
                        <td style="min-width:250px">
                            <div class="d-flex align-items-center gap-3">
                                <?php if (!empty($s['profile_photo_path'])): ?>
                                    <img class="profile-avatar" src="<?= e(asset($s['profile_photo_path'])) ?>" alt="Foto de <?= e($s['name']) ?>">
                                <?php else: ?>
                                    <span class="profile-placeholder"><i class="bi bi-person"></i></span>
                                <?php endif; ?>
                                <div>
                                    <strong class="d-block"><?= e($s['name']) ?></strong>
                                    <small class="d-block text-muted"><?= e($s['email']) ?></small>
                                    <small class="d-block text-primary">Mensagem: <?= e($s['internal_code'] ?? '---------') ?></small>
                                </div>
                            </div>
                        </td>
                        <td><?= e(format_cpf($s['cpf'] ?? '')) ?></td>
                        <td>
                            <?= e(format_whatsapp($s['whatsapp'] ?? '')) ?>
                            <?php if ($studentWhatsLink): ?>
                                <a class="btn btn-sm btn-success rounded-pill d-block mt-2" target="_blank" href="<?= e($studentWhatsLink) ?>"><i class="bi bi-whatsapp"></i> Chamar Aluno</a>
                            <?php endif; ?>
                        </td>
                        <td><?= e($s['city']) ?> / <?= e($s['uf']) ?><small class="d-block text-muted"><?= e($s['bairro']) ?></small></td>
                        <td><span class="badge text-bg-primary"><?= e($s['category'] ?: 'Não definida') ?></span><small class="d-block text-muted mt-1"><?= e(license_process_label($s['license_process'] ?? '')) ?></small></td>
                        <td style="min-width:320px">
                            <div class="mb-2">
                                <span class="badge text-bg-info"><?= e(student_level_label($s['student_level'] ?? '')) ?></span>
                                <?php if (!empty($s['student_level_note'])): ?><small class="d-block text-muted mt-1"><?= e($s['student_level_note']) ?></small><?php endif; ?>
                                <?php if (!empty($s['student_level_updated_at'])): ?><small class="d-block text-muted">Atualizado em <?= e(date('d/m/Y H:i', strtotime($s['student_level_updated_at']))) ?></small><?php endif; ?>
                            </div>
                            <?php $studentPackages = $lessonPackageMap[(int)$s['id']] ?? []; ?>
                            <div class="border rounded-3 p-2 mb-3 bg-light-subtle">
                                <strong class="small d-block mb-2"><i class="bi bi-card-checklist"></i> Aulas contratadas e saldo</strong>
                                <div class="d-flex flex-wrap gap-1 mb-2">
                                    <?php foreach ($studentPackages as $cat => $pkg): ?><span class="badge text-bg-light border text-dark">Cat. <?= e($cat) ?>: <?= (int)$pkg['used_lessons'] ?>/<?= (int)$pkg['contracted_lessons'] ?> feitas · <?= (int)$pkg['remaining_lessons'] ?> restantes</span><?php endforeach; ?>
                                    <?php if (!$studentPackages): ?><span class="text-danger small">Contrato de aulas ainda não configurado.</span><?php endif; ?>
                                </div>
                                <button class="btn btn-sm btn-outline-success rounded-pill" type="button" data-bs-toggle="collapse" data-bs-target="#package-<?= (int)$s['id'] ?>"><i class="bi bi-pencil-square"></i> Configurar contrato</button>
                                <div class="collapse mt-2" id="package-<?= (int)$s['id'] ?>">
                                    <form method="post" action="<?= e(url('admin/students/package')) ?>" class="row g-2 js-package-form">
                                        <?= CSRF::input() ?><input type="hidden" name="student_id" value="<?= (int)$s['id'] ?>">
                                        <div class="col-12"><select name="license_process" class="form-select form-select-sm js-license-process"><option value="first_license" <?= ($s['license_process'] ?? '')==='first_license'?'selected':'' ?>>Primeira habilitação</option><option value="addition" <?= ($s['license_process'] ?? '')==='addition'?'selected':'' ?>>Adição de categoria</option><option value="classification" <?= ($s['license_process'] ?? '')==='classification'?'selected':'' ?>>Classificação / mudança</option></select></div>
                                        <div class="col-6 js-process-first"><label class="small">Qtd. A</label><input type="number" name="lessons_a" min="0" class="form-control form-control-sm" value="<?= (int)($studentPackages['A']['contracted_lessons'] ?? 0) ?>"></div>
                                        <div class="col-6 js-process-first"><label class="small">Qtd. B</label><input type="number" name="lessons_b" min="0" class="form-control form-control-sm" value="<?= (int)($studentPackages['B']['contracted_lessons'] ?? 0) ?>"></div>
                                        <div class="col-6 js-process-addition"><label class="small">Categoria</label><select name="addition_category" class="form-select form-select-sm"><option value="A" <?= ($s['license_category'] ?? '')==='A'?'selected':'' ?>>A</option><option value="B" <?= ($s['license_category'] ?? '')==='B'?'selected':'' ?>>B</option></select></div>
                                        <div class="col-6 js-process-addition"><label class="small">Quantidade</label><input type="number" name="addition_lessons" min="0" class="form-control form-control-sm" value="<?= (int)(($studentPackages[$s['license_category'] ?? 'A']['contracted_lessons'] ?? 0)) ?>"></div>
                                        <div class="col-6 js-process-classification"><label class="small">Categoria</label><select name="classification_category" class="form-select form-select-sm"><option value="C" <?= ($s['license_category'] ?? '')==='C'?'selected':'' ?>>C</option><option value="D" <?= ($s['license_category'] ?? '')==='D'?'selected':'' ?>>D</option><option value="E" <?= ($s['license_category'] ?? '')==='E'?'selected':'' ?>>E</option></select></div>
                                        <div class="col-6 js-process-classification"><label class="small">Quantidade</label><input type="number" name="classification_lessons" min="0" class="form-control form-control-sm" value="<?= (int)(($studentPackages[$s['license_category'] ?? 'C']['contracted_lessons'] ?? 0)) ?>"></div>
                                        <div class="col-12"><button class="btn btn-sm btn-success rounded-pill"><i class="bi bi-save"></i> Salvar contrato</button></div>
                                    </form>
                                </div>
                            </div>
                            <form method="post" action="<?= e(url('admin/students/notes')) ?>">
                                <?= CSRF::input() ?>
                                <input type="hidden" name="student_id" value="<?= (int)$s['id'] ?>">
                                <textarea name="admin_notes" class="form-control form-control-sm mb-2" rows="3" placeholder="Bloco de informações internas do admin"><?= e($s['admin_notes'] ?? '') ?></textarea>
                                <button class="btn btn-sm btn-outline-primary rounded-pill"><i class="bi bi-save"></i> Salvar informações</button>
                            </form>
                        </td>
                        <td>
                            <?php if ($isPending): ?>
                                <span class="badge text-bg-warning text-dark">Aguardando aprovação</span>
                                <?php if (!empty($s['registration_requested_at'])): ?><small class="d-block text-muted"><?= e(date('d/m/Y H:i', strtotime($s['registration_requested_at']))) ?></small><?php endif; ?>
                            <?php elseif ($isFinished): ?>
                                <span class="badge text-bg-success">Finalizado</span>
                                <?php if (!empty($s['finished_at'])): ?><small class="d-block text-muted"><?= e(date('d/m/Y', strtotime($s['finished_at']))) ?></small><?php endif; ?>
                            <?php else: ?>
                                <span class="badge text-bg-warning text-dark">Ativo</span>
                            <?php endif; ?>
                        </td>
                        <td class="text-end">
                            <div class="d-flex flex-wrap gap-2 justify-content-end">
                                <button type="button" class="btn btn-sm btn-outline-warning rounded-pill" data-bs-toggle="modal" data-bs-target="#editStudent-<?= (int)$s['id'] ?>"><i class="bi bi-pencil-square"></i> Editar cadastro</button>
                                <?php if ($isPending): ?>
                                    <form method="post" action="<?= e(url('admin/students/approve')) ?>" onsubmit="return confirm('Aprovar este cadastro e liberar o pacote de aulas?');"><?= CSRF::input() ?><input type="hidden" name="student_id" value="<?= (int)$s['id'] ?>"><button class="btn btn-sm btn-success rounded-pill"><i class="bi bi-check2-circle"></i> Aprovar</button></form>
                                <?php elseif ($isFinished): ?>
                                    <form method="post" action="<?= e(url('admin/students/reactivate')) ?>">
                                        <?= CSRF::input() ?>
                                        <input type="hidden" name="student_id" value="<?= (int)$s['id'] ?>">
                                        <button class="btn btn-sm btn-outline-primary rounded-pill">Reativar</button>
                                    </form>
                                    <form method="post" action="<?= e(url('admin/students/delete-finished')) ?>" onsubmit="return confirm('Tem certeza que deseja apagar este cadastro finalizado? Essa ação remove o aluno e seus agendamentos do sistema.');">
                                        <?= CSRF::input() ?>
                                        <input type="hidden" name="student_id" value="<?= (int)$s['id'] ?>">
                                        <button class="btn btn-sm btn-outline-danger rounded-pill">Apagar Cadastro</button>
                                    </form>
                                <?php else: ?>
                                    <form method="post" action="<?= e(url('admin/students/finish')) ?>" onsubmit="return confirm('Marcar este cadastro como finalizado?');">
                                        <?= CSRF::input() ?>
                                        <input type="hidden" name="student_id" value="<?= (int)$s['id'] ?>">
                                        <button class="btn btn-sm btn-success rounded-pill">Finalizar</button>
                                    </form>
                                <?php endif; ?>
                            </div>
                            <div class="modal fade text-start" id="editStudent-<?= (int)$s['id'] ?>" tabindex="-1" aria-hidden="true">
                                <div class="modal-dialog modal-lg modal-dialog-scrollable"><div class="modal-content rounded-4 border-0">
                                    <div class="modal-header"><h2 class="modal-title h5">Editar cadastro de <?= e($s['name']) ?></h2><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
                                    <form method="post" action="<?= e(url('admin/students/update')) ?>" class="js-mask-form">
                                        <div class="modal-body"><div class="row g-3">
                                            <?= CSRF::input() ?><input type="hidden" name="student_id" value="<?= (int)$s['id'] ?>">
                                            <div class="col-md-6"><label class="form-label">Nome completo</label><input name="name" class="form-control" required value="<?= e($s['name']) ?>"></div>
                                            <div class="col-md-3"><label class="form-label">CPF</label><input name="cpf" class="form-control cpf-mask" required value="<?= e(format_cpf($s['cpf']??'')) ?>" maxlength="14"></div>
                                            <div class="col-md-3"><label class="form-label">WhatsApp</label><input name="whatsapp" class="form-control whatsapp-mask" required value="<?= e(format_whatsapp($s['whatsapp']??'')) ?>" maxlength="15"></div>
                                            <div class="col-md-6"><label class="form-label">E-mail / usuário</label><input type="email" name="email" class="form-control" required value="<?= e($s['email']) ?>"></div>
                                            <div class="col-md-2"><label class="form-label">UF</label><input name="uf" maxlength="2" class="form-control text-uppercase" required value="<?= e($s['uf']) ?>"></div>
                                            <div class="col-md-2"><label class="form-label">Cidade</label><input name="city" class="form-control" required value="<?= e($s['city']) ?>"></div>
                                            <div class="col-md-2"><label class="form-label">Bairro</label><input name="bairro" class="form-control" required value="<?= e($s['bairro']) ?>"></div>
                                            <div class="col-md-6"><label class="form-label">Nova senha</label><input type="password" name="password" minlength="6" class="form-control" placeholder="Deixe em branco para manter"></div>
                                            <div class="col-12"><div class="alert alert-info rounded-4 mb-0"><i class="bi bi-info-circle"></i> As aulas contratadas continuam sendo editadas separadamente em <strong>Configurar contrato</strong>.</div></div>
                                        </div></div>
                                        <div class="modal-footer"><button type="button" class="btn btn-light rounded-pill" data-bs-dismiss="modal">Cancelar</button><button class="btn btn-primary rounded-pill"><i class="bi bi-save"></i> Salvar cadastro</button></div>
                                    </form>
                                </div></div>
                            </div>
                        </td>
                    </tr>
                <?php endforeach; ?>
                <?php if (!$students): ?><tr><td colspan="8" class="text-center text-muted py-4">Nenhum aluno cadastrado.</td></tr><?php endif; ?>
                </tbody></table></div>
            </div></div>
        </div>
    </div>
</main>

<script>
function cpfDigits(value) {
    return (value || '').replace(/\D/g, '').slice(0, 11);
}
function whatsappDigits(value) {
    return (value || '').replace(/\D/g, '').slice(0, 11);
}
function maskCpf(value) {
    let v = cpfDigits(value);
    v = v.replace(/(\d{3})(\d)/, '$1.$2');
    v = v.replace(/(\d{3})(\d)/, '$1.$2');
    v = v.replace(/(\d{3})(\d{1,2})$/, '$1-$2');
    return v;
}
function maskWhatsapp(value) {
    let v = whatsappDigits(value);
    if (v.length > 10) {
        v = v.replace(/^(\d{2})(\d{5})(\d{0,4}).*/, '($1) $2-$3');
    } else if (v.length > 6) {
        v = v.replace(/^(\d{2})(\d{4})(\d{0,4}).*/, '($1) $2-$3');
    } else if (v.length > 2) {
        v = v.replace(/^(\d{2})(\d{0,5})/, '($1) $2');
    } else if (v.length > 0) {
        v = v.replace(/^(\d*)/, '($1');
    }
    return v;
}
function isRepeatedSequence(digits) {
    return /^(\d)\1+$/.test(digits || '');
}
document.querySelectorAll('.cpf-mask').forEach(function(input) {
    input.addEventListener('input', function() {
        input.value = maskCpf(input.value);
    });
    if (input.value) input.value = maskCpf(input.value);
});
document.querySelectorAll('.whatsapp-mask').forEach(function(input) {
    input.addEventListener('input', function() {
        input.value = maskWhatsapp(input.value);
    });
    if (input.value) input.value = maskWhatsapp(input.value);
});
document.querySelectorAll('form').forEach(function(form) {
    form.addEventListener('submit', function(e) {
        const cpfInput = form.querySelector('.cpf-mask');
        const whatsInput = form.querySelector('.whatsapp-mask');
        if (cpfInput) {
            const cpf = cpfDigits(cpfInput.value);
            if (cpf.length !== 11 || isRepeatedSequence(cpf)) {
                e.preventDefault();
                alert('CPF inválido. Informe os 11 dígitos e não use sequência repetida como 000.000.000-00.');
                cpfInput.focus();
                return;
            }
        }
        if (whatsInput) {
            const whats = whatsappDigits(whatsInput.value);
            if (whats.length !== 11 || isRepeatedSequence(whats)) {
                e.preventDefault();
                alert('WhatsApp inválido. Informe com DDD e 11 dígitos no formato (00) 00000-0000.');
                whatsInput.focus();
            }
        }
    });
});
</script>

<script>
function syncLicenseProcess(scope){var select=scope.querySelector('.js-license-process');if(!select)return;var v=select.value;scope.querySelectorAll('.js-process-first').forEach(function(e){e.classList.toggle('d-none',v!=='first_license');});scope.querySelectorAll('.js-process-addition').forEach(function(e){e.classList.toggle('d-none',v!=='addition');});scope.querySelectorAll('.js-process-classification').forEach(function(e){e.classList.toggle('d-none',v!=='classification');});}
document.querySelectorAll('form').forEach(function(form){if(form.querySelector('.js-license-process')){syncLicenseProcess(form);form.querySelector('.js-license-process').addEventListener('change',function(){syncLicenseProcess(form);});}});
</script>
