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

<?= $this->section('content') ?>
<?php
$statusLabels = ['draft' => 'Borrador', 'signed' => 'Firmada', 'delivered' => 'Entregada'];
$signatureFields = array_values(array_filter($fields, static fn ($field) => ($field['type'] ?? '') === 'signature'));
$photos = $photos ?? [];
$sectionLabels = [
    'general' => 'Evidencia general',
    'antes' => 'Antes de la entrega',
    'durante' => 'Durante la entrega',
    'despues' => 'Después de la entrega',
];
$groupedPhotos = [];
foreach ($photos as $photo) {
    $groupedPhotos[$photo['section'] ?? 'general'][] = $photo;
}
?>
<section class="card stack-md">
    <div class="section-head">
        <div>
            <h3><?= esc($note['folio']) ?> · <?= esc($note['title']) ?></h3>
            <p><?= esc($client['nombre'] ?? '') ?> · <?= esc($template['code'] . ' · ' . $template['name']) ?></p>
        </div>
        <div class="actions-row">
            <form method="post" action="<?= site_url('delivery-notes/' . $note['id'] . '/duplicate') ?>">
                <?= csrf_field() ?>
                <button class="btn btn-secondary" type="submit">Duplicar</button>
            </form>
            <a class="btn btn-primary" href="<?= site_url('delivery-notes/' . $note['id'] . '/pdf') ?>" target="_blank">Descargar PDF</a>
        </div>
    </div>

    <form method="post" action="<?= site_url('delivery-notes/' . $note['id'] . '/update') ?>" class="stack-md">
        <?= csrf_field() ?>
        <div class="grid grid-2">
            <div>
                <label>Título</label>
                <input type="text" name="title" value="<?= esc($note['title']) ?>" required>
            </div>
            <div>
                <label>Estado</label>
                <select name="status">
                    <?php foreach ($statusLabels as $key => $label): ?>
                        <option value="<?= esc($key) ?>" <?= $note['status'] === $key ? 'selected' : '' ?>><?= esc($label) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>

        <?php foreach ($fields as $field): ?>
            <?php
            $key = (string) ($field['key'] ?? '');
            if ($key === '' || ($field['type'] ?? '') === 'signature') {
                continue;
            }
            ?>
            <div>
                <label><?= esc($field['label']) ?><?= ! empty($field['required']) ? ' *' : '' ?></label>
                <?php if (($field['type'] ?? '') === 'textarea'): ?>
                    <textarea name="field_<?= esc($key) ?>" rows="4" <?= ! empty($field['required']) ? 'required' : '' ?>><?= esc($values[$key] ?? '') ?></textarea>
                <?php else: ?>
                    <input type="<?= ($field['type'] ?? '') === 'date' ? 'date' : 'text' ?>" name="field_<?= esc($key) ?>" value="<?= esc($values[$key] ?? '') ?>" <?= ! empty($field['required']) ? 'required' : '' ?>>
                <?php endif; ?>
            </div>
        <?php endforeach; ?>

        <button class="btn btn-primary" type="submit">Guardar acta</button>
    </form>

    <?php if ($signatureFields !== []): ?>
        <div class="stack-md">
            <h4>Firmas requeridas por plantilla</h4>
            <?php foreach ($signatureFields as $field): ?>
                <?php
                $key = (string) $field['key'];
                $sig = $signatures[$key] ?? null;
                ?>
                <fieldset>
                    <legend><?= esc($field['label']) ?></legend>
                    <?= view('partials/signature_pad', [
                        'signableType' => 'delivery_note',
                        'signableId' => (int) $note['id'],
                        'role' => $key,
                        'uploadUrl' => site_url('signatures/upload'),
                        'currentName' => $sig['name'] ?? '',
                        'currentPath' => $sig['png_path'] ?? null,
                        'fieldKey' => $key,
                    ]) ?>
                </fieldset>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>

    <div class="section-head">
        <div>
            <h4>Imágenes del acta</h4>
            <p>Estas imágenes aparecerán como galería al final del PDF del acta.</p>
        </div>
    </div>

    <form method="post" action="<?= site_url('delivery-notes/' . $note['id'] . '/photos') ?>" enctype="multipart/form-data" class="stack-sm">
        <?= csrf_field() ?>
        <div class="grid grid-3">
            <div>
                <label>Sección</label>
                <select name="section">
                    <?php foreach ($sectionLabels as $key => $label): ?>
                        <option value="<?= esc($key) ?>"><?= esc($label) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div>
                <label>Descripción opcional</label>
                <input type="text" name="caption" placeholder="Ej. Entrega de planos y equipos">
            </div>
            <div>
                <label>Imágenes</label>
                <input type="file" name="photos[]" accept="image/*" multiple required>
            </div>
        </div>
        <button class="btn btn-primary" type="submit">Agregar imágenes</button>
    </form>

    <?php if ($photos === []): ?>
        <p class="muted">Aún no hay imágenes en esta acta.</p>
    <?php else: ?>
        <div class="report-gallery stack-md">
            <?php foreach ($sectionLabels as $section => $label): ?>
                <?php if (empty($groupedPhotos[$section])): continue; endif; ?>
                <div class="stack-sm">
                    <h5><?= esc($label) ?></h5>
                    <div class="gallery-grid">
                        <?php foreach ($groupedPhotos[$section] as $photo): ?>
                            <figure class="gallery-item">
                                <img src="<?= esc(site_url('delivery-notes/' . $note['id'] . '/photos/' . $photo['id'])) ?>" alt="<?= esc($photo['caption'] ?: $label) ?>">
                                <?php if (! empty($photo['caption'])): ?>
                                    <figcaption><?= esc($photo['caption']) ?></figcaption>
                                <?php endif; ?>
                                <form method="post" action="<?= site_url('delivery-notes/' . $note['id'] . '/photos/' . $photo['id'] . '/delete') ?>">
                                    <?= csrf_field() ?>
                                    <button class="link-button" type="submit">Eliminar</button>
                                </form>
                            </figure>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>

    <h4>Inspecciones asociadas</h4>
    <?php if ($inspections === []): ?>
        <p class="muted">Sin inspecciones vinculadas.</p>
    <?php else: ?>
        <ul>
            <?php foreach ($inspections as $inspection): ?>
                <li><a href="<?= site_url('inspections/' . $inspection['id']) ?>"><?= esc($inspection['folio']) ?></a> — <?= esc($inspection['sistema'] ?? '') ?></li>
            <?php endforeach; ?>
        </ul>
    <?php endif; ?>

    <p class="muted">Verificación pública: <a href="<?= site_url('verify/' . $note['verify_token']) ?>" target="_blank"><?= esc(site_url('verify/' . $note['verify_token'])) ?></a></p>
</section>
<script src="<?= base_url('assets/js/signature_pad.js') ?>"></script>
<?= $this->endSection() ?>
