<?php
$errors = $errors ?? [];
$admission = $admission ?? [];
$academic = $admission['academic'] ?? [];
$currentJobTitle = old('job_title', $admission['job_title'] ?? '');
$currentUnitName = old('unit_name', $admission['unit_name'] ?? '');
$isProfessorJob = in_array($currentJobTitle, $config['professor_jobs'] ?? [], true);
$isInternJob = $currentJobTitle === 'Estagiário Ed. Física';
$showAcademic = (int) old('is_student', $admission['is_student'] ?? 0) === 1 || $isInternJob;
$currentMaritalStatus = old('marital_status', $admission['marital_status'] ?? '');
$hasDependents = (int) old('has_dependents', $admission['has_dependents'] ?? 0) === 1;
$dependents = old('dependents', $admission['dependents'] ?? [['full_name'=>'','birth_date'=>'','cpf'=>'','birth_city'=>'','has_disability'=>0]]);
$dependentCertificateAttachments = [];
if (!empty($admission['attachments'])) {
    foreach ($admission['attachments'] as $attachment) {
        $labelKey = (string) ($attachment['label_key'] ?? '');
        if (preg_match('/^dependent_birth_certificate_(\d+)$/', $labelKey, $matches)) {
            $dependentCertificateAttachments[(int) $matches[1]] = $attachment;
        } elseif ($labelKey === 'dependent_birth_certificate' && !isset($dependentCertificateAttachments[0])) {
            $dependentCertificateAttachments[0] = $attachment;
        }
    }
}
$statuses = $config['statuses'];
$storedPixFallback = strtoupper(trim((string) ($admission['bank_agency'] ?? ''))) === 'PIX' && !empty($admission['bank_account'] ?? '');
$currentBankPaymentMethod = (string) old('bank_payment_method', $admission['bank_payment_method'] ?? ((!empty($admission['pix_key']) || $storedPixFallback) ? 'pix' : 'bank'));
$showBankDetails = $currentBankPaymentMethod !== 'pix';
$bankAgencyValue = $currentBankPaymentMethod === 'pix' && empty($admission['bank_payment_method'] ?? null) && $storedPixFallback ? '' : old('bank_agency', $admission['bank_agency'] ?? '');
$bankAccountValue = $currentBankPaymentMethod === 'pix' && empty($admission['bank_payment_method'] ?? null) && $storedPixFallback ? '' : old('bank_account', $admission['bank_account'] ?? '');
$pixKeyValue = old('pix_key', $admission['pix_key'] ?? ($storedPixFallback ? ($admission['bank_account'] ?? '') : ''));
$invalidClass = static fn (string $key): string => !empty($errors[$key]) ? ' is-invalid' : '';
$fieldError = static fn (string $key): string => !empty($errors[$key]) ? '<div class="field-error">' . e((string) $errors[$key]) . '</div>' : '';
?>
<?= csrf_field() ?>

<section class="form-section">
    <div class="section-header"><h2>1. Aviso e consentimento</h2><p>Sem esse aceite, o formulário nem anda.</p></div>
    <div class="alert alert-light border lh-lg">Este formulário foi estruturado para o processo de admissão e contempla dados pessoais, documentos, dados acadêmicos e anexos. Os dados devem ser tratados conforme a LGPD.</div>
    <div class="form-check form-switch">
        <input class="form-check-input<?= $invalidClass('consent') ?>" type="checkbox" id="consent" name="consent" value="1" <?= checked(old('consent', $admission['consent'] ?? 0), 1) ?>>
        <label class="form-check-label fw-semibold" for="consent">Li e concordo em prosseguir</label>
    </div>
    <?php if (!empty($errors['consent'])): ?><div class="field-error"><?= e($errors['consent']) ?></div><?php endif; ?>
</section>

