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

<?= $this->section('content') ?>
<?php
$template = $template ?? null;
$fields = $fields ?? [];
?>
<section class="card stack-md">
    <div class="section-head">
        <div>
            <h3><?= esc($title) ?></h3>
            <p>Usa variables como <code>{{cliente}}</code>, <code>{{fecha_entrega}}</code> o <code>{{trabajos_realizados}}</code> dentro del texto.</p>
        </div>
        <a class="btn btn-secondary" href="<?= site_url('delivery-note-templates') ?>">Volver</a>
    </div>

    <form method="post" action="<?= esc($action) ?>" id="delivery-template-form" class="stack-md">
        <?= csrf_field() ?>
        <div class="grid grid-3">
            <div>
                <label>Clave</label>
                <input type="text" name="code" value="<?= esc(old('code', $template['code'] ?? 'SIM14')) ?>" required>
            </div>
            <div>
                <label>Nombre</label>
                <input type="text" name="name" value="<?= esc(old('name', $template['name'] ?? 'Acta de entrega')) ?>" required>
            </div>
            <div>
                <label>Estado</label>
                <select name="is_active">
                    <option value="1" <?= (int) old('is_active', $template['is_active'] ?? 1) === 1 ? 'selected' : '' ?>>Activa</option>
                    <option value="0" <?= (int) old('is_active', $template['is_active'] ?? 1) === 0 ? 'selected' : '' ?>>Inactiva</option>
                </select>
            </div>
        </div>

        <div>
            <label>Texto del acta</label>
            <div class="wysiwyg-toolbar" aria-label="Herramientas de texto">
                <button type="button" data-command="bold"><strong>B</strong></button>
                <button type="button" data-command="italic"><em>I</em></button>
                <button type="button" data-command="underline"><u>U</u></button>
                <button type="button" data-command="insertUnorderedList">Lista</button>
            </div>
            <div id="body-editor" class="wysiwyg-editor" contenteditable="true"><?= old('body_html', $template['body_html'] ?? '<h3>Acta de entrega-recepción</h3><p>En {{ciudad}}, a {{fecha_entrega}}, se hace constar la entrega de los trabajos realizados para {{cliente}}.</p>') ?></div>
            <textarea name="body_html" id="body-html" hidden></textarea>
        </div>

        <div class="section-head">
            <div>
                <h4>Campos de captura</h4>
                <p>El tipo <strong>Firma</strong> crea automáticamente un canvas para firmar al emitir el acta.</p>
            </div>
            <button class="btn btn-secondary" type="button" id="add-field">Agregar campo</button>
        </div>
        <div id="template-fields" class="template-fields"></div>
        <textarea name="fields_json" id="fields-json" hidden><?= esc(json_encode($fields, JSON_UNESCAPED_UNICODE)) ?></textarea>

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

<script>
(() => {
    const form = document.getElementById('delivery-template-form');
    const editor = document.getElementById('body-editor');
    const body = document.getElementById('body-html');
    const fieldsWrap = document.getElementById('template-fields');
    const fieldsJson = document.getElementById('fields-json');
    const addButton = document.getElementById('add-field');
    let fields = JSON.parse(fieldsJson.value || '[]');

    const types = [
        ['text', 'Texto corto'],
        ['textarea', 'Texto largo'],
        ['date', 'Fecha'],
        ['signature', 'Firma'],
    ];

    const render = () => {
        fieldsWrap.innerHTML = '';
        if (fields.length === 0) {
            fieldsWrap.innerHTML = '<p class="muted">Agrega los campos que debe capturar el acta.</p>';
        }
        fields.forEach((field, index) => {
            const row = document.createElement('div');
            row.className = 'template-field-row';
            row.innerHTML = `
                <input type="text" data-prop="key" value="${escapeHtml(field.key || '')}" placeholder="clave_variable">
                <input type="text" data-prop="label" value="${escapeHtml(field.label || '')}" placeholder="Etiqueta visible">
                <select data-prop="type">${types.map(([value, label]) => `<option value="${value}" ${field.type === value ? 'selected' : ''}>${label}</option>`).join('')}</select>
                <label class="check-inline"><input type="checkbox" data-prop="required" ${field.required ? 'checked' : ''}> Obligatorio</label>
                <button type="button" class="link-button" data-remove="${index}">Quitar</button>
            `;
            fieldsWrap.appendChild(row);
        });
    };

    const sync = () => {
        const rows = [...fieldsWrap.querySelectorAll('.template-field-row')];
        fields = rows.map((row) => {
            const out = {};
            row.querySelectorAll('[data-prop]').forEach((input) => {
                const prop = input.dataset.prop;
                out[prop] = input.type === 'checkbox' ? input.checked : input.value.trim();
            });
            return out;
        });
        fieldsJson.value = JSON.stringify(fields);
    };

    function escapeHtml(value) {
        return String(value).replace(/[&<>"']/g, (c) => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'}[c]));
    }

    document.querySelectorAll('.wysiwyg-toolbar [data-command]').forEach((button) => {
        button.addEventListener('click', () => {
            document.execCommand(button.dataset.command, false, null);
            editor.focus();
        });
    });

    addButton.addEventListener('click', () => {
        sync();
        fields.push({key: '', label: '', type: 'text', required: false});
        render();
    });

    fieldsWrap.addEventListener('input', sync);
    fieldsWrap.addEventListener('change', sync);
    fieldsWrap.addEventListener('click', (event) => {
        const remove = event.target.closest('[data-remove]');
        if (!remove) return;
        sync();
        fields.splice(Number(remove.dataset.remove), 1);
        render();
        sync();
    });

    form.addEventListener('submit', () => {
        sync();
        body.value = editor.innerHTML;
    });

    render();
})();
</script>
<?= $this->endSection() ?>
