<?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');
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <style>
        @page {
            margin: 34px 38px 58px 38px;
        }

        body {
            font-family: DejaVu Sans, sans-serif;
            color: #111827;
            font-size: 11px;
            line-height: 1.45;
        }

        .page-number {
            position: fixed;
            bottom: -34px;
            right: 0;
            font-size: 10px;
            color: #6b7280;
        }

        .page-number:after {
            content: counter(page) ' / ' counter(pages);
        }

        .title {
            text-align: center;
            font-size: 13px;
            font-weight: bold;
            margin: 0 0 12px;
        }

        .consent {
            text-align: justify;
            margin: 0 0 14px;
        }

        .section-title {
            font-size: 12px;
            font-weight: bold;
            margin: 14px 0 6px;
            text-transform: uppercase;
        }

        .field {
            margin: 0 0 2px;
        }

        .inline-pair {
            margin: 0 0 2px;
        }

        .divider {
            border-top: 1px solid #111827;
            margin: 10px 0 12px;
        }

        .dependent-box {
            border: 1px solid #d1d5db;
            padding: 6px 8px;
            margin: 0 0 8px;
        }

        .list {
            margin: 4px 0 0 16px;
            padding: 0;
        }

        .declaration {
            margin-top: 14px;
            text-align: justify;
        }

        .signature {
            margin-top: 18px;
            text-align: center;
        }

        .signature-line {
            margin-top: 30px;
        }

        .muted {
            color: #4b5563;
        }
    </style>
</head>
<body>
    <div class="page-number"></div>

    <div class="title">TERMO DE CONSENTIMENTO PARA TRATAMENTO DE DADOS PESSOAIS</div>

    <p class="consent">
        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="section-title">FICHA DE ADMISSÃO</div>

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

    <div class="section-title">Dependentes</div>
    <?php if (empty($dependents)): ?>
        <p class="field">Nenhum dependente declarado.</p>
    <?php else: ?>
        <?php foreach ($dependents as $index => $dependent): ?>
            <div class="dependent-box">
                <p class="field"><strong>Nome do Dependente <?= (int) $index + 1 ?>:</strong> <?= e($dependent['full_name']) ?></p>
                <p class="field"><strong>Data de Nascimento:</strong> <?= e($rawDate($dependent['birth_date'])) ?></p>
                <p class="field"><strong>CPF:</strong> <?= e($maskedCpf($dependent['cpf'])) ?></p>
                <p class="field"><strong>Cidade de Nascimento:</strong> <?= e($dependent['birth_city']) ?></p>
                <p class="field"><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="section-title">Dados de Estágio</div>
    <?php if ($academic): ?>
        <p class="field"><strong>Natureza do estágio:</strong> <?= e($academic['internship_nature']) ?></p>
        <p class="field"><strong>Nível:</strong> <?= e($academic['academic_level']) ?></p>
        <p class="field"><strong>Instituição:</strong> <?= e($academic['institution_name']) ?></p>
        <p class="field"><strong>CNPJ da Instituição de Ensino:</strong> <?= e($academic['institution_cnpj']) ?></p>
        <p class="field"><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 class="field"><strong>Coordenador/Professor orientador:</strong> <?= e($academic['advisor_name']) ?></p>
        <p class="field"><strong>Semestre:</strong> <?= e($academic['semester']) ?></p>
        <p class="field"><strong>Turno que estuda:</strong> <?= e($academic['study_shift'] ?? '-') ?></p>
        <p class="field"><strong>Curso:</strong> <?= e($academic['course_name']) ?></p>
        <p class="field"><strong>RGM / Matrícula:</strong> <?= e($academic['registration_number']) ?></p>
    <?php else: ?>
        <p class="field">Não se aplica.</p>
    <?php endif; ?>

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

    <div class="section-title">Dados bancários</div>
    <p class="field"><strong>Função:</strong> <?= e($admission['employment_function'] ?: $admission['job_title']) ?></p>
    <p class="field"><strong>Forma de recebimento:</strong> <?= e($bankPaymentMethod === 'pix' ? 'PIX' : 'Agência / Conta') ?></p>
    <?php if ($bankPaymentMethod === 'pix'): ?>
        <p class="field"><strong>Chave PIX:</strong> <?= e($displayPixKey) ?></p>
    <?php else: ?>
        <p class="field"><strong>Dados bancários:</strong> ag <?= e($displayBankAgency) ?> cc <?= e($displayBankAccount) ?></p>
    <?php endif; ?>
    <p class="field"><strong>Transporte:</strong> <?= e($markOption((int) $admission['uses_transport_voucher'] === 1, 'Sim')) ?> <?= e($markOption((int) $admission['uses_transport_voucher'] !== 1, 'Não')) ?></p>
    <p class="field"><strong>Valor VT:</strong> <?= e(formatMoney($admission['transport_voucher_daily_value'])) ?></p>
    <p class="field"><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="section-title">Documentos necessários</div>
    <ul class="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>
        <?php if (\App\Support\AdmissionForm::isStudentAdmission($admission)): ?>
            <li>Declaração de matrícula</li>
        <?php endif; ?>
        <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="section-title">Anexos enviados</div>
    <ul class="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="declaration">
        Assumo inteira responsabilidade pelas informações aqui prestadas, e consentidas para tratamentos.
    </p>

    <div class="signature">
        ______________________, <?= e($today->format('d')) ?> de <?= e($today->format('m')) ?> de <?= e($today->format('Y')) ?>.
        <div class="signature-line">______________________________________________</div>
        <div>Assinatura do Funcionário</div>
    </div>
</body>
</html>