<section class="form-section">
    <div class="section-header"><h2>2. Dados pessoais</h2><p>Identificação principal do colaborador.</p></div>
    <div class="row g-3">
        <div class="col-md-4"><label class="form-label">Raça</label><select class="form-select<?= $invalidClass('race') ?>" name="race"><option value="">Selecione</option><?php foreach ($config['races'] as $key=>$label): ?><option value="<?= e($key) ?>" <?= selected(old('race', $admission['race'] ?? ''), $key) ?>><?= e($label) ?></option><?php endforeach; ?></select><?php if (!empty($errors['race'])): ?><div class="field-error"><?= e($errors['race']) ?></div><?php endif; ?></div>
        <div class="col-md-4"><label class="form-label">Unidade</label><select class="form-select<?= $invalidClass('unit_name') ?>" name="unit_name" id="unit_name"><option value="">Selecione</option><?php foreach (($config['units'] ?? []) as $unit): ?><option value="<?= e($unit) ?>" <?= selected($currentUnitName, $unit) ?>><?= e($unit) ?></option><?php endforeach; ?><?php if ($currentUnitName !== '' && !in_array($currentUnitName, $config['units'] ?? [], true)): ?><option value="<?= e($currentUnitName) ?>" selected>Atual: <?= e($currentUnitName) ?> (fora da lista)</option><?php endif; ?></select><?php if (!empty($errors['unit_name'])): ?><div class="field-error"><?= e($errors['unit_name']) ?></div><?php endif; ?></div>
        <div class="col-md-4"><label class="form-label">Cargo</label><select class="form-select<?= $invalidClass('job_title') ?>" name="job_title" id="job_title"><option value="">Selecione</option><?php foreach (($config['job_titles'] ?? []) as $job): ?><option value="<?= e($job) ?>" <?= selected($currentJobTitle, $job) ?>><?= e($job) ?></option><?php endforeach; ?><?php if ($currentJobTitle !== '' && !in_array($currentJobTitle, $config['job_titles'] ?? [], true)): ?><option value="<?= e($currentJobTitle) ?>" selected>Atual: <?= e($currentJobTitle) ?> (fora da lista)</option><?php endif; ?></select><?php if (!empty($errors['job_title'])): ?><div class="field-error"><?= e($errors['job_title']) ?></div><?php endif; ?></div>
        <div class="col-md-6"><label class="form-label">Nome completo</label><input type="text" class="form-control<?= $invalidClass('full_name') ?>" name="full_name" value="<?= e(old('full_name', $admission['full_name'] ?? '')) ?>"><?php if (!empty($errors['full_name'])): ?><div class="field-error"><?= e($errors['full_name']) ?></div><?php endif; ?></div>
        <div class="col-md-3"><label class="form-label">Pai</label><input type="text" class="form-control" name="father_name" value="<?= e(old('father_name', $admission['father_name'] ?? '')) ?>"></div>
        <div class="col-md-3"><label class="form-label">Mãe</label><input type="text" class="form-control<?= $invalidClass('mother_name') ?>" name="mother_name" value="<?= e(old('mother_name', $admission['mother_name'] ?? '')) ?>"><?php if (!empty($errors['mother_name'])): ?><div class="field-error"><?= e($errors['mother_name']) ?></div><?php endif; ?></div>
        <div class="col-md-3"><label class="form-label">Data de nascimento</label><input type="date" class="form-control<?= $invalidClass('birth_date') ?>" name="birth_date" value="<?= e(old('birth_date', $admission['birth_date'] ?? '')) ?>"><?php if (!empty($errors['birth_date'])): ?><div class="field-error"><?= e($errors['birth_date']) ?></div><?php endif; ?></div>
        <div class="col-md-3"><label class="form-label">Estado civil</label><select class="form-select<?= $invalidClass('marital_status') ?>" name="marital_status" id="marital_status"><option value="">Selecione</option><?php foreach ($config['marital_statuses'] as $key=>$label): ?><option value="<?= e($key) ?>" <?= selected($currentMaritalStatus, $key) ?>><?= e($label) ?></option><?php endforeach; ?></select><?php if (!empty($errors['marital_status'])): ?><div class="field-error"><?= e($errors['marital_status']) ?></div><?php endif; ?></div>
        <div class="col-md-3"><label class="form-label">Você é estudante?</label><select class="form-select toggle-field<?= $invalidClass('is_student') ?>" name="is_student" data-target="#academic-section"><option value="0" <?= selected(old('is_student', $admission['is_student'] ?? 0), 0) ?>>Não</option><option value="1" <?= selected(old('is_student', $admission['is_student'] ?? 0), 1) ?>>Sim</option></select></div>
        <div class="col-md-3"><label class="form-label">Escolaridade</label><select class="form-select<?= $invalidClass('education_level') ?>" name="education_level"><option value="">Selecione</option><?php foreach ($config['education_levels'] as $key=>$label): ?><option value="<?= e($key) ?>" <?= selected(old('education_level', $admission['education_level'] ?? ''), $key) ?>><?= e($label) ?></option><?php endforeach; ?></select><?php if (!empty($errors['education_level'])): ?><div class="field-error"><?= e($errors['education_level']) ?></div><?php endif; ?></div>
        <div class="col-md-4"><label class="form-label">Nacionalidade</label><input type="text" class="form-control<?= $invalidClass('nationality') ?>" name="nationality" value="<?= e(old('nationality', $admission['nationality'] ?? '')) ?>"><?php if (!empty($errors['nationality'])): ?><div class="field-error"><?= e($errors['nationality']) ?></div><?php endif; ?></div>
        <div class="col-md-4"><label class="form-label">Naturalidade</label><input type="text" class="form-control" name="place_of_birth" value="<?= e(old('place_of_birth', $admission['place_of_birth'] ?? '')) ?>"></div>
        <div class="col-md-4"><label class="form-label">Município de nascimento</label><input type="text" class="form-control<?= $invalidClass('birth_city') ?>" name="birth_city" value="<?= e(old('birth_city', $admission['birth_city'] ?? '')) ?>"><?php if (!empty($errors['birth_city'])): ?><div class="field-error"><?= e($errors['birth_city']) ?></div><?php endif; ?></div>
        <div class="col-md-4"><label class="form-label">Estado de nascimento</label><input type="text" class="form-control text-uppercase" maxlength="2" name="birth_state" value="<?= e(old('birth_state', $admission['birth_state'] ?? '')) ?>"></div>
        <div class="col-md-4"><label class="form-label">E-mail pessoal</label><input type="email" class="form-control<?= $invalidClass('personal_email') ?>" name="personal_email" value="<?= e(old('personal_email', $admission['personal_email'] ?? '')) ?>"><?php if (!empty($errors['personal_email'])): ?><div class="field-error"><?= e($errors['personal_email']) ?></div><?php endif; ?></div>
        <div class="col-md-4"><label class="form-label">Celular</label><input type="text" class="form-control js-phone<?= $invalidClass('phone') ?>" name="phone" value="<?= e(old('phone', $admission['phone'] ?? '')) ?>"><?php if (!empty($errors['phone'])): ?><div class="field-error"><?= e($errors['phone']) ?></div><?php endif; ?></div>
        <div class="col-md-4"><label class="form-label">Contato de emergência</label><input type="text" class="form-control js-phone<?= $invalidClass('emergency_contact') ?>" name="emergency_contact" value="<?= e(old('emergency_contact', $admission['emergency_contact'] ?? '')) ?>"><?php if (!empty($errors['emergency_contact'])): ?><div class="field-error"><?= e($errors['emergency_contact']) ?></div><?php endif; ?></div>
    </div>
