<?php
$attachmentsByKey = [];
$dependentCertificateAttachments = [];
foreach ($admission['attachments'] as $attachment) {
    $labelKey = (string) $attachment['label_key'];
    if (preg_match('/^dependent_birth_certificate_(\d+)$/', $labelKey, $matches)) {
        $dependentCertificateAttachments[(int) $matches[1]] = $attachment;
        continue;
    }
    $attachmentsByKey[$labelKey] = $attachment;
}
ksort($dependentCertificateAttachments);

$rawDate = static function (?string $date): string {
    if (!$date || $date === '0000-00-00') {
        return '-';
    }

    try {
        return (new DateTimeImmutable($date))->format('Y-m-d');
    } catch (Throwable) {
        return (string) $date;
    }
};

$maskedPhone = static function (?string $phone): string {
    $digits = preg_replace('/\D/', '', (string) $phone);

    if (strlen($digits) === 11) {
        return sprintf('(%s) %s-%s', substr($digits, 0, 2), substr($digits, 2, 5), substr($digits, 7));
    }

    if (strlen($digits) === 10) {
        return sprintf('(%s) %s-%s', substr($digits, 0, 2), substr($digits, 2, 4), substr($digits, 6));
    }

    return (string) $phone ?: '-';
};

$maskedCpf = static function (?string $cpf): string {
    $digits = preg_replace('/\D/', '', (string) $cpf);
    if (strlen($digits) !== 11) {
        return (string) $cpf ?: '-';
    }

    return sprintf('%s.%s.%s-%s', substr($digits, 0, 3), substr($digits, 3, 3), substr($digits, 6, 3), substr($digits, 9, 2));
};

$maskedCep = static function (?string $cep): string {
    $digits = preg_replace('/\D/', '', (string) $cep);
    if (strlen($digits) !== 8) {
        return (string) $cep ?: '-';
    }

    return sprintf('%s-%s', substr($digits, 0, 5), substr($digits, 5, 3));
};

$markOption = static function (bool $condition, string $label): string {
    return ($condition ? '(X) ' : '( ) ') . $label;
};

$salaryTypeMark = static function (?string $current, string $expected, string $label): string {
    return (($current ?? '') === $expected ? '(X) ' : '( ) ') . $label;
};

$bankPaymentMethod = (($admission['bank_payment_method'] ?? null) === 'pix' || (strtoupper(trim((string) ($admission['bank_agency'] ?? ''))) === 'PIX' && !empty($admission['bank_account'] ?? ''))) ? 'pix' : 'bank';
$displayPixKey = $bankPaymentMethod === 'pix' ? (($admission['pix_key'] ?? '') !== '' ? $admission['pix_key'] : ($admission['bank_account'] ?? '-')) : '-';
$displayBankAgency = $bankPaymentMethod === 'bank' ? ($admission['bank_agency'] ?: '-') : '-';
$displayBankAccount = $bankPaymentMethod === 'bank' ? ($admission['bank_account'] ?: '-') : '-';

