<?php
$errors = $errors ?? [];
$error = $error ?? null;
$success = $success ?? null;
$documentUploadItems = $documentUploadItems ?? [];
$documentAccessToken = (string) ($documentAccessToken ?? '');
$maxUploadFileBytes = (int) ($maxUploadFileBytes ?? \Core\RequestLimits::uploadMaxFileBytes());
$maxUploadFileLabel = (string) ($maxUploadFileLabel ?? \Core\RequestLimits::uploadMaxFileLabel());
$postMaxBytes = (int) ($postMaxBytes ?? \Core\RequestLimits::postMaxBytes());
$postMaxLabel = (string) ($postMaxLabel ?? \Core\RequestLimits::postMaxLabel());
$formTimeoutSeconds = (int) ($formTimeoutSeconds ?? \Core\RequestLimits::formTimeoutSeconds());
$formStartedAt = time();
$uploadedCount = 0;
foreach ($documentUploadItems as $item) {
    if (!empty($item['attachment'])) {
        $uploadedCount++;
    }
}
$totalCount = count($documentUploadItems);
?>
<div class="row justify-content-center">
    <div class="col-12 col-xl-10">
        <div class="hero-card mb-4">
            <div class="hero-card__content">
                <div>
                    <span class="badge text-bg-primary mb-3">Etapa 2 de 3</span>
                    <h1 class="display-6 fw-bold mb-2">Envie os documentos, um por vez</h1>
                    <p class="lead text-muted mb-0">A ficha já foi salva. Agora cada documento sobe em um envio separado. Isso reduz o peso total e evita estourar o PHP quando o arquivo veio direto da câmera.</p>
                </div>
                <div class="hero-card__aside">
                    <div class="hero-stat"><span>Colaborador</span><strong><?= e((string) ($admission['full_name'] ?? '-')) ?></strong></div>
                    <div class="hero-stat"><span>Progresso</span><strong><?= e((string) $uploadedCount) ?>/<?= e((string) $totalCount) ?></strong></div>
                    <div class="hero-stat"><span>Limite por arquivo</span><strong><?= e($maxUploadFileLabel) ?></strong></div>
                </div>
            </div>
        </div>

        <?php if (!empty($success)): ?>
            <div class="alert alert-success shadow-sm form-alert">
                <strong><?= e($success) ?></strong>
            </div>
        <?php endif; ?>

        <?php if (!empty($errors) || !empty($error)): ?>
            <div class="alert alert-danger shadow-sm form-alert">
                <strong><?= e($error ?? 'Revise os documentos pendentes e tente novamente.') ?></strong>
                <ul class="form-alert__list mb-0 mt-2">
                    <?php foreach ($errors as $message): ?>
                        <li><?= e($message) ?></li>
                    <?php endforeach; ?>
                </ul>
            </div>
        <?php endif; ?>

        <div class="card shadow-sm border-0 mb-4">
            <div class="card-body p-3 p-lg-4">
                <div class="row g-3">
                    <?php foreach ($documentUploadItems as $item): ?>
                        <?php
                        $labelKey = (string) ($item['label_key'] ?? '');
                        $label = (string) ($item['label'] ?? $labelKey);
                        $hint = (string) ($item['hint'] ?? '');
                        $accept = (string) ($item['accept'] ?? '.pdf,.jpg,.jpeg,.png');
                        $attachment = is_array($item['attachment'] ?? null) ? $item['attachment'] : null;
                        $hasAttachment = $attachment !== null;
                        $fieldError = $errors[$labelKey] ?? null;
                        ?>
                        <div class="col-12 col-lg-6">
                            <div class="border rounded-4 p-3 h-100 d-flex flex-column gap-3">
                                <div class="d-flex justify-content-between align-items-start gap-3">
                                    <div>
                                        <h2 class="h6 mb-1"><?= e($label) ?></h2>
                                        <div class="text-muted small"><?= e($hint) ?></div>
                                    </div>
                                    <span class="badge <?= $hasAttachment ? 'text-bg-success' : 'text-bg-secondary' ?>"><?= $hasAttachment ? 'Enviado' : 'Pendente' ?></span>
                                </div>

                                <form
                                    method="post"
                                    action="<?= e(baseUrl('admissoes/documentos/enviar')) ?>"
                                    enctype="multipart/form-data"
                                    novalidate
                                    autocomplete="off"
                                    data-upload-guard="true"
                                    data-max-file-size-bytes="<?= e((string) $maxUploadFileBytes) ?>"
                                    data-max-file-size-label="<?= e($maxUploadFileLabel) ?>"
                                    data-post-max-bytes="<?= e((string) $postMaxBytes) ?>"
                                    data-post-max-label="<?= e($postMaxLabel) ?>"
                                    data-form-time-limit-seconds="<?= e((string) $formTimeoutSeconds) ?>"
                                    data-timeout-scope="documents-step"
                                >
                                    <?= csrf_field() ?>
                                    <input type="hidden" name="MAX_FILE_SIZE" value="<?= e((string) $maxUploadFileBytes) ?>">
                                    <input type="hidden" name="form_started_at" value="<?= e((string) $formStartedAt) ?>">
                                    <input type="hidden" name="admission_id" value="<?= e((string) ($admission['id'] ?? '')) ?>">
                                    <input type="hidden" name="document_access_token" value="<?= e($documentAccessToken) ?>">
                                    <input type="hidden" name="label_key" value="<?= e($labelKey) ?>">

                                    <label class="form-label">Arquivo</label>
                                    <input
                                        type="file"
                                        class="form-control js-file-preview<?= $fieldError ? ' is-invalid' : '' ?>"
                                        name="attachment_file"
                                        accept="<?= e($accept) ?>"
                                        data-auto-convert-doc-to-pdf="true"
                                        data-preview-target="#preview-<?= e($labelKey) ?>"
                                        data-preview-image="#preview-image-<?= e($labelKey) ?>"
                                        data-preview-meta="#preview-meta-<?= e($labelKey) ?>"
                                    >
                                    <?php if ($fieldError): ?>
                                        <div class="field-error mt-1"><?= e((string) $fieldError) ?></div>
                                    <?php endif; ?>

                                    <div id="preview-<?= e($labelKey) ?>" class="upload-preview<?= $hasAttachment ? '' : ' is-empty' ?> mt-3">
                                        <div class="upload-preview__media d-none">
                                            <img id="preview-image-<?= e($labelKey) ?>" class="upload-preview__image" alt="<?= e($label) ?>" src="">
                                        </div>
                                        <div id="preview-meta-<?= e($labelKey) ?>" class="upload-preview__meta">
                                            <?php if ($hasAttachment): ?>
                                                <div class="upload-preview__filename"><?= e((string) ($attachment['original_name'] ?? 'Arquivo enviado')) ?></div>
                                                <div class="upload-preview__size">Tamanho: <?= e(formatBytes((int) ($attachment['size_bytes'] ?? 0))) ?></div>
                                                <div class="upload-preview__hint">Arquivo salvo para esta ficha. Se você enviar outro, ele substitui o atual.</div>
                                            <?php else: ?>
                                                <div class="upload-preview__filename">Nenhum arquivo selecionado</div>
                                                <div class="upload-preview__hint">Selecione PDF, JPG ou PNG. Se vier imagem, ela será convertida para PDF antes do envio.</div>
                                            <?php endif; ?>
                                        </div>
                                    </div>

                                    <div class="d-flex justify-content-end mt-3">
                                        <button type="submit" class="btn btn-outline-primary">Enviar este documento</button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>

                <div class="form-tips form-tips--limits mt-4 mb-4">
                    <div><strong>Limite por arquivo:</strong> <?= e($maxUploadFileLabel) ?></div>
                    <div><strong>Limite total por envio:</strong> <?= e($postMaxLabel) ?></div>
                    <div><strong>Cada documento sobe sozinho:</strong> isso evita juntar tudo em um POST gigante</div>
                </div>

                <form method="post" action="<?= e(baseUrl('admissoes/documentos/concluir')) ?>" class="d-flex flex-column flex-md-row gap-3 justify-content-end" data-form-time-limit-seconds="<?= e((string) $formTimeoutSeconds) ?>" data-timeout-scope="documents-step">
                    <?= csrf_field() ?>
                    <input type="hidden" name="form_started_at" value="<?= e((string) $formStartedAt) ?>">
                    <input type="hidden" name="admission_id" value="<?= e((string) ($admission['id'] ?? '')) ?>">
                    <input type="hidden" name="document_access_token" value="<?= e($documentAccessToken) ?>">
                    <a href="<?= e(baseUrl('')) ?>" class="btn btn-outline-secondary px-4">Voltar ao início</a>
                    <button type="submit" class="btn btn-primary px-4">Concluir documentos e ir para foto</button>
                </form>
            </div>
        </div>
    </div>
</div>