</section>

<section class="form-section">
    <div class="section-header"><h2>3. Endereço</h2><p>Dados residenciais do colaborador.</p></div>
    <div class="row g-3">
        <div class="col-md-6"><label class="form-label">Endereço</label><input type="text" class="form-control<?= $invalidClass('address_line') ?>" name="address_line" value="<?= e(old('address_line', $admission['address_line'] ?? '')) ?>"><?php if (!empty($errors['address_line'])): ?><div class="field-error"><?= e($errors['address_line']) ?></div><?php endif; ?></div>
        <div class="col-md-2"><label class="form-label">Número</label><input type="text" class="form-control<?= $invalidClass('address_number') ?>" name="address_number" value="<?= e(old('address_number', $admission['address_number'] ?? '')) ?>"><?php if (!empty($errors['address_number'])): ?><div class="field-error"><?= e($errors['address_number']) ?></div><?php endif; ?></div>
        <div class="col-md-4"><label class="form-label">Bairro</label><input type="text" class="form-control<?= $invalidClass('neighborhood') ?>" name="neighborhood" value="<?= e(old('neighborhood', $admission['neighborhood'] ?? '')) ?>"><?php if (!empty($errors['neighborhood'])): ?><div class="field-error"><?= e($errors['neighborhood']) ?></div><?php endif; ?></div>
        <div class="col-md-2"><label class="form-label">CEP</label><input type="text" class="form-control js-cep<?= $invalidClass('zip_code') ?>" name="zip_code" value="<?= e(old('zip_code', $admission['zip_code'] ?? '')) ?>"><?php if (!empty($errors['zip_code'])): ?><div class="field-error"><?= e($errors['zip_code']) ?></div><?php endif; ?></div>
        <div class="col-md-4"><label class="form-label">Cidade</label><input type="text" class="form-control<?= $invalidClass('city') ?>" name="city" value="<?= e(old('city', $admission['city'] ?? '')) ?>"><?php if (!empty($errors['city'])): ?><div class="field-error"><?= e($errors['city']) ?></div><?php endif; ?></div>
        <div class="col-md-4"><label class="form-label">Outros / Complemento</label><input type="text" class="form-control" name="address_extra" value="<?= e(old('address_extra', $admission['address_extra'] ?? '')) ?>"></div>
        <div class="col-md-2"><label class="form-label">UF</label><input type="text" class="form-control text-uppercase<?= $invalidClass('state') ?>" maxlength="2" name="state" value="<?= e(old('state', $admission['state'] ?? '')) ?>"><?php if (!empty($errors['state'])): ?><div class="field-error"><?= e($errors['state']) ?></div><?php endif; ?></div>
    </div>
</section>

<section class="form-section">
    <div class="section-header"><h2>4. Documentos</h2><p>Documentos obrigatórios para admissão.</p></div>
    <div class="row g-3">
        <div class="col-md-3"><label class="form-label">RG</label><input type="text" class="form-control<?= $invalidClass('rg_number') ?>" name="rg_number" value="<?= e(old('rg_number', $admission['rg_number'] ?? '')) ?>"><?php if (!empty($errors['rg_number'])): ?><div class="field-error"><?= e($errors['rg_number']) ?></div><?php endif; ?></div>
        <div class="col-md-3"><label class="form-label">Data de expedição</label><input type="date" class="form-control<?= $invalidClass('rg_issue_date') ?>" name="rg_issue_date" value="<?= e(old('rg_issue_date', $admission['rg_issue_date'] ?? '')) ?>"><?php if (!empty($errors['rg_issue_date'])): ?><div class="field-error"><?= e($errors['rg_issue_date']) ?></div><?php endif; ?></div>
        <div class="col-md-3"><label class="form-label">Órgão de expedição</label><input type="text" class="form-control<?= $invalidClass('rg_issuer') ?>" name="rg_issuer" value="<?= e(old('rg_issuer', $admission['rg_issuer'] ?? '')) ?>"><?php if (!empty($errors['rg_issuer'])): ?><div class="field-error"><?= e($errors['rg_issuer']) ?></div><?php endif; ?></div>
        <div class="col-md-3"><label class="form-label">CPF</label><input type="text" class="form-control js-cpf<?= $invalidClass('cpf') ?>" name="cpf" value="<?= e(old('cpf', $admission['cpf'] ?? '')) ?>"><?php if (!empty($errors['cpf'])): ?><div class="field-error"><?= e($errors['cpf']) ?></div><?php endif; ?></div>
        <div class="col-md-4"><label class="form-label">Número PIS/PASEP</label><input type="text" class="form-control<?= $invalidClass('pis_number') ?>" name="pis_number" value="<?= e(old('pis_number', $admission['pis_number'] ?? '')) ?>"><?php if (!empty($errors['pis_number'])): ?><div class="field-error"><?= e($errors['pis_number']) ?></div><?php endif; ?></div>
        <div class="col-md-4"><label class="form-label">Data de emissão do PIS</label><input type="date" class="form-control<?= $invalidClass('pis_issue_date') ?>" name="pis_issue_date" value="<?= e(old('pis_issue_date', $admission['pis_issue_date'] ?? '')) ?>"><?php if (!empty($errors['pis_issue_date'])): ?><div class="field-error"><?= e($errors['pis_issue_date']) ?></div><?php endif; ?></div>
    </div>
