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

<?= $this->section('content') ?>
<section class="card stack-md">
    <div class="section-head">
        <div>
            <h3>Plantillas de acta</h3>
            <p>Textos formales editables con campos dinámicos y firmas configurables.</p>
        </div>
        <a class="btn btn-primary" href="<?= site_url('delivery-note-templates/create') ?>">Nueva plantilla</a>
    </div>

    <div class="table-responsive">
        <table>
            <thead>
                <tr>
                    <th>Clave</th>
                    <th>Nombre</th>
                    <th>Campos</th>
                    <th>Estado</th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($templates as $template): ?>
                    <?php $fields = json_decode((string) ($template['fields_json'] ?? '[]'), true) ?: []; ?>
                    <tr>
                        <td><strong><?= esc($template['code']) ?></strong></td>
                        <td><?= esc($template['name']) ?></td>
                        <td><?= count($fields) ?></td>
                        <td><span class="badge"><?= $template['is_active'] ? 'Activa' : 'Inactiva' ?></span></td>
                        <td class="table-actions">
                            <a class="btn btn-secondary" href="<?= site_url('delivery-note-templates/' . $template['id'] . '/edit') ?>">Editar</a>
                            <?php if ((int) $template['is_active'] === 1): ?>
                                <form method="post" action="<?= site_url('delivery-note-templates/' . $template['id'] . '/delete') ?>">
                                    <?= csrf_field() ?>
                                    <button class="link-button" type="submit">Desactivar</button>
                                </form>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
                <?php if ($templates === []): ?>
                    <tr><td colspan="5" class="muted">Aún no hay plantillas de acta.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</section>
<?= $this->endSection() ?>
