<?php
// Creating the widget
class niche_widget extends WP_Widget {

function __construct() {
    parent::__construct(
        'niche_widget',
        __('Variables de Ayuda', 'nichecreator'),
        array('description' => __('Widget de variables de ayuda', 'nichecreator'))
    );
}

public function widget($args, $instance) {
    $title = apply_filters('widget_title', '', $instance);
    echo $args['before_widget'];
    if (!empty($title)) echo $args['before_title'] . $title . $args['after_title'];
    ?>

<style>
    .variablesdisponibles {
        position: relative  !important;
        width: 100% !important;
    }
.widget_niche_widget {
  position: sticky;
  top: 100px;
  align-self: start; /* si estás usando flexbox en .col-2 */
}
.col-2 {
  display: flex;
  gap: 2rem;
  align-items: flex-start;
}
.widget_niche_widget {
  max-height: calc(100vh - 150px);
  overflow-y: auto;
}
.btn.button {
    vertical-align: middle !important;
}

.var #entradaspaginas,
.var #pluginseo,
.var #openai,
.var #gemini,
.var #valueserp,
.var #modelo,
.var #modelogem,
.var #type,
.var #imagendestacada,
.var #import,
.var #tipoordenacion,
.var #numfichas,
.var #campoordenacion,
.var #numerico,
.var #ocultarcats,
.var #textoh1,
.var #textoh1padre,
.var #ocultarh1,
.var #ocultardesc,
.var #metatitle,
.var #metatitlepadre,
.var #metadesc,
.var #metadescpadre,
.var #aplicarcss,
.var #plantillas,
.var #autor,
.var #autoria,
.var #catpags,
.var #autorcats,
.var #offset,
.var #offsetia,
.var #offsetcats,
.var #noindexno,
.var #noindexpadresno,
.var #pais,
.var #idioma,
.var #clusterdesc,
.var #clusterimagen,
.var #duplicados1,
.var #duplicados2,
.var #sustitucionant,
.var #sustitucionpost,
.var #quickscrape,
.var #apiplaces,
.var #herramienta,
.var #borrarposts,
.var #borrarautor,
.var #borrartipo,
.var #offsetscrape,
.var #borrarcampo2,
.var #borradocampo,
.var #campocat,
.var #tipocategoria,
.var #replicate {
  margin-top: 0 !important;
  margin-bottom: 0 !important;
  margin-right: 0 !important;
}

#vars-panel .var {
    min-height: 40px;
}
    .var span {
        width: 110px;
    }
.col-2 .col2 {
    position: sticky;
    top: 40px;
}
</style>
    <div class="variablesdisponibles">
        <button id="toggle-vars" class="button button-primary" style="margin-bottom: 1rem;">
            <?php _e('Mostrar variables disponibles', 'nichecreator'); ?>
        </button>
        <div id="vars-panel" style="display:none; border:1px solid #ddd; padding:1rem; background:#f9f9f9;">

            <div style="display:flex; flex-wrap:wrap; gap:1rem;">
                <div class="left" style="flex:1 1 45%">
                    <?php
                    $vars1 = [
                        'nombre' => 'Nombre', 'direccion' => 'Dirección', 'municipio' => 'Municipio', 'provincia' => 'Provincia',
                        'cp' => 'Código Postal', 'pais' => 'País', 'telefono' => 'Teléfono', 'horario' => 'Horario',
                        'lunes' => 'Horario (día)', 'martes' => 'Horario (día)', 'miercoles' => 'Horario (día)',
                        'jueves' => 'Horario (día)', 'viernes' => 'Horario (día)', 'sabado' => 'Horario (día)', 'domingo' => 'Horario (día)',
                        'email' => 'Email', 'website' => 'Sitio web', 'valoracion' => 'Valoración', 'reviews' => 'Número reseñas'
                    ];
                    foreach ($vars1 as $key => $label) {
                        echo "<div class='var'><span id='$key'>%$key</span><button class='btn button ' id='$key' data-clipboard-text='%$key' title='Copiar al portapapeles'>".__($label,'nichecreator')."</button><span style='display:none;color:green;margin-left:10px;' class='copiado'>Copied</span></div>";
                    }
                    ?>
                    <div class="var"><span id="slug">%slug</span><button class="btn button" id="slug" data-clipboard-text="%slug"><?php _e('Slug','nichecreator') ?></button><span style='display:none;color:green;margin-left:10px;' class='copiado'>Copied</span></div>

                </div>

                <div class="right" style="flex:1 1 45%">
                    <?php
                    $vars2 = [
                        'foto' => 'Foto (URL)', 'urlmaps' => 'URL mapa', 'iframe' => 'Iframe mapa',
                        'latitud' => 'Latitud GPS', 'longitud' => 'Longitud GPS', 'categoriapadre' => 'Categoría padre',
                        'categoria' => 'Categoría', 'etiqueta' => 'Etiqueta', 'var1' => 'Var 1', 'var2' => 'Var 2',
                        'var3' => 'Var 3', 'var4' => 'Var 4', 'var5' => 'Var 5', 'var6' => 'Var 6',
                        'var7' => 'Var 7', 'var8' => 'Var 8', 'var9' => 'Var 9', 'var10' => 'Var 10'
                    ];
                    foreach ($vars2 as $key => $label) {
                        echo "<div class='var'><span id='$key'>%$key</span><button class='btn button ' id='$key' data-clipboard-text='%$key'>".__($label,'nichecreator')."</button><span style='display:none;color:green;margin-left:10px;' class='copiado'>Copied</span></div>";
                    }
                    ?>
                     <div class="var"><span id="migapan">%migapan</span><button class="btn button " id='migapan' data-clipboard-text="%migapan"><?php _e('Miga de pan','nichecreator') ?></button><span style='display:none;color:green;margin-left:10px;' class='copiado'>Copied</span></div>
                   
                </div>
            </div>



        </div><!-- /#vars-panel -->
    </div>

    <script>
    jQuery(function($){
        $('#toggle-vars').on('click', function(e){
            e.preventDefault();
            $('#vars-panel').slideToggle();
        });
		var clipboard = new ClipboardJS('.var .btn');
		clipboard.on('success', function(e) {
				var $mensaje = $(e.trigger).next('.copiado');
				 $mensaje.fadeIn(200);
				 setTimeout(function() {
						$mensaje.fadeOut(200);
					}, 2000);
				e.clearSelection();
			});
		clipboard.on('error', function(e) {
				//console.error('Action:', e.text);
				//console.error('Trigger:', e.trigger);
				alert(e.text);
			});
    });
	
    </script>

    <?php
    echo $args['after_widget'];
}

public function form($instance) {
    $title = isset($instance['title']) ? $instance['title'] : __('Variables', 'nichecreator');
    ?>
    <p>
        <label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:'); ?></label>
        <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo esc_attr($title); ?>" />
    </p>
    <?php
}

public function update($new_instance, $old_instance) {
    $instance = [];
    $instance['title'] = (!empty($new_instance['title'])) ? strip_tags($new_instance['title']) : '';
    return $instance;
}
}

function niche_load_widget() {
    register_widget('niche_widget');
}
add_action('widgets_init', 'niche_load_widget');