</section>


<section id="cref-section" class="form-section conditional-section<?= $isProfessorJob ? '' : ' is-hidden' ?>">
    <div class="section-header"><h2>5. Professores de Educação Física</h2><p>Preencha apenas para cargos que exigem registro profissional.</p></div>
    <div class="row g-3">
        <div class="col-md-4"><label class="form-label">Número do CREF</label><input type="text" class="form-control<?= $invalidClass('cref_number') ?>" name="cref_number" value="<?= e(old('cref_number', $admission['cref_number'] ?? '')) ?>"><?php if (!empty($errors['cref_number'])): ?><div class="field-error"><?= e($errors['cref_number']) ?></div><?php endif; ?></div>
        <div class="col-md-4"><label class="form-label">CNPJ</label><input type="text" class="form-control js-cnpj<?= $invalidClass('professor_mei_cnpj') ?>" name="professor_mei_cnpj" value="<?= e(old('professor_mei_cnpj', $admission['professor_mei_cnpj'] ?? '')) ?>"><?php if (!empty($errors['professor_mei_cnpj'])): ?><div class="field-error"><?= e($errors['professor_mei_cnpj']) ?></div><?php endif; ?></div>
        <div class="col-md-4">
            <div class="alert alert-light border mb-0 h-100 d-flex align-items-center">Para professores de Educação Física, o CREF, o CNPJ e os anexos profissionais são obrigatórios.</div>
        </div>
    </div>
</section>

<section class="form-section">
    <div class="section-header"><h2>6. Dependentes</h2><p>Estrutura escalável para aceitar mais dependentes no futuro.</p></div>
    <div class="row g-3">
        <div class="col-md-4"><label class="form-label">Possui filhos/dependentes?</label><select class="form-select toggle-field<?= $invalidClass('dependents') ?>" name="has_dependents" id="has_dependents" data-target="#dependents-section"><option value="0" <?= selected(old('has_dependents', $admission['has_dependents'] ?? 0), 0) ?>>Não</option><option value="1" <?= selected(old('has_dependents', $admission['has_dependents'] ?? 0), 1) ?>>Sim</option></select></div>
        <div class="col-md-4"><label class="form-label">Filho com deficiência ou invalidez?</label><select class="form-select" name="dependent_has_disability"><option value="0" <?= selected(old('dependent_has_disability', $admission['dependent_has_disability'] ?? 0), 0) ?>>Não</option><option value="1" <?= selected(old('dependent_has_disability', $admission['dependent_has_disability'] ?? 0), 1) ?>>Sim</option></select></div>
    </div>
    <div id="dependents-section" class="conditional-section mt-3">
        <?php if (!empty($errors['dependents'])): ?><div class="field-error mb-2"><?= e($errors['dependents']) ?></div><?php endif; ?>
        <div id="dependents-wrapper" class="d-grid gap-3">
            <?php foreach ($dependents as $index => $dependent): ?>
            <div class="dependent-card border rounded-4 p-3">
                <div class="d-flex justify-content-between align-items-center mb-3"><h3 class="h6 mb-0">Dependente <?= (int)$index + 1 ?></h3><button type="button" class="btn btn-sm btn-outline-danger remove-dependent">Remover</button></div>
                <div class="row g-3">
                    <div class="col-md-4"><label class="form-label">Nome completo</label><input type="text" class="form-control" name="dependents[<?= $index ?>][full_name]" value="<?= e($dependent['full_name'] ?? '') ?>"><?php if (!empty($errors["dependents.$index.full_name"])): ?><div class="field-error"><?= e($errors["dependents.$index.full_name"]) ?></div><?php endif; ?></div>
                    <div class="col-md-3"><label class="form-label">Data de nascimento</label><input type="date" class="form-control" name="dependents[<?= $index ?>][birth_date]" value="<?= e($dependent['birth_date'] ?? '') ?>"><?php if (!empty($errors["dependents.$index.birth_date"])): ?><div class="field-error"><?= e($errors["dependents.$index.birth_date"]) ?></div><?php endif; ?></div>
                    <div class="col-md-3"><label class="form-label">CPF</label><input type="text" class="form-control js-cpf" name="dependents[<?= $index ?>][cpf]" value="<?= e($dependent['cpf'] ?? '') ?>"><?php if (!empty($errors["dependents.$index.cpf"])): ?><div class="field-error"><?= e($errors["dependents.$index.cpf"]) ?></div><?php endif; ?></div>
                    <div class="col-md-2"><label class="form-label">Deficiência?</label><select class="form-select" name="dependents[<?= $index ?>][has_disability]"><option value="0" <?= selected($dependent['has_disability'] ?? 0, 0) ?>>Não</option><option value="1" <?= selected($dependent['has_disability'] ?? 0, 1) ?>>Sim</option></select></div>
                    <div class="col-md-6"><label class="form-label">Local/cidade de nascimento</label><input type="text" class="form-control" name="dependents[<?= $index ?>][birth_city]" value="<?= e($dependent['birth_city'] ?? '') ?>"><?php if (!empty($errors["dependents.$index.birth_city"])): ?><div class="field-error"><?= e($errors["dependents.$index.birth_city"]) ?></div><?php endif; ?></div>
                    <div class="col-md-6">
                        <label class="form-label">Certidão de nascimento do dependente <?= (int)$index + 1 ?></label>
                        <input type="file" class="form-control<?= !empty($errors["dependent_birth_certificates.$index"]) ? ' is-invalid' : '' ?>" name="dependent_birth_certificates[<?= $index ?>]" accept=".jpg,.jpeg,.png,.pdf">
                        <?php if (!empty($errors["dependent_birth_certificates.$index"])): ?><div class="field-error"><?= e($errors["dependent_birth_certificates.$index"]) ?></div><?php endif; ?>
                        <?php $currentDependentCertificate = $dependentCertificateAttachments[$index] ?? null; ?>
                        <?php if ($currentDependentCertificate && ($mode ?? 'create') === 'edit'): ?>
                            <div class="small text-muted mt-2"><?= e($currentDependentCertificate['original_name']) ?></div>
                            <div class="mt-2 d-flex gap-2 flex-wrap">
                                <a href="<?= e(baseUrl('admin/admissoes/' . $admission['id'] . '/anexos/' . $currentDependentCertificate['id'] . '/download')) ?>" target="_blank" class="btn btn-sm btn-outline-primary">Baixar atual</a>
                                <?php if (str_starts_with((string) $currentDependentCertificate['mime_type'], 'image/')): ?>
                                    <a href="<?= e(baseUrl('admin/admissoes/' . $admission['id'] . '/anexos/' . $currentDependentCertificate['id'] . '/visualizar')) ?>" target="_blank" class="btn btn-sm btn-outline-secondary">Visualizar</a>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        <button type="button" class="btn btn-outline-primary mt-3" id="add-dependent">Adicionar dependente</button>
    </div>
