<?= $this->extend('layouts/app') ?>

<?= $this->section('content') ?>
<?php
$autosaveUrl = site_url('inspections/' . $inspection['id'] . '/autosave');
$finalizeUrl = site_url('inspections/' . $inspection['id'] . '/finalize');
$duplicateUrl = site_url('inspections/' . $inspection['id'] . '/duplicate');
$attachmentUrl = site_url('inspections/' . $inspection['id'] . '/attachments');
$signatureUrl = site_url('signatures/upload');
$serverTs = $inspection['autosave_updated_at'] ?: $inspection['updated_at'];
$autosaveData = $inspection['autosave_json'] ? json_decode($inspection['autosave_json'], true) : null;
$savedItems = $autosaveData['items'] ?? [];
$savedObs = $autosaveData['observaciones'] ?? ($inspection['observaciones'] ?? '');
$savedHeader = $autosaveData['header'] ?? [];

if ($savedItems === [] && $answers !== []) {
    foreach ($answers as $itId => $a) {
        $savedItems[$itId] = [
            'value_bool' => $a['value_bool'],
            'value_text' => $a['value_text'],
            'value_number' => $a['value_number'],
            'value_json' => $a['value_json'] ? json_decode($a['value_json'], true) : null,
            'comentarios' => $a['comentarios'],
            'lecturas' => $a['lecturas'],
        ];
    }
}
?>
<section class="card stack-md inspection-form-card">
    <div class="section-head">
        <div>
            <h3>Captura · <?= esc($inspection['folio'] ?? '') ?></h3>
            <p><?= esc($template['code']) ?> · <?= esc($template['name']) ?> · <?= esc($client['nombre'] ?? '') ?></p>
        </div>
        <div class="actions-row">
            <span id="autosave-status" class="muted">Listo</span>
        </div>
    </div>

    <form id="inspection-form" data-server-ts="<?= esc((string) $serverTs) ?>" data-id="<?= (int) $inspection['id'] ?>" data-autosave-url="<?= esc($autosaveUrl) ?>" data-finalize-url="<?= esc($finalizeUrl) ?>" class="stack-md">
        <fieldset class="stack-sm">
            <legend>Datos generales</legend>
            <div class="grid grid-2">
                <div>
                    <label>Sistema</label>
                    <input type="text" data-bind="header.sistema" value="<?= esc($savedHeader['sistema'] ?? $inspection['sistema'] ?? '') ?>">
                </div>
                <div>
                    <label>Equipo</label>
                    <input type="text" data-bind="header.equipo" value="<?= esc($savedHeader['equipo'] ?? $inspection['equipo'] ?? '') ?>">
                </div>
                <div>
                    <label>Atención</label>
                    <input type="text" data-bind="header.atencion" value="<?= esc($savedHeader['atencion'] ?? $inspection['atencion'] ?? '') ?>">
                </div>
                <div>
                    <label>Servicio</label>
                    <input type="text" data-bind="header.servicio" value="<?= esc($savedHeader['servicio'] ?? $inspection['servicio'] ?? '') ?>">
                </div>
                <div>
                    <label>Contrato</label>
                    <input type="text" data-bind="header.contrato" value="<?= esc($savedHeader['contrato'] ?? $inspection['contrato'] ?? '') ?>">
                </div>
                <div>
                    <label>Fecha</label>
                    <input type="date" data-bind="header.fecha" value="<?= esc($savedHeader['fecha'] ?? $inspection['fecha'] ?? date('Y-m-d')) ?>">
                </div>
                <div>
                    <label>Periodicidad</label>
                    <input type="text" value="<?= esc(['mensual' => 'Mensual', 'semestral' => 'Semestral', 'anual' => 'Anual'][$inspection['periodicidad'] ?? 'mensual'] ?? 'Mensual') ?>" readonly>
                </div>
            </div>
        </fieldset>

        <?php if ($template['layout_mode'] === 'equipment_table'): ?>
            <?= view('inspections/equipment_table', ['template' => $template, 'savedItems' => $savedItems]) ?>
        <?php else: ?>
            <?php foreach ($template['sections'] as $section): ?>
                <fieldset class="stack-sm">
                    <legend><?= esc($section['titulo']) ?></legend>
                    <div class="inspection-items">
                        <?php foreach (($template['items_by_section'][$section['id']] ?? []) as $item): ?>
                            <?php $saved = $savedItems[$item['id']] ?? []; ?>
                            <?= view('inspections/fields/' . $item['tipo_campo'], ['item' => $item, 'saved' => $saved, 'inspection' => $inspection]) ?>
                        <?php endforeach; ?>
                    </div>
                </fieldset>
            <?php endforeach; ?>
        <?php endif; ?>

        <fieldset class="stack-sm">
            <legend>Observaciones</legend>
            <textarea data-bind="observaciones" rows="4"><?= esc($savedObs) ?></textarea>
        </fieldset>

        <fieldset class="stack-sm">
            <legend>Firma del inspector</legend>
            <?= view('partials/signature_pad', [
                'signableType' => 'inspection',
                'signableId' => (int) $inspection['id'],
                'role' => 'inspector',
                'currentName' => $signature['name'] ?? (session('auth_user')['name'] ?? ''),
                'currentPath' => $signature['png_path'] ?? null,
                'uploadUrl' => $signatureUrl,
            ]) ?>
        </fieldset>

        <div class="actions-row">
            <a class="btn btn-secondary" href="<?= site_url('inspections/' . $inspection['id']) ?>">Volver</a>
            <button type="button" class="btn btn-secondary" id="duplicate-btn">Duplicar</button>
            <button type="button" class="btn btn-primary" id="finalize-btn">Finalizar y firmar</button>
        </div>
    </form>
</section>

<script src="<?= base_url('assets/js/signature_pad.js') ?>"></script>
<script src="<?= base_url('assets/js/autosave.js') ?>"></script>
<script>
(function () {
    const finalize = document.getElementById('finalize-btn');
    const duplicate = document.getElementById('duplicate-btn');

    async function submitAfterFlush(action) {
        if (window.SimprofireAutosave) {
            await window.SimprofireAutosave.flush();
        }
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = action;
        const csrf = document.createElement('input');
        csrf.type = 'hidden';
        csrf.name = <?= json_encode(csrf_token()) ?>;
        csrf.value = <?= json_encode(csrf_hash()) ?>;
        form.appendChild(csrf);
        document.body.appendChild(form);
        form.submit();
    }

    finalize?.addEventListener('click', () => submitAfterFlush(<?= json_encode($finalizeUrl) ?>));
    duplicate?.addEventListener('click', () => submitAfterFlush(<?= json_encode($duplicateUrl) ?>));
})();
</script>
<?= $this->endSection() ?>
