<main class="container py-5">
    <div class="row justify-content-center">
        <div class="col-lg-9">
            <div class="card border-0 shadow-soft rounded-4">
                <div class="card-body p-4 p-md-5">
                    <h1 class="h3 fw-bold text-cfc-dark mb-1">Cadastro do Aluno</h1>
                    <p class="text-muted mb-4">Preencha seus dados para acessar o calendário de aulas.</p>
                    <form method="post" action="<?= e(url('register/post')) ?>" 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-6"><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-6"><label class="form-label">E-mail</label><input type="email" name="email" class="form-control" required></div>
                        <div class="col-md-6"><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-4 col-md-2"><label class="form-label">UF</label><input name="uf" maxlength="2" class="form-control text-uppercase" required></div>
                        <div class="col-8 col-md-5"><label class="form-label">Cidade</label><input name="city" class="form-control" required></div>
                        <div class="col-md-5"><label class="form-label">Bairro</label><input name="bairro" class="form-control" required></div>
                        <div class="col-md-6"><label class="form-label">Categoria Pretendida</label><select name="category" id="registerCategory" class="form-select" required>
                            <option value="">Selecione</option><option value="A">A - Motocicleta</option><option value="B">B - Carro</option><option value="AB">AB - Moto e carro</option><option value="C">C - Caminhão</option><option value="D">D - Ônibus / Micro-ônibus</option><option value="E">E - Carreta / Articulado</option>
                        </select></div>
                        <div class="col-md-3" id="lessonsABox"><label class="form-label">Aulas de moto</label><input type="number" name="lessons_a" id="registerLessonsA" class="form-control" min="0" value="2"><small class="text-muted">Mínimo: 2</small></div>
                        <div class="col-md-3" id="lessonsBBox"><label class="form-label">Aulas de carro</label><input type="number" name="lessons_b" id="registerLessonsB" class="form-control" min="0" value="2"><small class="text-muted">Mínimo: 2</small></div>
                        <div class="col-md-3 d-none" id="lessonsOtherBox"><label class="form-label">Quantidade de aulas</label><input type="number" name="lessons_other" id="registerLessonsOther" class="form-control" min="0" value="2"><small class="text-muted">Mínimo: 2</small></div>
                        <div class="col-md-6"><label class="form-label">Senha</label><input type="password" name="password" class="form-control" required minlength="6"></div>
                        <div class="col-12"><div class="alert alert-info rounded-4 mb-0"><i class="bi bi-info-circle"></i> Sua quantidade de aulas será enviada para análise. O administrador aprovará o cadastro antes de liberar o acesso.</div></div>
                        <div class="col-12"><button class="btn btn-primary btn-lg rounded-pill px-5">Enviar cadastro</button></div>
                    </form>
                </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 syncRegisterLessons(){
    const category=document.getElementById('registerCategory'); const aBox=document.getElementById('lessonsABox'); const bBox=document.getElementById('lessonsBBox'); const oBox=document.getElementById('lessonsOtherBox');
    const a=document.getElementById('registerLessonsA'), b=document.getElementById('registerLessonsB'), o=document.getElementById('registerLessonsOther'); if(!category)return;
    const v=category.value; aBox.classList.toggle('d-none', !['A','AB'].includes(v)); bBox.classList.toggle('d-none', !['B','AB'].includes(v)); oBox.classList.toggle('d-none', !['C','D','E'].includes(v));
    if(v==='A'){a.value=Math.max(2,parseInt(a.value||2));b.value=0;} if(v==='B'){b.value=Math.max(2,parseInt(b.value||2));a.value=0;} if(v==='AB'){a.value=Math.max(2,parseInt(a.value||2));b.value=Math.max(2,parseInt(b.value||2));} if(['C','D','E'].includes(v)){o.value=Math.max(2,parseInt(o.value||2));a.value=0;b.value=0;}
}
document.getElementById('registerCategory')?.addEventListener('change', syncRegisterLessons); syncRegisterLessons();
function isRepeatedSequence(digits) {
    return /^(\d)\1+$/.test(digits || '');
}
document.querySelectorAll('.cpf-mask').forEach(function(input) {
    input.addEventListener('input', function() {
        input.value = maskCpf(input.value);
    });
});
document.querySelectorAll('.whatsapp-mask').forEach(function(input) {
    input.addEventListener('input', function() {
        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();
            }
        }
        const cat=document.getElementById('registerCategory')?.value; const qa=parseInt(document.getElementById('registerLessonsA')?.value||0), qb=parseInt(document.getElementById('registerLessonsB')?.value||0), qo=parseInt(document.getElementById('registerLessonsOther')?.value||0);
        if((cat==='A'&&qa<2)||(cat==='B'&&qb<2)||(cat==='AB'&&(qa<2||qb<2))||(['C','D','E'].includes(cat)&&qo<2)){e.preventDefault();alert('A quantidade mínima é de 2 aulas por categoria.');}
    });
});
</script>