</section>

<section class="form-section">
    <?php if (($mode ?? 'create') === 'edit'): ?>
        <div class="section-header"><h2>7. Dados de admissão e bancários</h2><p>Campos internos preenchidos pelo usuário do sistema.</p></div>
        <div class="row g-3">
            <div class="col-md-4"><label class="form-label">Função</label><input type="text" class="form-control" name="employment_function" value="<?= e(old('employment_function', $admission['employment_function'] ?? '')) ?>"></div>
            <div class="col-md-4"><label class="form-label">Data de admissão</label><input type="date" class="form-control<?= $invalidClass('admission_date') ?>" name="admission_date" value="<?= e(old('admission_date', $admission['admission_date'] ?? '')) ?>"><?php if (!empty($errors['admission_date'])): ?><div class="field-error"><?= e($errors['admission_date']) ?></div><?php endif; ?></div>
            <div class="col-md-4"><label class="form-label">Data de demissão</label><input type="date" class="form-control<?= $invalidClass('dismissal_date') ?>" name="dismissal_date" value="<?= e(old('dismissal_date', $admission['dismissal_date'] ?? '')) ?>"><?php if (!empty($errors['dismissal_date'])): ?><div class="field-error"><?= e($errors['dismissal_date']) ?></div><?php endif; ?></div>
            <div class="col-md-3"><label class="form-label">Carga horária</label><input type="text" class="form-control" name="workload_hours" value="<?= e(old('workload_hours', $admission['workload_hours'] ?? '')) ?>" placeholder="Ex.: 30"></div>
            <div class="col-md-3"><label class="form-label">Salário</label><input type="text" class="form-control js-money<?= $invalidClass('salary_amount') ?>" name="salary_amount" value="<?= e(old('salary_amount', $admission['salary_amount'] ?? '')) ?>"><?php if (!empty($errors['salary_amount'])): ?><div class="field-error"><?= e($errors['salary_amount']) ?></div><?php endif; ?></div>
            <div class="col-md-3"><label class="form-label">Tipo de salário</label><select class="form-select<?= $invalidClass('salary_type') ?>" name="salary_type"><option value="">Selecione</option><?php foreach ($config['salary_types'] as $key=>$label): ?><option value="<?= e($key) ?>" <?= selected(old('salary_type', $admission['salary_type'] ?? ''), $key) ?>><?= e($label) ?></option><?php endforeach; ?></select><?php if (!empty($errors['salary_type'])): ?><div class="field-error"><?= e($errors['salary_type']) ?></div><?php endif; ?></div>
            <div class="col-md-3"><label class="form-label">Irá utilizar vale transporte?</label><select class="form-select toggle-field<?= $invalidClass('transport_voucher_daily_value') ?>" name="uses_transport_voucher" data-target="#vt-section"><option value="0" <?= selected(old('uses_transport_voucher', $admission['uses_transport_voucher'] ?? 0), 0) ?>>Não</option><option value="1" <?= selected(old('uses_transport_voucher', $admission['uses_transport_voucher'] ?? 0), 1) ?>>Sim</option></select></div>
            <div class="col-md-3 conditional-section" id="vt-section"><label class="form-label">Valor diário do vale transporte</label><input type="text" class="form-control<?= $invalidClass('transport_voucher_daily_value') ?>" name="transport_voucher_daily_value" value="<?= e(old('transport_voucher_daily_value', $admission['transport_voucher_daily_value'] ?? '')) ?>" placeholder="Ex.: 12,50" inputmode="decimal"><?php if (!empty($errors['transport_voucher_daily_value'])): ?><div class="field-error"><?= e($errors['transport_voucher_daily_value']) ?></div><?php endif; ?></div>
            <div class="col-md-2"><label class="form-label">Uniforme</label><select class="form-select" name="uniform_size"><option value="">Selecione</option><?php foreach ($config['uniform_sizes'] as $size): ?><option value="<?= e($size) ?>" <?= selected(old('uniform_size', $admission['uniform_size'] ?? ''), $size) ?>><?= e($size) ?></option><?php endforeach; ?></select></div>
            <div class="col-md-3"><label class="form-label">Forma de recebimento</label><select class="form-select" name="bank_payment_method" id="bank_payment_method"><option value="bank" <?= selected($currentBankPaymentMethod, 'bank') ?>>Agência / Conta</option><option value="pix" <?= selected($currentBankPaymentMethod, 'pix') ?>>PIX</option></select></div>
            <div class="col-md-5 conditional-section<?= $showBankDetails ? '' : ' is-hidden' ?>" id="bank-details-section"><div class="row g-3"><div class="col-md-4"><label class="form-label">Agência</label><input type="text" class="form-control<?= $invalidClass('bank_agency') ?>" name="bank_agency" value="<?= e($bankAgencyValue) ?>"><?php if (!empty($errors['bank_agency'])): ?><div class="field-error"><?= e($errors['bank_agency']) ?></div><?php endif; ?></div><div class="col-md-8"><label class="form-label">Conta</label><input type="text" class="form-control<?= $invalidClass('bank_account') ?>" name="bank_account" value="<?= e($bankAccountValue) ?>"><?php if (!empty($errors['bank_account'])): ?><div class="field-error"><?= e($errors['bank_account']) ?></div><?php endif; ?></div></div></div>
            <div class="col-md-5 conditional-section<?= $showBankDetails ? ' is-hidden' : '' ?>" id="pix-section"><label class="form-label">Chave PIX</label><input type="text" class="form-control<?= $invalidClass('pix_key') ?>" name="pix_key" value="<?= e($pixKeyValue) ?>" placeholder="CPF, e-mail, telefone ou aleatória"><?php if (!empty($errors['pix_key'])): ?><div class="field-error"><?= e($errors['pix_key']) ?></div><?php endif; ?></div>
            <div class="col-md-3"><label class="form-label">Status</label><select class="form-select" name="status"><?php foreach ($statuses as $key=>$label): ?><option value="<?= e($key) ?>" <?= selected(old('status', $admission['status'] ?? 'recebido'), $key) ?>><?= e($label) ?></option><?php endforeach; ?></select></div>
            <div class="col-12"><label class="form-label">Observações internas</label><textarea class="form-control" rows="4" name="internal_notes"><?= e(old('internal_notes', $admission['internal_notes'] ?? '')) ?></textarea></div>
        </div>
    <?php else: ?>
        <div class="section-header"><h2>7. Benefícios do colaborador</h2><p>Informe abaixo se irá utilizar vale-transporte e o tamanho do uniforme. Dados bancários e informações de admissão serão preenchidos internamente pelo RH.</p></div>
        <div class="row g-3">
            <div class="col-md-3"><label class="form-label">Irá utilizar vale transporte?</label><select class="form-select toggle-field<?= $invalidClass('transport_voucher_daily_value') ?>" name="uses_transport_voucher" data-target="#vt-section"><option value="0" <?= selected(old('uses_transport_voucher', $admission['uses_transport_voucher'] ?? 0), 0) ?>>Não</option><option value="1" <?= selected(old('uses_transport_voucher', $admission['uses_transport_voucher'] ?? 0), 1) ?>>Sim</option></select></div>
            <div class="col-md-3 conditional-section" id="vt-section"><label class="form-label">Valor diário do vale transporte</label><input type="text" class="form-control<?= $invalidClass('transport_voucher_daily_value') ?>" name="transport_voucher_daily_value" value="<?= e(old('transport_voucher_daily_value', $admission['transport_voucher_daily_value'] ?? '')) ?>" placeholder="Ex.: 12,50" inputmode="decimal"><?php if (!empty($errors['transport_voucher_daily_value'])): ?><div class="field-error"><?= e($errors['transport_voucher_daily_value']) ?></div><?php endif; ?></div><div class="col-md-3"><label class="form-label">Uniforme</label><select class="form-select" name="uniform_size"><option value="">Selecione</option><?php foreach ($config['uniform_sizes'] as $size): ?><option value="<?= e($size) ?>" <?= selected(old('uniform_size', $admission['uniform_size'] ?? ''), $size) ?>><?= e($size) ?></option><?php endforeach; ?></select></div>
        </div>
    <?php endif; ?>