$academic = $admission['academic'] ?? null;
$dependents = $admission['dependents'] ?? [];
$today = new DateTimeImmutable('now');
?>
<div class="print-document print-document--legal">
    <div class="print-legal-title">TERMO DE CONSENTIMENTO PARA TRATAMENTO DE DADOS PESSOAIS</div>

    <p class="print-legal-paragraph">
        Este termo de consentimento foi elaborado em conformidade com a Lei Geral de Proteção de Dados (LGPD).
        Consoante ao artigo 5º, inciso XII, da Lei 13.709, este documento viabiliza a manifestação livre,
        informada e inequívoca, pela qual o titular <strong><?= e($admission['full_name']) ?></strong>
        concorda com o tratamento de seus dados pessoais e dos dados do menor sob os seus cuidados,
        para a finalidade de contratação e admissão.
    </p>

    <div class="print-legal-section-title">FICHA DE ADMISSÃO</div>

    <p><strong>Nome do Funcionário:</strong> <?= e($admission['full_name']) ?></p>
    <p><strong>Tel:</strong> <?= e($maskedPhone($admission['phone'])) ?></p>
    <p><strong>Email:</strong> <?= e($admission['personal_email']) ?></p>
    <p><strong>Nome da Mãe:</strong> <?= e($admission['mother_name']) ?></p>
    <p><strong>Pai:</strong> <?= e($admission['father_name'] ?: '-') ?></p>
    <p><strong>Data Nasc:</strong> <?= e($rawDate($admission['birth_date'])) ?></p>
    <p><strong>Raça/Cor:</strong> <?= e($config['races'][$admission['race']] ?? $admission['race']) ?></p>
    <p><strong>Estado Civil:</strong> <?= e($config['marital_statuses'][$admission['marital_status']] ?? $admission['marital_status']) ?></p>
    <p><strong>Nome Cônjuge:</strong> -</p>
    <p><strong>Endereço:</strong> <?= e($admission['address_line']) ?>, <?= e($admission['address_number']) ?></p>
    <p><strong>Complemento:</strong> <?= e($admission['address_extra'] ?: '-') ?></p>
    <p><strong>CEP:</strong> <?= e($maskedCep($admission['zip_code'])) ?></p>
    <p><strong>Bairro:</strong> <?= e($admission['neighborhood']) ?></p>
    <p><strong>Cidade:</strong> <?= e($admission['city']) ?></p>
    <p><strong>Estado:</strong> <?= e($admission['state']) ?></p>
    <p><strong>Escolaridade:</strong> <?= e($config['education_levels'][$admission['education_level']] ?? $admission['education_level']) ?></p>
    <p><strong>Estudante:</strong> <?= e($markOption((int) $admission['is_student'] === 1, 'Sim')) ?> <?= e($markOption((int) $admission['is_student'] !== 1, 'Não')) ?></p>
    <p><strong>CPF:</strong> <?= e($maskedCpf($admission['cpf'])) ?></p>
    <p><strong>RG:</strong> <?= e($admission['rg_number']) ?></p>
    <p><strong>Órgão Expedidor:</strong> <?= e($admission['rg_issuer']) ?></p>
    <p><strong>Estado emissor:</strong> <?= e($admission['birth_state']) ?></p>
    <p><strong>Data emissão:</strong> <?= e($rawDate($admission['rg_issue_date'])) ?></p>
    <p><strong>Nacionalidade:</strong> <?= e($admission['nationality']) ?></p>
    <p><strong>Naturalidade:</strong> <?= e($admission['birth_city']) ?></p>
    <p><strong>Estado:</strong> <?= e($admission['birth_state']) ?></p>
    <p><strong>PIS:</strong> <?= e($admission['pis_number']) ?></p>
    <p><strong>Data emissão PIS:</strong> <?= e($rawDate($admission['pis_issue_date'])) ?></p>

    <div class="print-legal-section-title">Dependentes</div>
    <?php if (empty($dependents)): ?>
        <p>Nenhum dependente declarado.</p>
    <?php else: ?>
        <?php foreach ($dependents as $index => $dependent): ?>
            <div class="print-legal-box">
                <p><strong>Nome do Dependente <?= (int) $index + 1 ?>:</strong> <?= e($dependent['full_name']) ?></p>
                <p><strong>Data de Nascimento:</strong> <?= e($rawDate($dependent['birth_date'])) ?></p>
                <p><strong>CPF:</strong> <?= e($maskedCpf($dependent['cpf'])) ?></p>
                <p><strong>Cidade de Nascimento:</strong> <?= e($dependent['birth_city']) ?></p>
                <p><strong>Possui deficiência/invalidez:</strong> <?= e($markOption((int) $dependent['has_disability'] === 1, 'Sim')) ?> <?= e($markOption((int) $dependent['has_disability'] !== 1, 'Não')) ?></p>
            </div>
        <?php endforeach; ?>
    <?php endif; ?>

    <div class="print-legal-section-title">Dados de Estágio</div>
    <?php if ($academic): ?>
        <p><strong>Natureza do estágio:</strong> <?= e($academic['internship_nature']) ?></p>
        <p><strong>Nível:</strong> <?= e($academic['academic_level']) ?></p>
        <p><strong>Instituição:</strong> <?= e($academic['institution_name']) ?></p>
        <p><strong>CNPJ da Instituição de Ensino:</strong> <?= e($academic['institution_cnpj']) ?></p>
        <p><strong>Endereço Instituição de Ensino:</strong>
            <?= e($academic['institution_address']) ?>, <?= e($academic['institution_number']) ?> -
            <?= e($academic['institution_neighborhood']) ?> - <?= e($maskedCep($academic['institution_zip'])) ?> -
            <?= e($academic['institution_city']) ?>/<?= e($academic['institution_state']) ?>
        </p>
        <p><strong>Coordenador/Professor orientador:</strong> <?= e($academic['advisor_name']) ?></p>
        <p><strong>Semestre:</strong> <?= e($academic['semester']) ?></p>
        <p><strong>Turno que estuda:</strong> <?= e($academic['study_shift'] ?? '-') ?></p>
        <p><strong>Curso:</strong> <?= e($academic['course_name']) ?></p>
        <p><strong>RGM / Matrícula:</strong> <?= e($academic['registration_number']) ?></p>
    <?php else: ?>
        <p>Não se aplica.</p>
    <?php endif; ?>

    <div class="print-legal-section-title">Dados de Admissão</div>
    <p><strong>Data de Admissão:</strong> <?= e($rawDate($admission['admission_date'] ?? null)) ?></p>
    <p><strong>Data de Demissão:</strong> <?= e($rawDate($admission['dismissal_date'] ?? null)) ?></p>
    <p><strong>Carga Horária:</strong> <?= e($admission['workload_hours'] ?: '-') ?></p>
    <p><strong>Salário:</strong> <?= e(formatMoney($admission['salary_amount'] ?? null)) ?></p>

    <div class="print-legal-section-title">Dados bancários</div>
    <p><strong>Função:</strong> <?= e($admission['employment_function'] ?: $admission['job_title']) ?></p>
    <p><strong>Forma de recebimento:</strong> <?= e($bankPaymentMethod === 'pix' ? 'PIX' : 'Agência / Conta') ?></p>
    <?php if ($bankPaymentMethod === 'pix'): ?>
        <p><strong>Chave PIX:</strong> <?= e($displayPixKey) ?></p>
    <?php else: ?>
        <p><strong>Dados bancários:</strong> ag <?= e($displayBankAgency) ?> cc <?= e($displayBankAccount) ?></p>
    <?php endif; ?>
    <p><strong>Transporte:</strong> <?= e($markOption((int) $admission['uses_transport_voucher'] === 1, 'Sim')) ?> <?= e($markOption((int) $admission['uses_transport_voucher'] !== 1, 'Não')) ?></p>
    <p><strong>Valor VT:</strong> <?= e(formatMoney($admission['transport_voucher_daily_value'])) ?></p>
    <p><strong>Tipo de salário:</strong> <?= e($salaryTypeMark($admission['salary_type'] ?? null, 'mensal', 'mensal')) ?> <?= e($salaryTypeMark($admission['salary_type'] ?? null, 'semanal', 'semanal')) ?> <?= e($salaryTypeMark($admission['salary_type'] ?? null, 'quinzenal', 'quinzenal')) ?></p>

    <div class="print-legal-section-title">Documentos necessários</div>
    <ul class="print-list">
        <li>Carteira de Trabalho (Cópia CTPS Digital)</li>
        <li>Uma Foto 3x4</li>
        <li>Cópia certidão nascimento ou Casamento</li>
        <li>Cópia Comprovante de Residência</li>
        <li>Cópia Comprovante de escolaridade</li>
        <li>Cópia certidão nascimento filhos menores de 14 anos e CPF dos filhos</li>
        <li>Exame médico Admissional</li>
        <li>Cópia RG, CPF e Título Eleitoral</li>
        <li>Cópia PIS</li>
        <li>Cópia Reservista</li>
        <li>Número conta bancária</li>
    </ul>

    <div class="print-legal-section-title">Anexos enviados</div>
    <ul class="print-list">
        <?php foreach ($config['attachment_labels'] as $key => $label): ?>
            <?php if ($key === 'dependent_birth_certificate') continue; ?>
            <li><strong><?= e($label) ?>:</strong> <?= e($attachmentsByKey[$key]['original_name'] ?? 'Não enviado') ?></li>
        <?php endforeach; ?>
        <?php if (!empty($dependentCertificateAttachments)): ?>
            <?php foreach ($dependentCertificateAttachments as $index => $attachment): ?>
                <li><strong>Certidão de nascimento do dependente <?= (int) $index + 1 ?>:</strong> <?= e($attachment['original_name']) ?></li>
            <?php endforeach; ?>
        <?php elseif (!empty($attachmentsByKey['dependent_birth_certificate'])): ?>
            <li><strong>Certidão de nascimento do dependente:</strong> <?= e($attachmentsByKey['dependent_birth_certificate']['original_name']) ?></li>
        <?php endif; ?>
    </ul>

    <p class="print-legal-paragraph print-legal-declaration">
        Assumo inteira responsabilidade pelas informações aqui prestadas, e consentidas para tratamentos.
    </p>

    <div class="print-legal-signature">
        ______________________, <?= e($today->format('d')) ?> de <?= e($today->format('m')) ?> de <?= e($today->format('Y')) ?>.<br><br>
        ______________________________________________<br>
        Assinatura do Funcionário
    </div>
</div>
<script>window.onload = function(){ window.print(); };</script>
