<?php
// librerias/FormBuilderRender.php
class FormBuilderRender {
    private static $jsPrinted = false;

    public static function render($config, $data, $context = 'Default') {
        $db = $config['db']; $table = $config['table'];
        $colJson = $config['col_json']; $colPk = $config['col_pk'];

        if (empty($data)) { echo '<div class="alert alert-light">Sin datos.</div>'; return; }

        foreach ($data as $row) {
            $id = $row[$colPk];
            $jsonArray = json_decode($row[$colJson] ?? '[]', true);
            if (!is_array($jsonArray)) $jsonArray = [];
            
            $uniqueFormId = "form-wiz-{$context}-{$id}";
            self::dibujarFormulario($id, $jsonArray, $uniqueFormId, $config);
        }

        if (!self::$jsPrinted) { self::injectJS(); self::$jsPrinted = true; }
    }

    private static function dibujarFormulario($id, $jsonArray, $formId, $config) {
        $jsParams = sprintf("'%s', '%s', '%s', '%s', '%s', '%s'", $id, $config['db'], $config['table'], $config['col_json'], $config['col_pk'], $formId);
        ?>
        <form id="<?php echo $formId; ?>" onsubmit="return false;" autocomplete="off" style="max-width: 100%;">
            <?php if (empty($jsonArray)): ?>
                <div class="text-center text-muted mt-5">Configuración vacía.</div>
            <?php else: ?>
                <div class="row">
                    <?php foreach ($jsonArray as $field) { echo self::generarInput($field); } ?>
                </div>
                
                <div class="mt-5 pt-3 border-top text-right sticky-bottom bg-white pb-2">
                    <button type="button" class="btn btn-primary btn-lg shadow-sm" style="min-width: 150px;" onclick="FormBuilderJS.guardar(this, <?php echo $jsParams; ?>)">
                        <i class="feather icon-save mr-2"></i> Guardar
                    </button>
                </div>
            <?php endif; ?>
        </form>
        <?php
    }

    private static function generarInput($field) {
        // ... (Misma lógica de inputs anterior) ...
        // TIP DE DISEÑO: Usar col-lg para pantallas grandes
        $col = $field['col'] ?? '12';
        $type = $field['type'] ?? 'text';
        $label = $field['label'] ?? '';
        $required = !empty($field['required']) ? 'required' : '';
        $value = $field['value'] ?? '';
        $schema = htmlspecialchars(json_encode($field), ENT_QUOTES, 'UTF-8');
        
        // Estilo de input minimalista y alto
        $inputClass = "form-control bg-light border-0";
        $style = "height: 50px; border-radius: 6px;"; 

        $html = "";
        
        switch ($type) {
            case 'header':
                return "<div class='col-12 mt-4 mb-3'><h5 class='text-primary'>$label</h5><input type='hidden' class='input-dinamico' data-schema='$schema' value='header'></div>";
            
            case 'select':
                $opts = explode(',', $field['options'] ?? '');
                $optHtml = "<option value=''>Seleccionar...</option>";
                foreach($opts as $o) { $o=trim($o); $sel=($o==$value)?'selected':''; $optHtml.="<option value='$o' $sel>$o</option>"; }
                $html = "<select class='$inputClass' style='$style' data-schema='$schema' $required>$optHtml</select>";
                break;
            
            case 'textarea':
                 $html = "<textarea class='$inputClass' rows='4' style='border-radius: 6px; padding: 15px;' data-schema='$schema' $required>$value</textarea>";
                 break;

            case 'checkbox':
                 $chk = ($value == 'true' || $value === true) ? 'checked' : '';
                 $html = "<div class='mt-4 d-flex align-items-center p-3 bg-light rounded'><input type='checkbox' class='input-dinamico mr-3' style='transform: scale(1.5);' data-schema='$schema' $chk><span class='font-weight-bold text-dark'>$label</span></div>";
                 break;

            default:
                $html = "<input type='$type' class='$inputClass' style='$style' value='$value' data-schema='$schema' $required>";
        }

        return "<div class='col-md-$col mb-4'><label class='font-weight-bold text-muted small text-uppercase ml-1'>$label</label>$html</div>";
    }

    private static function injectJS() {
        // (El mismo JS de Guardar que ya funciona perfecto)
        ?>
        <script>
        const FormBuilderJS = {
            guardar: function(btn, id, db, table, colJson, colPk, formId) {
                let originalText = btn.innerHTML;
                btn.disabled = true; btn.innerHTML = 'Guardando...';
                
                const form = document.getElementById(formId);
                const inputs = form.querySelectorAll('.input-dinamico');
                let newJson = [];

                inputs.forEach(inp => {
                    let s = inp.getAttribute('data-schema'); if(!s) return;
                    let o = JSON.parse(s);
                    if (o.type === 'checkbox') o.value = inp.checked;
                    else if (o.type !== 'header') o.value = inp.value;
                    newJson.push(o);
                });

                const sql = `UPDATE ${table} SET ${colJson} = '${JSON.stringify(newJson).replace(/'/g, "\\'")}' WHERE ${colPk} = ${id}`;

                fetch('../librerias/AJAX/Execute.php', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                    body: `sql=${encodeURIComponent(sql)}&db=${db}`
                }).then(r=>r.json()).then(d=>{
                    if(d.status==='success'||d.rows_affected>=0) {
                        btn.className='btn btn-success btn-lg shadow-sm'; btn.innerHTML='¡Listo!';
                        setTimeout(()=>{ btn.className='btn btn-primary btn-lg shadow-sm'; btn.innerHTML=originalText; btn.disabled=false; },1500);
                    } else alert(d.message);
                });
            }
        };
        </script>
        <?php
    }
}
?>