</section>

<section id="academic-section" class="form-section conditional-section<?= $showAcademic ? '' : ' is-hidden' ?>">
    <div class="section-header"><h2>8. Estágio</h2><p>Esta seção é obrigatória para estagiários e também aparece quando o colaborador informa que é estudante.</p></div>
    <div class="row g-3">
        <div class="col-md-6"><label class="form-label d-block">Natureza do estágio</label><?php foreach (($config['internship_natures'] ?? []) as $value => $label): ?><div class="form-check form-check-inline"><input class="form-check-input<?= $invalidClass('academic.internship_nature') ?>" type="radio" name="academic[internship_nature]" id="internship_nature_<?= e(md5($value)) ?>" value="<?= e($value) ?>" <?= checked(old('academic.internship_nature', $academic['internship_nature'] ?? ''), $value) ?>><label class="form-check-label" for="internship_nature_<?= e(md5($value)) ?>"><?= e($label) ?></label></div><?php endforeach; ?><?php if (!empty($errors['academic.internship_nature'])): ?><div class="field-error"><?= e($errors['academic.internship_nature']) ?></div><?php endif; ?></div>
        <div class="col-md-6"><label class="form-label">Nível</label><select class="form-select<?= $invalidClass('academic.academic_level') ?>" name="academic[academic_level]"><option value="">Selecione</option><?php foreach (($config['academic_level_options'] ?? []) as $value => $label): ?><option value="<?= e($value) ?>" <?= selected(old('academic.academic_level', $academic['academic_level'] ?? ''), $value) ?>><?= e($label) ?></option><?php endforeach; ?></select><?php if (!empty($errors['academic.academic_level'])): ?><div class="field-error"><?= e($errors['academic.academic_level']) ?></div><?php endif; ?></div>
        <div class="col-md-4"><label class="form-label">Nome da instituição/faculdade</label><input type="text" class="form-control<?= $invalidClass('academic.institution_name') ?>" name="academic[institution_name]" value="<?= e(old('academic.institution_name', $academic['institution_name'] ?? '')) ?>"><?php if (!empty($errors['academic.institution_name'])): ?><div class="field-error"><?= e($errors['academic.institution_name']) ?></div><?php endif; ?></div>
        <div class="col-md-4"><label class="form-label">CNPJ da instituição/faculdade</label><input type="text" class="form-control js-cnpj<?= $invalidClass('academic.institution_cnpj') ?>" name="academic[institution_cnpj]" value="<?= e(old('academic.institution_cnpj', $academic['institution_cnpj'] ?? '')) ?>"><?php if (!empty($errors['academic.institution_cnpj'])): ?><div class="field-error"><?= e($errors['academic.institution_cnpj']) ?></div><?php endif; ?></div>
        <div class="col-md-4"><label class="form-label">Endereço da faculdade</label><input type="text" class="form-control<?= $invalidClass('academic.institution_address') ?>" name="academic[institution_address]" value="<?= e(old('academic.institution_address', $academic['institution_address'] ?? '')) ?>"><?php if (!empty($errors['academic.institution_address'])): ?><div class="field-error"><?= e($errors['academic.institution_address']) ?></div><?php endif; ?></div>
        <div class="col-md-2"><label class="form-label">Nº da faculdade</label><input type="text" class="form-control<?= $invalidClass('academic.institution_number') ?>" name="academic[institution_number]" value="<?= e(old('academic.institution_number', $academic['institution_number'] ?? '')) ?>"><?php if (!empty($errors['academic.institution_number'])): ?><div class="field-error"><?= e($errors['academic.institution_number']) ?></div><?php endif; ?></div>
        <div class="col-md-3"><label class="form-label">Bairro da faculdade</label><input type="text" class="form-control<?= $invalidClass('academic.institution_neighborhood') ?>" name="academic[institution_neighborhood]" value="<?= e(old('academic.institution_neighborhood', $academic['institution_neighborhood'] ?? '')) ?>"><?php if (!empty($errors['academic.institution_neighborhood'])): ?><div class="field-error"><?= e($errors['academic.institution_neighborhood']) ?></div><?php endif; ?></div>
        <div class="col-md-2"><label class="form-label">CEP da faculdade</label><input type="text" class="form-control js-cep<?= $invalidClass('academic.institution_zip') ?>" name="academic[institution_zip]" value="<?= e(old('academic.institution_zip', $academic['institution_zip'] ?? '')) ?>"><?php if (!empty($errors['academic.institution_zip'])): ?><div class="field-error"><?= e($errors['academic.institution_zip']) ?></div><?php endif; ?></div>
        <div class="col-md-3"><label class="form-label">Cidade da faculdade</label><input type="text" class="form-control<?= $invalidClass('academic.institution_city') ?>" name="academic[institution_city]" value="<?= e(old('academic.institution_city', $academic['institution_city'] ?? '')) ?>"><?php if (!empty($errors['academic.institution_city'])): ?><div class="field-error"><?= e($errors['academic.institution_city']) ?></div><?php endif; ?></div>
        <div class="col-md-2"><label class="form-label">Estado da faculdade</label><input type="text" class="form-control text-uppercase<?= $invalidClass('academic.institution_state') ?>" maxlength="2" name="academic[institution_state]" value="<?= e(old('academic.institution_state', $academic['institution_state'] ?? '')) ?>"><?php if (!empty($errors['academic.institution_state'])): ?><div class="field-error"><?= e($errors['academic.institution_state']) ?></div><?php endif; ?></div>
        <div class="col-md-4"><label class="form-label">Coordenador/Professor Orientador da disciplina do estágio (nome completo)</label><input type="text" class="form-control<?= $invalidClass('academic.advisor_name') ?>" name="academic[advisor_name]" value="<?= e(old('academic.advisor_name', $academic['advisor_name'] ?? '')) ?>"><?php if (!empty($errors['academic.advisor_name'])): ?><div class="field-error"><?= e($errors['academic.advisor_name']) ?></div><?php endif; ?></div>
        <div class="col-md-2"><label class="form-label">Semestre</label><input type="text" class="form-control<?= $invalidClass('academic.semester') ?>" name="academic[semester]" value="<?= e(old('academic.semester', $academic['semester'] ?? '')) ?>"><?php if (!empty($errors['academic.semester'])): ?><div class="field-error"><?= e($errors['academic.semester']) ?></div><?php endif; ?></div>
        <div class="col-md-3"><label class="form-label">Turno que estuda</label><input type="text" class="form-control<?= $invalidClass('academic.study_shift') ?>" name="academic[study_shift]" value="<?= e(old('academic.study_shift', $academic['study_shift'] ?? '')) ?>" placeholder="Ex.: Manhã, Tarde ou Noite"><?php if (!empty($errors['academic.study_shift'])): ?><div class="field-error"><?= e($errors['academic.study_shift']) ?></div><?php endif; ?></div>
        <div class="col-md-3"><label class="form-label">Nome do curso</label><input type="text" class="form-control<?= $invalidClass('academic.course_name') ?>" name="academic[course_name]" value="<?= e(old('academic.course_name', $academic['course_name'] ?? '')) ?>"><?php if (!empty($errors['academic.course_name'])): ?><div class="field-error"><?= e($errors['academic.course_name']) ?></div><?php endif; ?></div>
        <div class="col-md-2"><label class="form-label">RGM (Número da Matrícula)</label><input type="text" class="form-control<?= $invalidClass('academic.registration_number') ?>" name="academic[registration_number]" value="<?= e(old('academic.registration_number', $academic['registration_number'] ?? '')) ?>"><?php if (!empty($errors['academic.registration_number'])): ?><div class="field-error"><?= e($errors['academic.registration_number']) ?></div><?php endif; ?></div>
    </div>
</section>

<section class="form-section">
    <div class="section-header">
        <h2>9. Anexos obrigatórios</h2>
        <p>Tipos aceitos: JPG, PNG ou PDF. Máximo 5 MB.</p>
    </div>

    <div class="row g-3">
        <?php $attachmentLabels = $config['attachment_labels'] ?? []; ?>

        <?php foreach ($attachmentLabels as $field => $label): ?>
            <?php if ($field === 'dependent_birth_certificate') continue; ?>
            <?php
            $currentAttachment = null;
            if (($mode ?? 'create') === 'edit' && !empty($admission['attachments'])) {
                foreach ($admission['attachments'] as $attachment) {
                    if (($attachment['label_key'] ?? '') === $field) {
                        $currentAttachment = $attachment;
                        break;
                    }
                }
            }

            $isCurrentImage = $currentAttachment && str_starts_with((string) $currentAttachment['mime_type'], 'image/');
            ?>

            <?php
            $conditionalClass = '';
            $conditionalId = '';

            if ($field === 'cref_document') {
                $conditionalClass = $isProfessorJob ? '' : ' conditional-section is-hidden';
                $conditionalId = ' id="cref-document-section"';
            } elseif ($field === 'mei_certificate') {
                $conditionalClass = $isProfessorJob ? '' : ' conditional-section is-hidden';
                $conditionalId = ' id="mei-certificate-section"';
            } elseif ($field === 'marriage_certificate') {
                $conditionalClass = $currentMaritalStatus === 'casado' ? '' : ' conditional-section is-hidden';
                $conditionalId = ' id="marriage-certificate-section"';
            } elseif ($field === 'divorce_annotation') {
                $conditionalClass = $currentMaritalStatus === 'divorciado' ? '' : ' conditional-section is-hidden';
                $conditionalId = ' id="divorce-annotation-section"';
            } elseif ($field === 'dependent_birth_certificate') {
                $conditionalClass = $hasDependents ? '' : ' conditional-section is-hidden';
                $conditionalId = ' id="dependent-birth-certificate-section"';
            }
            ?>
            <div class="col-md-4<?= $conditionalClass ?>"<?= $conditionalId ?>>
                <label class="form-label"><?= e($label) ?></label>

                <input
                    type="file"
                    class="form-control js-file-preview<?= $invalidClass($field) ?>"
                    name="<?= e($field) ?>"
                    accept=".jpg,.jpeg,.png,.pdf"
                    data-preview-target="#preview-<?= e($field) ?>"
                    data-preview-image="#preview-image-<?= e($field) ?>"
                    data-preview-meta="#preview-meta-<?= e($field) ?>"
                >

                <?php if (!empty($errors[$field])): ?>
                    <div class="field-error"><?= e($errors[$field]) ?></div>
                <?php endif; ?>

                <div
                    id="preview-<?= e($field) ?>"
                    class="upload-preview<?= $currentAttachment ? '' : ' is-empty' ?>"
                >
                    <div class="upload-preview__media<?= $isCurrentImage ? '' : ' d-none' ?>">
                        <img
                            id="preview-image-<?= e($field) ?>"
                            class="upload-preview__image"
                            alt="<?= e($label) ?>"
                            src="<?= $isCurrentImage ? e(baseUrl('admin/admissoes/' . $admission['id'] . '/anexos/' . $currentAttachment['id'] . '/visualizar')) : '' ?>"
                        >
                    </div>

                    <div id="preview-meta-<?= e($field) ?>" class="upload-preview__meta">
                        <?php if ($currentAttachment): ?>
                            <div class="upload-preview__filename"><?= e($currentAttachment['original_name']) ?></div>

                            <?php if ($isCurrentImage): ?>
                                <div class="upload-preview__hint">Imagem atual</div>
                            <?php else: ?>
                                <div class="upload-preview__hint">Arquivo atual enviado</div>
                            <?php endif; ?>

                            <div class="mt-2">
                                <?php if ($isCurrentImage): ?>
                                    <a
                                        href="<?= e(baseUrl('admin/admissoes/' . $admission['id'] . '/anexos/' . $currentAttachment['id'] . '/visualizar')) ?>"
                                        target="_blank"
                                        class="btn btn-sm btn-outline-secondary"
                                    >
                                        Visualizar
                                    </a>
                                <?php endif; ?>

                                <a
                                    href="<?= e(baseUrl('admin/admissoes/' . $admission['id'] . '/anexos/' . $currentAttachment['id'] . '/download')) ?>"
                                    target="_blank"
                                    class="btn btn-sm btn-outline-primary"
                                >
                                    Baixar atual
                                </a>
                            </div>
                        <?php else: ?>
                            <div class="upload-preview__filename">Nenhum arquivo selecionado</div>
                            <div class="upload-preview__hint">A miniatura aparece aqui quando você escolher uma imagem.</div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
</section>
