<?php
if (!function_exists('pulsegrid_get_theme_version')) {
    function pulsegrid_get_theme_version() {
        static $version = null;
        if ($version === null) {
            $theme = wp_get_theme(get_template());
            $version = $theme->get('Version');
        }
        return $version ?: '2.0';
    }
}

// Enqueue trailer modal styles
function pulsegrid_enqueue_trailer_modal() {
    if (is_single()) {
        wp_enqueue_style('pulsegrid-trailer-modal', get_template_directory_uri() . '/trailer-modal.css', array(), pulsegrid_get_theme_version());
    }
}
add_action('wp_enqueue_scripts', 'pulsegrid_enqueue_trailer_modal');

// Enqueue admin scripts
function pulsegrid_admin_scripts($hook) {
    if ('toplevel_page_pulsegrid' !== $hook) {
        return;
    }
    wp_enqueue_style('pulsegrid-admin-panel', get_template_directory_uri() . '/assets/css/admin-panel.css', array(), pulsegrid_get_theme_version());
    wp_enqueue_script('jquery-ui-sortable');
}
add_action('admin_enqueue_scripts', 'pulsegrid_admin_scripts');

// Theme setup
function pulsegrid_setup() {
    // Add theme support for post thumbnails
    add_theme_support('post-thumbnails');
    
    // Add theme support for title tag
    add_theme_support('title-tag');
    
    // Add theme support for custom logo
    add_theme_support('custom-logo');
    
    // Add theme support for HTML5
    add_theme_support('html5', array(
        'search-form',
        'comment-form',
        'comment-list',
        'gallery',
        'caption',
    ));
    
    // Register navigation menus
    register_nav_menus(array(
        'primary' => 'Primary Menu',
    ));
    
    // Add image sizes
    add_image_size('post-grid-thumb', 200, 150, true);
    add_image_size('featured-thumb', 300, 200, true);
    
    // Enable comments on pages
    add_post_type_support('page', 'comments');
}
add_action('after_setup_theme', 'pulsegrid_setup');

// Enqueue styles and scripts
function pulsegrid_scripts() {
    wp_enqueue_style('pulsegrid-style', get_stylesheet_uri(), array(), pulsegrid_get_theme_version());
    wp_enqueue_script('pulsegrid-script', get_template_directory_uri() . '/js/main.js', array('jquery'), pulsegrid_get_theme_version(), true);
    
    // Enqueue comment reply script for threaded comments
    if (is_singular() && comments_open() && get_option('thread_comments')) {
        wp_enqueue_script('comment-reply');
    }
    
    // Enqueue adblock detector if enabled
    if (get_option('pulsegrid_adblock_detector', '0') === '1') {
        wp_enqueue_script('pulsegrid-adblock-detector', get_template_directory_uri() . '/js/adblock-detector.js', array(), pulsegrid_get_theme_version(), true);
    }
}
add_action('wp_enqueue_scripts', 'pulsegrid_scripts');

// Custom comment callback function
function pulsegrid_comment_callback($comment, $args, $depth) {
    if ('div' === $args['style']) {
        $tag = 'div';
        $add_below = 'comment';
    } else {
        $tag = 'li';
        $add_below = 'div-comment';
    }
    ?>
    <<?php echo $tag; ?> <?php comment_class(empty($args['has_children']) ? '' : 'parent'); ?> id="comment-<?php comment_ID(); ?>">
        <?php if ('div' != $args['style']) : ?>
            <div id="div-comment-<?php comment_ID(); ?>" class="comment-body">
        <?php endif; ?>
        
        <div class="comment-author vcard">
            <?php echo get_avatar($comment, 32); ?>
            <cite class="fn"><?php comment_author_link(); ?></cite>
            <span class="says">dice:</span>
        </div>
        
        <div class="comment-meta">
            <span class="comment-date"><?php comment_date('j F, Y'); ?> a las <?php comment_time('H:i'); ?></span>
        </div>
        
        <div class="comment-content">
            <?php comment_text(); ?>
        </div>
        
        <div class="comment-reply">
            <?php 
            comment_reply_link(array_merge($args, array(
                'add_below' => $add_below,
                'depth' => $depth,
                'max_depth' => $args['max_depth'],
                'reply_text' => 'Responder'
            ))); 
            ?>
        </div>
        
        <?php if ('div' != $args['style']) : ?>
            </div>
        <?php endif; ?>
    <?php
}

// Include custom widgets
require get_template_directory() . '/inc/custom-widgets.php';

// Register sidebars and enable default widgets
function pulsegrid_widgets_init() {
    register_sidebar(array(
        'name'          => 'Main Sidebar',
        'id'            => 'sidebar-1',
        'description'   => 'Add widgets here to appear in your sidebar.',
        'before_widget' => '<div id="%1$s" class="sidebar-widget %2$s">',
        'after_widget'  => '</div>',
        'before_title'  => '<h3 class="widget-title">',
        'after_title'   => '</h3>',
    ));
    
    // Enable default WordPress widgets
    add_theme_support('widgets');
    add_theme_support('widgets-block-editor');
}
add_action('widgets_init', 'pulsegrid_widgets_init');

// Fallback menu function
function pulsegrid_fallback_menu() {
    echo '<ul class="nav-menu">';
    echo '<li><a href="' . home_url() . '">Inicio</a></li>';
    echo '<li><a href="' . home_url('/sample-page/') . '">Página de ejemplo</a></li>';
    echo '<li><a href="#">En Emisión</a></li>';
    echo '<li><a href="#">Contacto</a></li>';
    echo '</ul>';
}

// Custom pagination function
function pulsegrid_pagination($query = null) {
    global $wp_query;
    
    if (!$query) {
        $query = $wp_query;
    }
    
    $big = 999999999;
    
    echo paginate_links(array(
        'base' => str_replace($big, '%#%', esc_url(get_pagenum_link($big))),
        'format' => '?paged=%#%',
        'current' => max(1, get_query_var('paged')),
        'total' => $query->max_num_pages,
        'prev_text' => '« Anterior',
        'next_text' => 'Siguiente »',
        'type' => 'list'
    ));
}

// Get related posts function
function pulsegrid_get_related_posts($post_id, $limit = 6) {
    // Get the related posts type from Customizer
    $related_type = get_theme_mod('pulsegrid_related_type', 'category');
    
    $args = array(
        'post__not_in' => array($post_id),
        'posts_per_page' => $limit,
        'ignore_sticky_posts' => 1,
    );
    
    if ($related_type === 'tag') {
        // Get posts by tags
        $tags = wp_get_post_tags($post_id);
        if ($tags) {
            $tag_ids = array();
            foreach($tags as $tag) {
                $tag_ids[] = $tag->term_id;
            }
            
            $args['tax_query'] = array(
                array(
                    'taxonomy' => 'post_tag',
                    'field' => 'term_id',
                    'terms' => $tag_ids
                )
            );
            
            return new WP_Query($args);
        }
    } else {
        // Get posts by category (default)
        $categories = wp_get_post_categories($post_id);
        if ($categories) {
            $args['tax_query'] = array(
                array(
                    'taxonomy' => 'category',
                    'field' => 'term_id',
                    'terms' => $categories
                )
            );
            
            return new WP_Query($args);
        }
    }
    
    return false;
}

// Excerpt length
function pulsegrid_excerpt_length($length) {
    return 20;
}
add_filter('excerpt_length', 'pulsegrid_excerpt_length');

// Custom excerpt more
function pulsegrid_excerpt_more($more) {
    return '...';
}
add_filter('excerpt_more', 'pulsegrid_excerpt_more');


// Add PulseGrid Admin Menu
function pulsegrid_add_admin_menu() {
    add_menu_page(
        'PulseGrid Pro',
        'PulseGrid Pro',
        'manage_options',
        'pulsegrid',
        'pulsegrid_admin_page',
        'dashicons-plus-alt',
        3
    );
}
add_action('admin_menu', 'pulsegrid_add_admin_menu');

// Admin Page Content
function pulsegrid_admin_page() {
    $active_tab = isset($_GET['tab']) ? sanitize_key($_GET['tab']) : 'slider';
    if ($active_tab === 'general') {
        $active_tab = 'slider';
    }

    $tab_meta = array(
        'slider' => array(
            'label'       => 'Slider',
            'parent'      => 'General',
            'description' => 'Configura el slider de la página de inicio: visibilidad, tipo, autoplay y posts destacados.',
            'group'       => 'general',
        ),
        'home' => array(
            'label'       => 'Home',
            'parent'      => 'General',
            'description' => 'Configura las secciones de contenido y widgets de la página principal.',
            'group'       => 'general',
        ),
        'anuncios' => array(
            'label'       => 'Anuncios',
            'parent'      => 'General',
            'description' => 'Gestiona los códigos publicitarios en distintas áreas del sitio.',
            'group'       => 'general',
        ),
        'soporte' => array(
            'label'       => 'Soporte',
            'parent'      => null,
            'description' => 'Información de contacto y soporte para el tema PulseGrid Pro.',
            'group'       => 'soporte',
        ),
        'licencia' => array(
            'label'       => 'Licencia',
            'parent'      => null,
            'description' => 'Activa o desactiva la licencia de PulseGrid Pro para este dominio (servidor wptheme.site).',
            'group'       => 'licencia',
        ),
    );

    if (!isset($tab_meta[$active_tab])) {
        $active_tab = 'slider';
    }

    $current = $tab_meta[$active_tab];
    $general_tabs = array('slider', 'home', 'anuncios');
    $settings_tabs = $general_tabs;
    $is_general_group = in_array($active_tab, $general_tabs, true);
    
    if (isset($_POST['pulsegrid_settings_submit'])) {
        check_admin_referer('pulsegrid_settings_nonce');
        
        if ($active_tab === 'slider') {
            if (isset($_POST['pulsegrid_slider_posts_ids'])) {
                $selected_posts = array_map('intval', $_POST['pulsegrid_slider_posts_ids']);
                update_option('pulsegrid_slider_posts_ids', $selected_posts);
            } else {
                update_option('pulsegrid_slider_posts_ids', array());
            }
            
            update_option('pulsegrid_slider_enabled', isset($_POST['pulsegrid_slider_enabled']) ? '1' : '0');
            update_option('pulsegrid_search_enabled', isset($_POST['pulsegrid_search_enabled']) ? '1' : '0');
            update_option('pulsegrid_slider_type', sanitize_text_field($_POST['pulsegrid_slider_type'] ?? get_option('pulsegrid_slider_type', 'carousel')));
            update_option('pulsegrid_slider_autoplay', isset($_POST['pulsegrid_slider_autoplay']) ? '1' : '0');
            $slider_interval = isset($_POST['pulsegrid_slider_interval'])
                ? intval($_POST['pulsegrid_slider_interval'])
                : (int) get_option('pulsegrid_slider_interval', 5);
            update_option('pulsegrid_slider_interval', max(1, min(30, $slider_interval)));
            update_option('pulsegrid_slider_posts_count', isset($_POST['pulsegrid_slider_posts_count'])
                ? intval($_POST['pulsegrid_slider_posts_count'])
                : (int) get_option('pulsegrid_slider_posts_count', 10));
        } elseif ($active_tab === 'home') {
            // Home sections are saved below
        } elseif ($active_tab === 'anuncios') {
            // Allow script tags and all HTML for ad codes
            $allowed_html = wp_kses_allowed_html('post');
            $allowed_html['script'] = array(
                'type' => true,
                'src' => true,
                'async' => true,
                'defer' => true,
                'charset' => true,
            );
            $allowed_html['iframe'] = array(
                'src' => true,
                'width' => true,
                'height' => true,
                'frameborder' => true,
                'scrolling' => true,
                'marginheight' => true,
                'marginwidth' => true,
                'allowfullscreen' => true,
            );
            
            update_option('pulsegrid_header_ad', wp_kses(stripslashes($_POST['pulsegrid_header_ad']), $allowed_html));
            update_option('pulsegrid_sidebar_ad', wp_kses(stripslashes($_POST['pulsegrid_sidebar_ad']), $allowed_html));
            update_option('pulsegrid_footer_ad', wp_kses(stripslashes($_POST['pulsegrid_footer_ad']), $allowed_html));
            update_option('pulsegrid_home_ad', wp_kses(stripslashes($_POST['pulsegrid_home_ad']), $allowed_html));
            update_option('pulsegrid_post_content_ad', wp_kses(stripslashes($_POST['pulsegrid_post_content_ad']), $allowed_html));
            update_option('pulsegrid_post_comments_ad', wp_kses(stripslashes($_POST['pulsegrid_post_comments_ad']), $allowed_html));
            update_option('pulsegrid_adblock_detector', isset($_POST['pulsegrid_adblock_detector']) ? '1' : '0');
        }
        
        // Guardar secciones del home
        if (isset($_POST['pulsegrid_home_sections'])) {
            $sections = array();
            foreach ($_POST['pulsegrid_home_sections'] as $index => $section) {
                $sections[] = array(
                    'enabled' => isset($section['enabled']) ? true : false,
                    'title' => sanitize_text_field($section['title']),
                    'type' => sanitize_text_field($section['type']),
                    'category' => isset($section['category']) ? intval($section['category']) : 0,
                    'tag' => isset($section['tag']) ? intval($section['tag']) : 0,
                    'posts_count' => intval($section['posts_count']),
                    'image_orientation' => 'vertical'
                );
            }
            update_option('pulsegrid_home_sections', $sections);
        }
        
        echo '<div class="notice notice-success is-dismissible"><p>Configuración guardada correctamente.</p></div>';
    }
    ?>
    <div class="pg-panel-wrap">
        <div class="pg-panel-header">
            <div class="pg-panel-label">Panel de ajustes</div>
            <h1>PulseGrid Pro</h1>
            <p class="pg-panel-subtitle">Opciones del tema PulseGrid Pro.</p>
        </div>

        <div class="pg-panel-layout">
            <aside class="pg-panel-sidebar">
                <nav class="pg-panel-nav" aria-label="Navegación del panel">
                    <div class="pg-menu-group <?php echo $is_general_group ? 'is-open' : ''; ?>" data-menu-group="general">
                        <button type="button" class="pg-menu-item pg-menu-parent <?php echo $is_general_group ? 'is-active' : ''; ?>" aria-expanded="<?php echo $is_general_group ? 'true' : 'false'; ?>" aria-controls="pg-submenu-general">
                            <span class="dashicons dashicons-admin-settings" aria-hidden="true"></span>
                            <span class="pg-menu-parent-label">General</span>
                            <span class="pg-menu-chevron dashicons dashicons-arrow-down-alt2" aria-hidden="true"></span>
                        </button>
                        <ul class="pg-submenu" id="pg-submenu-general">
                            <li>
                                <a href="<?php echo esc_url(admin_url('admin.php?page=pulsegrid&tab=slider')); ?>" class="<?php echo $active_tab === 'slider' ? 'is-active' : ''; ?>">Slider</a>
                            </li>
                            <li>
                                <a href="<?php echo esc_url(admin_url('admin.php?page=pulsegrid&tab=home')); ?>" class="<?php echo $active_tab === 'home' ? 'is-active' : ''; ?>">Home</a>
                            </li>
                            <li>
                                <a href="<?php echo esc_url(admin_url('admin.php?page=pulsegrid&tab=anuncios')); ?>" class="<?php echo $active_tab === 'anuncios' ? 'is-active' : ''; ?>">Anuncios</a>
                            </li>
                        </ul>
                    </div>
                    <a href="<?php echo esc_url(admin_url('admin.php?page=pulsegrid&tab=soporte')); ?>" class="pg-menu-item <?php echo $active_tab === 'soporte' ? 'is-active' : ''; ?>">
                        <span class="dashicons dashicons-sos" aria-hidden="true"></span>
                        Soporte
                    </a>
                    <a href="<?php echo esc_url(admin_url('admin.php?page=pulsegrid&tab=licencia')); ?>" class="pg-menu-item <?php echo $active_tab === 'licencia' ? 'is-active' : ''; ?>">
                        <span class="dashicons dashicons-admin-network" aria-hidden="true"></span>
                        Licencia
                    </a>
                </nav>
            </aside>

            <main class="pg-panel-main">
                <div class="pg-breadcrumbs">
                    Inicio
                    <?php if ($current['parent']) : ?>
                        &raquo; <?php echo esc_html($current['parent']); ?>
                    <?php endif; ?>
                    &raquo; <span><?php echo esc_html($current['label']); ?></span>
                </div>

                <div class="pg-content-header">
                    <h2><?php echo esc_html($current['label']); ?></h2>
                    <p><?php echo esc_html($current['description']); ?></p>
                </div>

                <?php if (in_array($active_tab, $settings_tabs, true)) : ?>
                <form method="post" action="">
                    <?php wp_nonce_field('pulsegrid_settings_nonce'); ?>

                    <div class="pg-panel-body">
            
            <?php if ($active_tab === 'slider') : ?>
                
                <!-- Slider Visibility Section -->
                <div class="pulsegrid-admin-box">
                    <h3 class="pulsegrid-box-title">Visibilidad del Slider</h3>
                    <table class="form-table">
                        <tr>
                            <th scope="row"><label>Mostrar Slider</label></th>
                        <td>
                            <div class="pulsegrid-switch-field">
                                <label class="pulsegrid-toggle-switch" for="pulsegrid_slider_enabled">
                                    <input type="checkbox" name="pulsegrid_slider_enabled" id="pulsegrid_slider_enabled" value="1" <?php checked(get_option('pulsegrid_slider_enabled', '1'), '1'); ?>>
                                    <span class="pulsegrid-toggle-slider"></span>
                                </label>
                                <span class="pulsegrid-switch-label">Mostrar slider en la página de inicio</span>
                            </div>
                            <p class="description">Activa o desactiva la visualización del slider en la página principal.</p>
                        </td>
                    </tr>
                    <tr>
                            <th scope="row"><label>Mostrar Buscador</label></th>
                        <td>
                            <div class="pulsegrid-switch-field">
                                <label class="pulsegrid-toggle-switch" for="pulsegrid_search_enabled">
                                    <input type="checkbox" name="pulsegrid_search_enabled" id="pulsegrid_search_enabled" value="1" <?php checked(get_option('pulsegrid_search_enabled', '1'), '1'); ?>>
                                    <span class="pulsegrid-toggle-slider"></span>
                                </label>
                                <span class="pulsegrid-switch-label">Mostrar buscador en la página de inicio</span>
                            </div>
                            <p class="description">Activa o desactiva la visualización del buscador en la página principal.</p>
                        </td>
                    </tr>
                    </table>
                </div>
                
                <!-- Slider Type Section -->
                <div class="pulsegrid-admin-box">
                    <h3 class="pulsegrid-box-title">Tipo de Slider</h3>
                    <?php
                    $slider_type_current = get_option('pulsegrid_slider_type', 'carousel');
                    $slider_img_base = get_template_directory_uri() . '/assets/images/';
                    ?>
                    <p class="pg-slider-type-intro">Selecciona el estilo de slider para la página de inicio.</p>
                    <div class="pg-slider-type-grid">
                        <label class="pg-slider-type-option">
                            <input type="radio" name="pulsegrid_slider_type" value="carousel" <?php checked($slider_type_current, 'carousel'); ?>>
                            <span class="pg-slider-type-card">
                                <span class="pg-slider-type-head">
                                    <span class="pg-slider-type-radio" aria-hidden="true"></span>
                                    <span class="pg-slider-type-text">
                                        <strong>Carrusel</strong>
                                        <span class="pg-slider-type-desc">Slider horizontal con miniaturas (usa imagen destacada)</span>
                                    </span>
                                </span>
                                <span class="pg-slider-type-preview">
                                    <img src="<?php echo esc_url($slider_img_base . 'slider-carrusel.png'); ?>" alt="<?php esc_attr_e('Vista previa del slider Carrusel', 'pulsegrid'); ?>" loading="lazy">
                                </span>
                            </span>
                        </label>
                        <label class="pg-slider-type-option">
                            <input type="radio" name="pulsegrid_slider_type" value="fullwidth" <?php checked($slider_type_current, 'fullwidth'); ?>>
                            <span class="pg-slider-type-card">
                                <span class="pg-slider-type-head">
                                    <span class="pg-slider-type-radio" aria-hidden="true"></span>
                                    <span class="pg-slider-type-text">
                                        <strong>Imagen Completa</strong>
                                        <span class="pg-slider-type-desc">Slider de ancho completo con backdrop (usa Backdrop URL de TMDB)</span>
                                    </span>
                                </span>
                                <span class="pg-slider-type-preview">
                                    <img src="<?php echo esc_url($slider_img_base . 'slider-completo.png'); ?>" alt="<?php esc_attr_e('Vista previa del slider Imagen Completa', 'pulsegrid'); ?>" loading="lazy">
                                </span>
                            </span>
                        </label>
                    </div>
                </div>
                
                <!-- Slider Configuration Section -->
                <div class="pulsegrid-admin-box">
                    <h3 class="pulsegrid-box-title">Configuración del Slider</h3>
                    <table class="form-table">
                        <tr>
                            <th scope="row"><label>Autoplay</label></th>
                        <td>
                            <div class="pulsegrid-switch-field">
                                <label class="pulsegrid-toggle-switch" for="pulsegrid_slider_autoplay">
                                    <input type="checkbox" name="pulsegrid_slider_autoplay" id="pulsegrid_slider_autoplay" value="1" <?php checked(get_option('pulsegrid_slider_autoplay', '0'), '1'); ?>>
                                    <span class="pulsegrid-toggle-slider"></span>
                                </label>
                                <span class="pulsegrid-switch-label">Activar movimiento automático del slider</span>
                            </div>
                            <br><br>
                            <label for="pulsegrid_slider_interval">Tiempo de avance (segundos):</label>
                            <input type="number" name="pulsegrid_slider_interval" id="pulsegrid_slider_interval" value="<?php echo esc_attr(get_option('pulsegrid_slider_interval', 5)); ?>" min="1" max="30" class="small-text" required>
                            <p class="description">Configura cada cuántos segundos avanza el slider automáticamente.</p>
                            <script>
                            jQuery(document).ready(function($) {
                                $('#pulsegrid_slider_autoplay').on('change', function() {
                                    var $interval = $('#pulsegrid_slider_interval');
                                    if ($(this).is(':checked')) {
                                        $interval.prop('required', true).prop('readonly', false).removeClass('pg-input-disabled');
                                    } else {
                                        $interval.prop('required', false).prop('readonly', true).addClass('pg-input-disabled');
                                    }
                                }).trigger('change');
                            });
                            </script>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="pulsegrid_slider_posts_count">Cantidad de Posts</label></th>
                        <td>
                            <input type="number" name="pulsegrid_slider_posts_count" id="pulsegrid_slider_posts_count" value="<?php echo esc_attr(get_option('pulsegrid_slider_posts_count', 10)); ?>" min="1" max="50" class="small-text">
                            <p class="description">Número de posts a mostrar en el slider (predeterminado: 10).</p>
                        </td>
                    </tr>
                    </table>
                </div>
                
                <!-- Post Selection Section -->
                <div class="pulsegrid-admin-box">
                    <h3 class="pulsegrid-box-title">Seleccionar Posts para el Slider</h3>
                    <p class="pg-slider-posts-note">
                        <span class="dashicons dashicons-info" aria-hidden="true"></span>
                        Si no añades posts en la selección manual, el slider usará automáticamente los últimos posts publicados (hasta la cantidad indicada en «Cantidad de Posts»).
                    </p>
                    <table class="form-table">
                        <tr>
                            <th scope="row"><label>Posts Disponibles</label></th>
                        <td>
                            <div id="pulsegrid-post-selector">
                                <div class="pulsegrid-selector-container">
                                    <div class="pulsegrid-available-posts">
                                        <h3>Seleccionar posts</h3>
                                        <input type="text" id="pulsegrid-search-posts" placeholder="Buscar..." class="regular-text">
                                        <div id="pulsegrid-posts-list" class="pulsegrid-posts-list">
                                            <?php
                                            $all_posts = get_posts(array(
                                                'posts_per_page' => -1,
                                                'post_status' => 'publish',
                                                'orderby' => 'title',
                                                'order' => 'ASC'
                                            ));
                                            $selected_ids = get_option('pulsegrid_slider_posts_ids', array());
                                            
                                            foreach ($all_posts as $post) :
                                                if (!in_array($post->ID, $selected_ids)) :
                                            ?>
                                                <div class="pulsegrid-post-item" data-id="<?php echo $post->ID; ?>">
                                                    <?php if (has_post_thumbnail($post->ID)) : ?>
                                                        <img src="<?php echo get_the_post_thumbnail_url($post->ID, 'thumbnail'); ?>" alt="<?php echo esc_attr($post->post_title); ?>">
                                                    <?php else : ?>
                                                        <div class="pulsegrid-no-thumb"></div>
                                                    <?php endif; ?>
                                                    <span><?php echo esc_html($post->post_title); ?></span>
                                                    <button type="button" class="button pulsegrid-add-post">+</button>
                                                </div>
                                            <?php
                                                endif;
                                            endforeach;
                                            ?>
                                        </div>
                                    </div>
                                    
                                    <div class="pulsegrid-selected-posts">
                                        <h3>✓ Posts seleccionados</h3>
                                        <p class="description">Arrastra para reordenar</p>
                                        <div id="pulsegrid-selected-list" class="pulsegrid-posts-list pulsegrid-sortable">
                                            <?php
                                            if (!empty($selected_ids)) :
                                                foreach ($selected_ids as $post_id) :
                                                    $post = get_post($post_id);
                                                    if ($post) :
                                            ?>
                                                <div class="pulsegrid-post-item" data-id="<?php echo $post->ID; ?>">
                                                    <input type="hidden" name="pulsegrid_slider_posts_ids[]" value="<?php echo $post->ID; ?>">
                                                    <?php if (has_post_thumbnail($post->ID)) : ?>
                                                        <img src="<?php echo get_the_post_thumbnail_url($post->ID, 'thumbnail'); ?>" alt="<?php echo esc_attr($post->post_title); ?>">
                                                    <?php else : ?>
                                                        <div class="pulsegrid-no-thumb"></div>
                                                    <?php endif; ?>
                                                    <span><?php echo esc_html($post->post_title); ?></span>
                                                    <button type="button" class="button pulsegrid-remove-post">×</button>
                                                </div>
                                            <?php
                                                    endif;
                                                endforeach;
                                            endif;
                                            ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <p class="description">Arrastra los posts seleccionados para definir el orden en el slider.</p>
                        </td>
                    </tr>
                    </table>
                </div>
                
            <?php elseif ($active_tab === 'home') : ?>
                <div class="pulsegrid-home-sections">
                    <div class="pulsegrid-info-box">
                        <h3><span class="dashicons dashicons-info"></span> Configuración de la Página Principal</h3>
                        <p>Configura las secciones de contenido y su widget que deseas mostrar en la página principal.</p>
                        <ul style="margin-left: 20px;">
                            <li>Cada sección mostrará posts de una categoría específica.</li>
                            <li>Usa títulos descriptivos y atractivos para cada sección.</li>
                            <li>Asegúrate de que la categoría seleccionada tenga posts publicados.</li>
                            <li>El número de posts recomendado es 7 (o bien 14 para 2 filas de 7 columnas).</li>
                            <li>Las secciones aparecerán en el orden que se ven en la página principal.</li>
                        </ul>
                    </div>

                    <h3 class="pg-section-heading">Secciones de Contenido</h3>
                    <p class="description">Agrega secciones personalizadas. Cada sección puede mostrar posts por categoría, etiqueta o los últimos posts publicados.</p>

                    <div id="pulsegrid-sections-container">
                        <?php
                        $sections = get_option('pulsegrid_home_sections', array());
                        if (empty($sections)) {
                            $sections = array(
                                array('enabled' => true, 'title' => 'Películas', 'type' => 'category', 'category' => '', 'tag' => '', 'posts_count' => 14)
                            );
                        }
                        
                        $categories = get_categories(array('hide_empty' => false));
                        $tags = get_tags(array('hide_empty' => false));
                        
                        foreach ($sections as $index => $section) :
                            $section_enabled = isset($section['enabled']) ? $section['enabled'] : true;
                            $section_title = isset($section['title']) ? $section['title'] : '';
                            $section_type = isset($section['type']) ? $section['type'] : 'category';
                            $section_category = isset($section['category']) ? $section['category'] : '';
                            $section_tag = isset($section['tag']) ? $section['tag'] : '';
                            $section_posts_count = isset($section['posts_count']) ? $section['posts_count'] : 14;
                        ?>
                        <div class="pulsegrid-section-item" data-index="<?php echo $index; ?>">
                            <div class="pulsegrid-section-header">
                                <label class="pulsegrid-toggle-switch">
                                    <input type="checkbox" name="pulsegrid_home_sections[<?php echo $index; ?>][enabled]" value="1" <?php checked($section_enabled, true); ?>>
                                    <span class="pulsegrid-toggle-slider"></span>
                                </label>
                                <h3>Sección <?php echo ($index + 1); ?></h3>
                                <div class="pulsegrid-section-actions">
                                    <button type="button" class="button pulsegrid-move-up" title="Subir">↑</button>
                                    <button type="button" class="button pulsegrid-move-down" title="Bajar">↓</button>
                                    <button type="button" class="button pulsegrid-remove-section" title="Eliminar">×</button>
                                    <button type="button" class="button pulsegrid-toggle-section" title="Expandir/Contraer">▼</button>
                                </div>
                            </div>
                            
                            <div class="pulsegrid-section-content">
                                <table class="form-table">
                                    <tr>
                                        <th scope="row"><label>Título de la Sección</label></th>
                                        <td>
                                            <input type="text" name="pulsegrid_home_sections[<?php echo $index; ?>][title]" value="<?php echo esc_attr($section_title); ?>" class="regular-text" placeholder="Ej: Películas">
                                            <p class="description">El título que aparecerá en la sección.</p>
                                        </td>
                                    </tr>
                                    <tr>
                                        <th scope="row"><label>Tipo de Contenido</label></th>
                                        <td>
                                            <select name="pulsegrid_home_sections[<?php echo $index; ?>][type]" class="pulsegrid-section-type regular-text" data-index="<?php echo $index; ?>">
                                                <option value="category" <?php selected($section_type, 'category'); ?>>Por Categoría</option>
                                                <option value="tag" <?php selected($section_type, 'tag'); ?>>Por Etiqueta</option>
                                                <option value="latest" <?php selected($section_type, 'latest'); ?>>Últimos Posts Publicados</option>
                                            </select>
                                            <p class="description">Selecciona el tipo de contenido que se mostrará en esta sección.</p>
                                        </td>
                                    </tr>
                                    <tr class="pulsegrid-category-row" data-index="<?php echo $index; ?>" <?php echo $section_type == 'category' ? '' : 'style="display: none;"'; ?>>
                                        <th scope="row"><label>Categoría</label></th>
                                        <td>
                                            <select name="pulsegrid_home_sections[<?php echo $index; ?>][category]" class="regular-text">
                                                <option value="">Seleccionar categoría</option>
                                                <?php foreach ($categories as $cat) : ?>
                                                    <option value="<?php echo $cat->term_id; ?>" <?php selected($section_category, $cat->term_id); ?>>
                                                        <?php echo esc_html($cat->name); ?> (<?php echo $cat->count; ?> posts)
                                                    </option>
                                                <?php endforeach; ?>
                                            </select>
                                            <p class="description">Selecciona la categoría de posts que se mostrarán en esta sección. <a href="<?php echo admin_url('edit-tags.php?taxonomy=category'); ?>" target="_blank">Gestionar categorías</a></p>
                                        </td>
                                    </tr>
                                    <tr class="pulsegrid-tag-row" data-index="<?php echo $index; ?>" <?php echo $section_type == 'tag' ? '' : 'style="display: none;"'; ?>>
                                        <th scope="row"><label>Etiqueta</label></th>
                                        <td>
                                            <select name="pulsegrid_home_sections[<?php echo $index; ?>][tag]" class="regular-text">
                                                <option value="">Seleccionar etiqueta</option>
                                                <?php foreach ($tags as $tag) : ?>
                                                    <option value="<?php echo $tag->term_id; ?>" <?php selected($section_tag, $tag->term_id); ?>>
                                                        <?php echo esc_html($tag->name); ?> (<?php echo $tag->count; ?> posts)
                                                    </option>
                                                <?php endforeach; ?>
                                            </select>
                                            <p class="description">Selecciona la etiqueta de posts que se mostrarán en esta sección. <a href="<?php echo admin_url('edit-tags.php?taxonomy=post_tag'); ?>" target="_blank">Gestionar etiquetas</a></p>
                                        </td>
                                    </tr>
                                    <tr>
                                        <th scope="row"><label>Número de Posts</label></th>
                                        <td>
                                            <input type="number" name="pulsegrid_home_sections[<?php echo $index; ?>][posts_count]" value="<?php echo esc_attr($section_posts_count); ?>" min="1" max="56" class="small-text">
                                            <p class="description">Cantidad de posts a mostrar (1-56). Recomendado: 7 o múltiplos de 7.</p>
                                        </td>
                                    </tr>
                                </table>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>

                    <button type="button" id="pulsegrid-add-section" class="button button-primary pg-add-section-btn">
                        <span class="dashicons dashicons-plus-alt"></span>
                        <span>Agregar Nueva Sección</span>
                    </button>
                </div>
                
            <?php elseif ($active_tab === 'anuncios') : ?>
                <table class="form-table">
                    <tr>
                        <th scope="row"><label>Detector de AdBlock</label></th>
                        <td>
                            <div class="pulsegrid-switch-field">
                                <label class="pulsegrid-toggle-switch" for="pulsegrid_adblock_detector">
                                    <input type="checkbox" name="pulsegrid_adblock_detector" id="pulsegrid_adblock_detector" value="1" <?php checked(get_option('pulsegrid_adblock_detector', '0'), '1'); ?>>
                                    <span class="pulsegrid-toggle-slider"></span>
                                </label>
                                <span class="pulsegrid-switch-label">Activar detector de bloqueadores de anuncios</span>
                            </div>
                            <p class="description">Muestra una alerta cuando se detecta un bloqueador de anuncios activo.</p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="pulsegrid_header_ad">Anuncio del Header</label></th>
                        <td>
                            <textarea name="pulsegrid_header_ad" id="pulsegrid_header_ad" rows="5" cols="50" class="large-text code"><?php echo esc_textarea(get_option('pulsegrid_header_ad', '')); ?></textarea>
                            <p class="description">Código HTML del anuncio para el header.</p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="pulsegrid_sidebar_ad">Anuncio del Sidebar</label></th>
                        <td>
                            <textarea name="pulsegrid_sidebar_ad" id="pulsegrid_sidebar_ad" rows="5" cols="50" class="large-text code"><?php echo esc_textarea(get_option('pulsegrid_sidebar_ad', '')); ?></textarea>
                            <p class="description">Código HTML del anuncio para el sidebar.</p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="pulsegrid_footer_ad">Anuncio del Footer</label></th>
                        <td>
                            <textarea name="pulsegrid_footer_ad" id="pulsegrid_footer_ad" rows="5" cols="50" class="large-text code"><?php echo esc_textarea(get_option('pulsegrid_footer_ad', '')); ?></textarea>
                            <p class="description">Código HTML del anuncio para el footer.</p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="pulsegrid_home_ad">Anuncio del Home</label></th>
                        <td>
                            <textarea name="pulsegrid_home_ad" id="pulsegrid_home_ad" rows="5" cols="50" class="large-text code"><?php echo esc_textarea(get_option('pulsegrid_home_ad', '')); ?></textarea>
                            <p class="description">Código HTML del anuncio entre el slider y el contenido del home.</p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="pulsegrid_post_content_ad">Anuncio Post (Después del Contenido)</label></th>
                        <td>
                            <textarea name="pulsegrid_post_content_ad" id="pulsegrid_post_content_ad" rows="5" cols="50" class="large-text code"><?php echo esc_textarea(get_option('pulsegrid_post_content_ad', '')); ?></textarea>
                            <p class="description">Código HTML del anuncio después del contenido del post.</p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="pulsegrid_post_comments_ad">Anuncio Post (Antes de Comentarios)</label></th>
                        <td>
                            <textarea name="pulsegrid_post_comments_ad" id="pulsegrid_post_comments_ad" rows="5" cols="50" class="large-text code"><?php echo esc_textarea(get_option('pulsegrid_post_comments_ad', '')); ?></textarea>
                            <p class="description">Código HTML del anuncio antes de los comentarios.</p>
                        </td>
                    </tr>
                </table>
                
            <?php endif; ?>
                    </div>

                    <div class="pg-panel-footer">
                        <button type="submit" name="pulsegrid_settings_submit" class="button button-primary">
                            <span class="dashicons dashicons-saved" aria-hidden="true"></span>
                            Guardar cambios
                        </button>
                    </div>
                </form>
                <?php else : ?>
                    <div class="pg-panel-body">
            <?php if ($active_tab === 'soporte') : ?>
                <div class="pulsegrid-support-section">
                    <div class="pulsegrid-support-grid">
                        <div class="pulsegrid-support-card">
                            <h3><span class="dashicons dashicons-email"></span> Contacto:</h3>
                            <div class="support-card-content">
                                <p>Para reportar algún problema o pedir alguna nueva funcionalidad escríbeme en <strong>FOROBETA</strong></p>
                                <p>Para más proyectos visita mi página web <a href="https://wptheme.site/" target="_blank" style="color: #3498db; text-decoration: none;">WpTheme</a></p>
                            </div>
                        </div>
                        
                        <div class="pulsegrid-support-card">
                            <h3><span class="dashicons dashicons-info"></span> Información del Tema</h3>
                            <div class="support-card-content">
                                <p><strong>Nombre del Tema:</strong> <span style="color: #3498db;">PulseGrid Pro</span></p>
                                <p><strong>Versión:</strong> <?php echo esc_html(pulsegrid_get_theme_version()); ?></p>
                                <p><strong>Autor:</strong> Jach</p>
                            </div>
                        </div>
                        
                        <div class="pulsegrid-support-card">
                            <h3><span class="dashicons dashicons-admin-links"></span> Enlaces Útiles</h3>
                            <div class="support-card-content">
                                <p><span class="dashicons dashicons-admin-users"></span> <a href="https://forobeta.com/members/jach12k7.282356/" target="_blank" style="color: #3498db; text-decoration: none;">Perfil en ForoBeta</a></p>
                                <p><span class="dashicons dashicons-admin-site"></span> <a href="https://wptheme.site/" target="_blank" style="color: #3498db; text-decoration: none;">Sitio Web WpTheme</a></p>
                                <p><span class="dashicons dashicons-book"></span> <a href="https://wptheme.site/documentacion/pulsegridpro/index.html" target="_blank" style="color: #3498db; text-decoration: none;">Documentación del Theme</a></p>
                            </div>
                        </div>
                    </div>
                    
                    <div class="pulsegrid-support-footer">
                        <p><strong>¡Gracias por usar PulseGrid Pro!</strong></p>
                        <p>Si te gusta este tema, considera dejar una reseña o compartirlo con otros.</p>
                    </div>
                </div>
            <?php elseif ($active_tab === 'licencia') : ?>
                <?php pulsegrid_theme_license()->render_license_panel(); ?>
            <?php endif; ?>
                    </div>
                <?php endif; ?>
            </main>
        </div>
    </div>
    
    <script>
    jQuery(document).ready(function($) {
        $('.pg-menu-parent').on('click', function() {
            var $group = $(this).closest('.pg-menu-group');
            var isOpen = $group.toggleClass('is-open').hasClass('is-open');
            $(this).attr('aria-expanded', isOpen ? 'true' : 'false');
        });

        // Search functionality
        $('#pulsegrid-search-posts').on('keyup', function() {
            var searchTerm = $(this).val().toLowerCase();
            $('#pulsegrid-posts-list .pulsegrid-post-item').each(function() {
                var postTitle = $(this).find('span').text().toLowerCase();
                if (postTitle.indexOf(searchTerm) > -1) {
                    $(this).show();
                } else {
                    $(this).hide();
                }
            });
        });
        
        // Add post to selected
        $(document).on('click', '.pulsegrid-add-post', function() {
            var $item = $(this).closest('.pulsegrid-post-item');
            var postId = $item.data('id');
            var postHtml = $item.clone();
            
            // Change button to remove
            postHtml.find('button').removeClass('pulsegrid-add-post').addClass('pulsegrid-remove-post').text('×');
            
            // Add hidden input
            postHtml.prepend('<input type="hidden" name="pulsegrid_slider_posts_ids[]" value="' + postId + '">');
            
            // Add to selected list
            $('#pulsegrid-selected-list').append(postHtml);
            
            // Remove from available list
            $item.remove();
        });
        
        // Remove post from selected
        $(document).on('click', '.pulsegrid-remove-post', function() {
            var $item = $(this).closest('.pulsegrid-post-item');
            var postId = $item.data('id');
            var postHtml = $item.clone();
            
            // Remove hidden input
            postHtml.find('input[type="hidden"]').remove();
            
            // Change button to add
            postHtml.find('button').removeClass('pulsegrid-remove-post').addClass('pulsegrid-add-post').text('+');
            
            // Add to available list
            $('#pulsegrid-posts-list').append(postHtml);
            
            // Remove from selected list
            $item.remove();
        });
        
        // Make selected list sortable
        if (typeof $.fn.sortable !== 'undefined') {
            $('#pulsegrid-selected-list').sortable({
                placeholder: 'pulsegrid-sortable-placeholder',
                cursor: 'move',
                opacity: 0.6
            });
        }
        
        // Home sections management
        var sectionIndex = <?php echo count(get_option('pulsegrid_home_sections', array())); ?>;
        
        // Handle section type change
        $(document).on('change', '.pulsegrid-section-type', function() {
            var index = $(this).data('index');
            var type = $(this).val();
            
            // Hide all option rows
            $('.pulsegrid-category-row[data-index="' + index + '"]').hide();
            $('.pulsegrid-tag-row[data-index="' + index + '"]').hide();
            
            // Show relevant row based on type
            if (type === 'category') {
                $('.pulsegrid-category-row[data-index="' + index + '"]').show();
            } else if (type === 'tag') {
                $('.pulsegrid-tag-row[data-index="' + index + '"]').show();
            }
            // For 'latest', no additional fields needed
        });
        
        // Add new section
        $('#pulsegrid-add-section').on('click', function() {
            var categories = <?php echo json_encode(array_map(function($cat) {
                return array('id' => $cat->term_id, 'name' => $cat->name, 'count' => $cat->count);
            }, get_categories(array('hide_empty' => false)))); ?>;
            
            var tags = <?php echo json_encode(array_map(function($tag) {
                return array('id' => $tag->term_id, 'name' => $tag->name, 'count' => $tag->count);
            }, get_tags(array('hide_empty' => false)))); ?>;
            
            var categoryOptions = '<option value="">Seleccionar categoría</option>';
            categories.forEach(function(cat) {
                categoryOptions += '<option value="' + cat.id + '">' + cat.name + ' (' + cat.count + ' posts)</option>';
            });
            
            var tagOptions = '<option value="">Seleccionar etiqueta</option>';
            tags.forEach(function(tag) {
                tagOptions += '<option value="' + tag.id + '">' + tag.name + ' (' + tag.count + ' posts)</option>';
            });
            
            var sectionHtml = '<div class="pulsegrid-section-item" data-index="' + sectionIndex + '">' +
                '<div class="pulsegrid-section-header">' +
                    '<label class="pulsegrid-toggle-switch">' +
                        '<input type="checkbox" name="pulsegrid_home_sections[' + sectionIndex + '][enabled]" value="1" checked>' +
                        '<span class="pulsegrid-toggle-slider"></span>' +
                    '</label>' +
                    '<h3>Sección ' + (sectionIndex + 1) + '</h3>' +
                    '<div class="pulsegrid-section-actions">' +
                        '<button type="button" class="button pulsegrid-move-up" title="Subir">↑</button>' +
                        '<button type="button" class="button pulsegrid-move-down" title="Bajar">↓</button>' +
                        '<button type="button" class="button pulsegrid-remove-section" title="Eliminar">×</button>' +
                        '<button type="button" class="button pulsegrid-toggle-section" title="Expandir/Contraer">▼</button>' +
                    '</div>' +
                '</div>' +
                '<div class="pulsegrid-section-content">' +
                    '<table class="form-table">' +
                        '<tr>' +
                            '<th scope="row"><label>Título de la Sección</label></th>' +
                            '<td>' +
                                '<input type="text" name="pulsegrid_home_sections[' + sectionIndex + '][title]" value="" class="regular-text" placeholder="Ej: Películas">' +
                                '<p class="description">El título que aparecerá en la sección.</p>' +
                            '</td>' +
                        '</tr>' +
                        '<tr>' +
                            '<th scope="row"><label>Tipo de Contenido</label></th>' +
                            '<td>' +
                                '<select name="pulsegrid_home_sections[' + sectionIndex + '][type]" class="pulsegrid-section-type regular-text" data-index="' + sectionIndex + '">' +
                                    '<option value="category">Por Categoría</option>' +
                                    '<option value="tag">Por Etiqueta</option>' +
                                    '<option value="latest">Últimos Posts Publicados</option>' +
                                '</select>' +
                                '<p class="description">Selecciona el tipo de contenido que se mostrará en esta sección.</p>' +
                            '</td>' +
                        '</tr>' +
                        '<tr class="pulsegrid-category-row" data-index="' + sectionIndex + '">' +
                            '<th scope="row"><label>Categoría</label></th>' +
                            '<td>' +
                                '<select name="pulsegrid_home_sections[' + sectionIndex + '][category]" class="regular-text">' +
                                    categoryOptions +
                                '</select>' +
                                '<p class="description">Selecciona la categoría de posts que se mostrarán en esta sección.</p>' +
                            '</td>' +
                        '</tr>' +
                        '<tr class="pulsegrid-tag-row" data-index="' + sectionIndex + '" style="display: none;">' +
                            '<th scope="row"><label>Etiqueta</label></th>' +
                            '<td>' +
                                '<select name="pulsegrid_home_sections[' + sectionIndex + '][tag]" class="regular-text">' +
                                    tagOptions +
                                '</select>' +
                                '<p class="description">Selecciona la etiqueta de posts que se mostrarán en esta sección.</p>' +
                            '</td>' +
                        '</tr>' +
                        '<tr>' +
                            '<th scope="row"><label>Número de Posts</label></th>' +
                            '<td>' +
                                '<input type="number" name="pulsegrid_home_sections[' + sectionIndex + '][posts_count]" value="7" min="1" max="56" class="small-text">' +
                                '<p class="description">Cantidad de posts a mostrar (1-56). Recomendado: 7 o múltiplos de 7.</p>' +
                            '</td>' +
                        '</tr>' +
                    '</table>' +
                '</div>' +
            '</div>';
            
            $('#pulsegrid-sections-container').append(sectionHtml);
            sectionIndex++;
            updateSectionNumbers();
        });
        
        // Remove section
        $(document).on('click', '.pulsegrid-remove-section', function() {
            if (confirm('¿Estás seguro de eliminar esta sección?')) {
                $(this).closest('.pulsegrid-section-item').remove();
                updateSectionNumbers();
            }
        });
        
        // Toggle section content
        $(document).on('click', '.pulsegrid-toggle-section', function() {
            var $content = $(this).closest('.pulsegrid-section-item').find('.pulsegrid-section-content');
            $content.slideToggle();
            $(this).text($(this).text() === '▼' ? '▲' : '▼');
        });
        
        // Move section up
        $(document).on('click', '.pulsegrid-move-up', function() {
            var $section = $(this).closest('.pulsegrid-section-item');
            var $prev = $section.prev('.pulsegrid-section-item');
            if ($prev.length) {
                $section.insertBefore($prev);
                updateSectionNumbers();
            }
        });
        
        // Move section down
        $(document).on('click', '.pulsegrid-move-down', function() {
            var $section = $(this).closest('.pulsegrid-section-item');
            var $next = $section.next('.pulsegrid-section-item');
            if ($next.length) {
                $section.insertAfter($next);
                updateSectionNumbers();
            }
        });
        
        // Update section numbers and indices
        function updateSectionNumbers() {
            $('.pulsegrid-section-item').each(function(index) {
                $(this).attr('data-index', index);
                $(this).find('h3').text('Sección ' + (index + 1));
                
                // Update input names
                $(this).find('input, select').each(function() {
                    var name = $(this).attr('name');
                    if (name) {
                        var newName = name.replace(/\[\d+\]/, '[' + index + ']');
                        $(this).attr('name', newName);
                    }
                });
            });
        }
    });
    </script>
    <?php
}

// Modificar posts por página para archivos de etiquetas y categorías
function pulsegrid_tag_posts_per_page($query) {
    if (!is_admin() && $query->is_main_query()) {
        if (is_tag() || is_category()) {
            $query->set('posts_per_page', 14);
        }

        if ($query->is_search()) {
            $query->set('post_type', 'post');
        }
    }
}
add_action('pre_get_posts', 'pulsegrid_tag_posts_per_page');

// Include license manager (preferir versión ofuscada si está disponible)
$__pg_lm_obf = get_template_directory() . '/inc/license-manager.obf.php';
if (file_exists($__pg_lm_obf)) {
    require_once $__pg_lm_obf;
} else {
    require_once get_template_directory() . '/inc/license-manager.php';
}

// Create Últimos Posts page on theme activation
function pulsegrid_create_ultimos_posts_page() {
    // Check if page already exists
    $existing_page = get_page_by_title('Últimos Posts');
    
    if (!$existing_page) {
        // Create the page
        $page_data = array(
            'post_title'    => 'Últimos Posts',
            'post_content'  => '<!-- Esta página mostrará automáticamente los últimos posts publicados -->',
            'post_status'   => 'publish',
            'post_type'     => 'page',
            'post_author'   => 1,
            'page_template' => 'template-ultimos-posts.php'
        );
        
        $page_id = wp_insert_post($page_data);
        
        // Add page description meta
        if ($page_id && !is_wp_error($page_id)) {
            update_post_meta($page_id, '_pulsegrid_page_description', 'Descubre los últimos posts publicados en nuestro sitio. Mantente al día con todo el contenido nuevo.');
        }
    }
}
add_action('after_switch_theme', 'pulsegrid_create_ultimos_posts_page');

// Customizer - Footer Settings
function pulsegrid_customize_register($wp_customize) {
    // Add PulseGrid Pro Panel
    $wp_customize->add_panel('pulsegrid_panel', array(
        'title'       => __('PulseGrid Pro', 'pulsegrid'),
        'description' => __('Configuración del tema PulseGrid Pro', 'pulsegrid'),
        'priority'    => 30,
    ));
    
    // Add Post Individuales Section
    $wp_customize->add_section('pulsegrid_single_posts_section', array(
        'title'    => __('Post Individuales', 'pulsegrid'),
        'panel'    => 'pulsegrid_panel',
        'priority' => 10,
    ));
    
    // Template Selection Setting
    $wp_customize->add_setting('pulsegrid_single_template', array(
        'default'           => 'simple',
        'sanitize_callback' => 'sanitize_text_field',
        'transport'         => 'refresh',
    ));
    
    $wp_customize->add_control('pulsegrid_single_template', array(
        'label'       => __('Plantilla', 'pulsegrid'),
        'description' => __('Selecciona el estilo de plantilla para los posts individuales.', 'pulsegrid'),
        'section'     => 'pulsegrid_single_posts_section',
        'type'        => 'select',
        'choices'     => array(
            'simple'   => __('Sencilla', 'pulsegrid'),
            'featured' => __('Destacada', 'pulsegrid'),
        ),
        'priority'    => 5,
    ));
    
    // Show Tags Setting
    $wp_customize->add_setting('pulsegrid_show_tags', array(
        'default'           => '1',
        'sanitize_callback' => 'absint',
        'transport'         => 'refresh',
    ));
    
    $wp_customize->add_control('pulsegrid_show_tags', array(
        'label'       => __('Mostrar Etiquetas', 'pulsegrid'),
        'description' => __('Muestra u oculta la sección de etiquetas en los posts.', 'pulsegrid'),
        'section'     => 'pulsegrid_single_posts_section',
        'type'        => 'checkbox',
        'priority'    => 10,
    ));
    
    // Tags Title Setting
    $wp_customize->add_setting('pulsegrid_tags_title', array(
        'default'           => 'Etiquetas',
        'sanitize_callback' => 'sanitize_text_field',
        'transport'         => 'refresh',
    ));

    $wp_customize->add_control('pulsegrid_tags_title', array(
        'label'       => __('Título de Etiquetas', 'pulsegrid'),
        'description' => __('Personaliza el título que aparece en la sección de etiquetas.', 'pulsegrid'),
        'section'     => 'pulsegrid_single_posts_section',
        'type'        => 'text',
        'priority'    => 20,
    ));

    // Tags Type Setting
    $wp_customize->add_setting('pulsegrid_tags_type', array(
        'default'           => 'tags',
        'sanitize_callback' => 'sanitize_text_field',
        'transport'         => 'refresh',
    ));

    $wp_customize->add_control('pulsegrid_tags_type', array(
        'label'       => __('Tipo de Etiquetas', 'pulsegrid'),
        'description' => __('Selecciona qué tipo de contenido mostrar en la sección de etiquetas.', 'pulsegrid'),
        'section'     => 'pulsegrid_single_posts_section',
        'type'        => 'select',
        'choices'     => array(
            'tags'      => __('Etiquetas', 'pulsegrid'),
            'categories'=> __('Categorías', 'pulsegrid'),
        ),
        'priority'    => 30,
    ));

    // Show Related Posts Setting
    $wp_customize->add_setting('pulsegrid_show_related', array(
        'default'           => '1',
        'sanitize_callback' => 'absint',
        'transport'         => 'refresh',
    ));

    $wp_customize->add_control('pulsegrid_show_related', array(
        'label'       => __('Mostrar Posts Relacionados', 'pulsegrid'),
        'description' => __('Muestra u oculta la sección de posts relacionados.', 'pulsegrid'),
        'section'     => 'pulsegrid_single_posts_section',
        'type'        => 'checkbox',
        'priority'    => 40,
    ));

    // Related Posts Title Setting
    $wp_customize->add_setting('pulsegrid_related_title', array(
        'default'           => 'Podría Interesarte',
        'sanitize_callback' => 'sanitize_text_field',
        'transport'         => 'refresh',
    ));

    $wp_customize->add_control('pulsegrid_related_title', array(
        'label'       => __('Título de Posts Relacionados', 'pulsegrid'),
        'description' => __('Personaliza el título que aparece en la sección de posts relacionados.', 'pulsegrid'),
        'section'     => 'pulsegrid_single_posts_section',
        'type'        => 'text',
        'priority'    => 50,
    ));

    // Related Posts Type Setting
    $wp_customize->add_setting('pulsegrid_related_type', array(
        'default'           => 'category',
        'sanitize_callback' => 'sanitize_text_field',
        'transport'         => 'refresh',
    ));

    $wp_customize->add_control('pulsegrid_related_type', array(
        'label'       => __('Mostrar Posts Relacionados Por', 'pulsegrid'),
        'description' => __('Selecciona cómo se mostrarán los posts relacionados.', 'pulsegrid'),
        'section'     => 'pulsegrid_single_posts_section',
        'type'        => 'select',
        'choices'     => array(
            'category' => __('Categoría', 'pulsegrid'),
            'tag'      => __('Etiquetas', 'pulsegrid'),
        ),
        'priority'    => 60,
    ));

    // Show Comments Setting
    $wp_customize->add_setting('pulsegrid_show_comments', array(
        'default'           => '1',
        'sanitize_callback' => 'absint',
        'transport'         => 'refresh',
    ));

    $wp_customize->add_control('pulsegrid_show_comments', array(
        'label'       => __('Mostrar Comentarios', 'pulsegrid'),
        'description' => __('Muestra u oculta la sección de comentarios en los posts.', 'pulsegrid'),
        'section'     => 'pulsegrid_single_posts_section',
        'type'        => 'checkbox',
        'priority'    => 70,
    ));
    
    // Add Páginas Section
    $wp_customize->add_section('pulsegrid_pages_section', array(
        'title'    => __('Páginas', 'pulsegrid'),
        'panel'    => 'pulsegrid_panel',
        'priority' => 20,
    ));
    
    // Show Page Title Setting
    $wp_customize->add_setting('pulsegrid_show_page_title', array(
        'default'           => '1',
        'sanitize_callback' => 'absint',
        'transport'         => 'refresh',
    ));
    
    $wp_customize->add_control('pulsegrid_show_page_title', array(
        'label'       => __('Mostrar Título de la Página', 'pulsegrid'),
        'description' => __('Muestra u oculta el título en las páginas.', 'pulsegrid'),
        'section'     => 'pulsegrid_pages_section',
        'type'        => 'checkbox',
        'priority'    => 10,
    ));
    
    // Add Footer Section
    $wp_customize->add_section('pulsegrid_footer_section', array(
        'title'    => __('Footer Settings', 'pulsegrid'),
        'panel'    => 'pulsegrid_panel',
        'priority' => 40,
    ));
    
    // Footer Description
    $wp_customize->add_setting('pulsegrid_footer_description', array(
        'default'           => 'PulseGrid - Tu portal de descarga de juegos favorito.',
        'sanitize_callback' => 'sanitize_textarea_field',
        'transport'         => 'refresh',
    ));
    
    $wp_customize->add_control('pulsegrid_footer_description', array(
        'label'       => __('Descripción del Footer', 'pulsegrid'),
        'description' => __('Texto descriptivo que aparecerá en el footer del sitio.', 'pulsegrid'),
        'section'     => 'pulsegrid_footer_section',
        'type'        => 'textarea',
        'priority'    => 10,
    ));
    
    // Footer Copyright
    $wp_customize->add_setting('pulsegrid_footer_copyright', array(
        'default'           => '© 2026 PulseGrid. Todos los derechos reservados.',
        'sanitize_callback' => 'wp_kses_post',
        'transport'         => 'refresh',
    ));
    
    $wp_customize->add_control('pulsegrid_footer_copyright', array(
        'label'       => __('Copyright', 'pulsegrid'),
        'description' => __('Texto de copyright que aparecerá en el footer.', 'pulsegrid'),
        'section'     => 'pulsegrid_footer_section',
        'type'        => 'text',
        'priority'    => 20,
    ));
}
add_action('customize_register', 'pulsegrid_customize_register');

// Add metabox for page comments control
function pulsegrid_add_page_metabox() {
    add_meta_box(
        'pulsegrid_page_comments',
        __('Configuración de Comentarios', 'pulsegrid'),
        'pulsegrid_page_comments_callback',
        'page',
        'side',
        'default'
    );
}
add_action('add_meta_boxes', 'pulsegrid_add_page_metabox');

// Metabox callback
function pulsegrid_page_comments_callback($post) {
    wp_nonce_field('pulsegrid_page_comments_nonce', 'pulsegrid_page_comments_nonce_field');
    $value = get_post_meta($post->ID, '_pulsegrid_enable_comments', true);
    ?>
    <label for="pulsegrid_enable_comments">
        <input type="checkbox" name="pulsegrid_enable_comments" id="pulsegrid_enable_comments" value="1" <?php checked($value, '1'); ?>>
        <?php _e('Activar comentarios en esta página', 'pulsegrid'); ?>
    </label>
    <p class="description"><?php _e('Marca esta casilla para permitir comentarios en esta página específica.', 'pulsegrid'); ?></p>
    <?php
}

// Save metabox data
function pulsegrid_save_page_comments($post_id) {
    if (!isset($_POST['pulsegrid_page_comments_nonce_field'])) {
        return;
    }
    
    if (!wp_verify_nonce($_POST['pulsegrid_page_comments_nonce_field'], 'pulsegrid_page_comments_nonce')) {
        return;
    }
    
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
    }
    
    if (!current_user_can('edit_page', $post_id)) {
        return;
    }
    
    $value = isset($_POST['pulsegrid_enable_comments']) ? '1' : '0';
    update_post_meta($post_id, '_pulsegrid_enable_comments', $value);
}
add_action('save_post_page', 'pulsegrid_save_page_comments');

// ============================================
// TMDB Movie/Series Metadata for Posts
// ============================================

// Add metaboxes for movie/series data
function pulsegrid_add_tmdb_metaboxes() {
    add_meta_box(
        'pulsegrid_tmdb_synopsis',
        __('Sinopsis', 'pulsegrid'),
        'pulsegrid_tmdb_synopsis_callback',
        'post',
        'normal',
        'high'
    );
    
    add_meta_box(
        'pulsegrid_tmdb_details',
        __('Detalles de Película/Serie (TMDB)', 'pulsegrid'),
        'pulsegrid_tmdb_details_callback',
        'post',
        'normal',
        'high'
    );

    add_meta_box(
        'pulsegrid_tmdb_idiomas',
        __('Idiomas', 'pulsegrid'),
        'pulsegrid_tmdb_idiomas_callback',
        'post',
        'side',
        'default'
    );
}
add_action('add_meta_boxes', 'pulsegrid_add_tmdb_metaboxes');

function pulsegrid_reposition_idiomas_metabox() {
    $screen = get_current_screen();
    if (!$screen || !in_array($screen->base, array('post', 'post-new'), true) || $screen->post_type !== 'post') {
        return;
    }
    ?>
    <script>
    jQuery(function($) {
        var $idiomas = $('#pulsegrid_tmdb_idiomas');
        var $categories = $('#categorydiv');
        if ($idiomas.length && $categories.length) {
            $idiomas.insertAfter($categories);
        }
    });
    </script>
    <?php
}
add_action('admin_footer-post.php', 'pulsegrid_reposition_idiomas_metabox');
add_action('admin_footer-post-new.php', 'pulsegrid_reposition_idiomas_metabox');

// Synopsis Metabox Callback
function pulsegrid_tmdb_synopsis_callback($post) {
    wp_nonce_field('pulsegrid_save_tmdb', 'pulsegrid_tmdb_synopsis_nonce');
    $synopsis = get_post_meta($post->ID, '_tmdb_synopsis', true);
    ?>
    <p class="description"><?php _e('La sinopsis se mostrará al inicio del post, antes del contenido principal.', 'pulsegrid'); ?></p>
    <textarea name="tmdb_synopsis" rows="6" style="width:100%;padding:8px;font-size:14px;"><?php echo esc_textarea($synopsis); ?></textarea>
    <?php
}

// Idiomas Metabox Callback (sidebar, below categories)
function pulsegrid_tmdb_idiomas_callback($post) {
    $idioma = get_post_meta($post->ID, '_tmdb_idioma', true);
    $idiomas_disponibles = array('Español', 'Latino', 'Japonés');
    $idiomas_seleccionados = is_array($idioma) ? $idioma : (!empty($idioma) ? array($idioma) : array());
    ?>
    <p class="description"><?php _e('Selecciona uno o más idiomas.', 'pulsegrid'); ?></p>
    <div class="pulsegrid-idiomas-checkboxes" style="display: flex; flex-direction: column; gap: 8px; margin-top: 8px;">
        <?php foreach ($idiomas_disponibles as $lang) :
            $checked = in_array($lang, $idiomas_seleccionados, true) ? 'checked' : '';
        ?>
            <label style="display: flex; align-items: center; gap: 6px; cursor: pointer;">
                <input type="checkbox" name="tmdb_idioma[]" value="<?php echo esc_attr($lang); ?>" <?php echo $checked; ?>>
                <?php echo esc_html($lang); ?>
            </label>
        <?php endforeach; ?>
    </div>
    <?php
}

// TMDB Details Metabox Callback
function pulsegrid_tmdb_details_callback($post) {
    wp_nonce_field('pulsegrid_save_tmdb', 'pulsegrid_tmdb_nonce');
    
    $tmdb_type = get_post_meta($post->ID, '_tmdb_type', true);
    $tmdb_id = get_post_meta($post->ID, '_tmdb_id', true);
    $rating = get_post_meta($post->ID, '_tmdb_rating', true);
    $runtime = get_post_meta($post->ID, '_tmdb_runtime', true);
    $seasons = get_post_meta($post->ID, '_tmdb_seasons', true);
    $episodes = get_post_meta($post->ID, '_tmdb_episodes', true);
    $director = get_post_meta($post->ID, '_tmdb_director', true);
    $cast = get_post_meta($post->ID, '_tmdb_cast', true);
    $trailer = get_post_meta($post->ID, '_tmdb_trailer', true);
    $backdrop = get_post_meta($post->ID, '_tmdb_backdrop', true);
    $calidad = get_post_meta($post->ID, '_tmdb_calidad', true);
    ?>
    <style>
        .pulsegrid-tmdb-row{margin-bottom:15px}
        .pulsegrid-tmdb-row label{display:block;font-weight:600;margin-bottom:5px}
        .pulsegrid-tmdb-row input,.pulsegrid-tmdb-row select,.pulsegrid-tmdb-row textarea{width:100%;padding:8px}
        .pulsegrid-tmdb-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:15px}
        .pulsegrid-tmdb-grid-2{display:grid;grid-template-columns:repeat(2,1fr);gap:15px}
    </style>
    
    <div class="pulsegrid-tmdb-grid">
        <div class="pulsegrid-tmdb-row">
            <label><?php _e('Tipo de Contenido', 'pulsegrid'); ?></label>
            <select name="tmdb_type">
                <option value=""><?php _e('Seleccionar', 'pulsegrid'); ?></option>
                <option value="movie" <?php selected($tmdb_type, 'movie'); ?>><?php _e('Película', 'pulsegrid'); ?></option>
                <option value="tv" <?php selected($tmdb_type, 'tv'); ?>><?php _e('Serie', 'pulsegrid'); ?></option>
            </select>
        </div>
        <div class="pulsegrid-tmdb-row">
            <label><?php _e('TMDB ID', 'pulsegrid'); ?></label>
            <input type="text" name="tmdb_id" value="<?php echo esc_attr($tmdb_id); ?>" placeholder="Ej: 12345">
            <p class="description">ID de TMDB. Puedes añadirlo manualmente o dejar que el plugin lo rellene automáticamente.</p>
        </div>
        <div class="pulsegrid-tmdb-row">
            <label><?php _e('Calificación (0-10)', 'pulsegrid'); ?></label>
            <input type="number" name="tmdb_rating" value="<?php echo esc_attr($rating); ?>" min="0" max="10" step="0.1">
        </div>
    </div>
    
    <div class="pulsegrid-tmdb-grid-2">
        <div class="pulsegrid-tmdb-row">
            <label><?php _e('Calidad', 'pulsegrid'); ?></label>
            <select name="tmdb_calidad" id="tmdb_calidad_select">
                <option value=""><?php _e('Seleccionar', 'pulsegrid'); ?></option>
                <option value="CAM" <?php selected($calidad, 'CAM'); ?>>CAM</option>
                <option value="TS" <?php selected($calidad, 'TS'); ?>>TS</option>
                <option value="DVDRip" <?php selected($calidad, 'DVDRip'); ?>>DVDRip</option>
                <option value="HD" <?php selected($calidad, 'HD'); ?>>HD</option>
                <option value="Full HD" <?php selected($calidad, 'Full HD'); ?>>Full HD</option>
                <option value="720p" <?php selected($calidad, '720p'); ?>>720p</option>
                <option value="1080p" <?php selected($calidad, '1080p'); ?>>1080p</option>
                <option value="4K" <?php selected($calidad, '4K'); ?>>4K</option>
                <option value="BluRay" <?php selected($calidad, 'BluRay'); ?>>BluRay</option>
                <option value="custom" <?php selected($calidad, 'custom'); ?>>Personalizada</option>
            </select>
        </div>
        <div class="pulsegrid-tmdb-row">
            <label><?php _e('Duración (min)', 'pulsegrid'); ?></label>
            <input type="number" name="tmdb_runtime" value="<?php echo esc_attr($runtime); ?>">
        </div>
    </div>

    <div class="pulsegrid-tmdb-row" id="custom_quality_row" style="display: none;">
        <label><?php _e('Calidad Personalizada', 'pulsegrid'); ?></label>
        <input type="text" name="tmdb_calidad_custom" id="tmdb_calidad_custom" value="<?php echo esc_attr(get_post_meta($post->ID, '_tmdb_calidad_custom', true)); ?>" placeholder="Ej: WEB-DL, HDTV, etc.">
    </div>
    <script>
    jQuery(document).ready(function($) {
        function toggleCustomQuality() {
            if ($('#tmdb_calidad_select').val() === 'custom') {
                $('#custom_quality_row').show();
            } else {
                $('#custom_quality_row').hide();
            }
        }

        toggleCustomQuality();
        $('#tmdb_calidad_select').on('change', toggleCustomQuality);
    });
    </script>
    
    <div class="pulsegrid-tmdb-grid-2">
        <div class="pulsegrid-tmdb-row">
            <label><?php _e('Temporadas (Series)', 'pulsegrid'); ?></label>
            <input type="number" name="tmdb_seasons" value="<?php echo esc_attr($seasons); ?>">
        </div>
        <div class="pulsegrid-tmdb-row">
            <label><?php _e('Episodios (Series)', 'pulsegrid'); ?></label>
            <input type="number" name="tmdb_episodes" value="<?php echo esc_attr($episodes); ?>">
        </div>
    </div>
    
    <div class="pulsegrid-tmdb-row">
        <label><?php _e('Número de Episodio', 'pulsegrid'); ?></label>
        <input type="text" name="tmdb_episode_number" value="<?php echo esc_attr(get_post_meta($post->ID, '_tmdb_episode_number', true)); ?>" placeholder="Ej: 1x13, 2x3, 1x20">
        <p class="description">Formato: Temporada x Episodio (Ej: 1x13, 2x3)</p>
    </div>
    
    <div class="pulsegrid-tmdb-row">
        <label style="display: block; margin-bottom: 5px;">
            <input type="checkbox" name="pulsegrid_exclude_from_latest" value="1" style="width: 16px; height: 16px; margin: 0 5px 0 0; vertical-align: middle;" <?php checked(get_post_meta($post->ID, '_pulsegrid_exclude_from_latest', true), '1'); ?>>
            <?php _e('Ocultar de "Últimos Posts"', 'pulsegrid'); ?>
        </label>
        <p class="description" style="margin-left: 21px;">Marca esta opción para que este post no aparezca en la página de Últimos Posts.</p>
    </div>
    
    <div class="pulsegrid-tmdb-row">
        <label><?php _e('Director/Creador', 'pulsegrid'); ?></label>
        <input type="text" name="tmdb_director" value="<?php echo esc_attr($director); ?>">
    </div>
    
    <div class="pulsegrid-tmdb-row">
        <label><?php _e('Reparto', 'pulsegrid'); ?></label>
        <textarea name="tmdb_cast" rows="2"><?php echo esc_textarea($cast); ?></textarea>
    </div>
    
    <div class="pulsegrid-tmdb-row">
        <label><?php _e('Trailer (YouTube URL)', 'pulsegrid'); ?></label>
        <input type="url" name="tmdb_trailer" value="<?php echo esc_url($trailer); ?>" placeholder="https://youtube.com/watch?v=...">
    </div>
    
    <div class="pulsegrid-tmdb-row">
        <label><?php _e('Backdrop URL', 'pulsegrid'); ?></label>
        <input type="url" name="tmdb_backdrop" value="<?php echo esc_url($backdrop); ?>" placeholder="https://image.tmdb.org/t/p/original/...">
        <p class="description">URL de la imagen de fondo. Puedes añadirla manualmente o dejar que el plugin la rellene automáticamente.</p>
    </div>
    <?php
}


// Save TMDB Metadata
function pulsegrid_save_tmdb_meta($post_id) {
    if (!isset($_POST['pulsegrid_tmdb_nonce']) || !wp_verify_nonce($_POST['pulsegrid_tmdb_nonce'], 'pulsegrid_save_tmdb')) return;
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if (!current_user_can('edit_post', $post_id)) return;
    
    // Save synopsis
    if (isset($_POST['tmdb_synopsis'])) {
        update_post_meta($post_id, '_tmdb_synopsis', wp_kses_post($_POST['tmdb_synopsis']));
    }
    
    // Save basic fields
    $fields = array('tmdb_type', 'tmdb_id', 'tmdb_rating', 'tmdb_runtime', 'tmdb_seasons', 'tmdb_episodes', 'tmdb_episode_number', 'tmdb_director', 'tmdb_cast', 'tmdb_trailer', 'tmdb_backdrop', 'tmdb_calidad', 'tmdb_calidad_custom');
    
    foreach ($fields as $field) {
        if (isset($_POST[$field])) {
            $value = $_POST[$field];
            if (strpos($field, 'url') !== false || strpos($field, 'trailer') !== false || strpos($field, 'backdrop') !== false) {
                $value = esc_url_raw($value);
            } else {
                $value = sanitize_text_field($value);
            }
            update_post_meta($post_id, '_' . $field, $value);
        }
    }
    
    // Save idioma as array
    if (isset($_POST['tmdb_idioma']) && is_array($_POST['tmdb_idioma'])) {
        $idiomas = array_map('sanitize_text_field', $_POST['tmdb_idioma']);
        update_post_meta($post_id, '_tmdb_idioma', $idiomas);
    } else {
        update_post_meta($post_id, '_tmdb_idioma', array());
    }
    
    // Save exclude from latest posts option
    if (isset($_POST['pulsegrid_exclude_from_latest'])) {
        update_post_meta($post_id, '_pulsegrid_exclude_from_latest', '1');
    } else {
        delete_post_meta($post_id, '_pulsegrid_exclude_from_latest');
    }
}
add_action('save_post_post', 'pulsegrid_save_tmdb_meta');

// Function to display TMDB badges on thumbnails
function pulsegrid_get_tmdb_badges($post_id = null) {
    if (!$post_id) {
        $post_id = get_the_ID();
    }
    
    $calidad = get_post_meta($post_id, '_tmdb_calidad', true);
    $calidad_custom = get_post_meta($post_id, '_tmdb_calidad_custom', true);
    $rating = get_post_meta($post_id, '_tmdb_rating', true);
    $idioma = get_post_meta($post_id, '_tmdb_idioma', true);
    
    // Use custom quality if "custom" is selected and custom value exists
    $display_calidad = ($calidad === 'custom' && !empty($calidad_custom)) ? $calidad_custom : $calidad;
    
    if (empty($display_calidad) && empty($rating) && empty($idioma)) {
        return '';
    }
    
    $badges = '<div class="pulsegrid-tmdb-badges">';
    
    // Top badges (quality on left, rating on right)
    if (!empty($display_calidad) || !empty($rating)) {
        $badges .= '<div class="tmdb-badges-top">';
        
        // Quality on the left
        if (!empty($display_calidad)) {
            $badges .= '<span class="tmdb-badge tmdb-badge-quality">' . esc_html($display_calidad) . '</span>';
        } else {
            $badges .= '<span></span>'; // Empty span to maintain spacing
        }
        
        // Rating on the right
        if (!empty($rating)) {
            $badges .= '<span class="tmdb-badge tmdb-badge-rating">★ ' . esc_html($rating) . '</span>';
        }
        
        $badges .= '</div>';
    }
    
    // Bottom badge (languages with flags in single badge)
    if (!empty($idioma)) {
        $idiomas_array = is_array($idioma) ? $idioma : array($idioma);
        if (!empty($idiomas_array)) {
            $badges .= '<div class="tmdb-badges-bottom">';
            $badges .= '<span class="tmdb-badge tmdb-badge-language-unified">';
            
            $lang_map = array(
                'Español' => array('abbr' => 'CAS', 'flag' => 'español.svg'),
                'Latino' => array('abbr' => 'LAT', 'flag' => 'latino.svg'),
                'Japonés' => array('abbr' => 'JAP', 'flag' => 'japones.webp')
            );
            
            $lang_items = array();
            foreach ($idiomas_array as $lang) {
                if (isset($lang_map[$lang])) {
                    $flag_url = get_template_directory_uri() . '/flag/' . $lang_map[$lang]['flag'];
                    $lang_items[] = '<span class="language-item">' .
                                   '<img src="' . esc_url($flag_url) . '" alt="' . esc_attr($lang) . '" class="language-flag">' .
                                   '<span class="language-abbr">' . esc_html($lang_map[$lang]['abbr']) . '</span>' .
                                   '</span>';
                }
            }
            
            $badges .= implode(' · ', $lang_items);
            $badges .= '</span>';
            $badges .= '</div>';
        }
    }
    
    $badges .= '</div>';
    
    return $badges;
}

// Function to get post thumbnail with TMDB badges
function pulsegrid_post_thumbnail_with_badges($size = 'medium', $post_id = null) {
    if (!$post_id) {
        $post_id = get_the_ID();
    }
    
    if (has_post_thumbnail($post_id)) {
        echo '<div class="post-thumbnail-wrapper">';
        echo get_the_post_thumbnail($post_id, $size, array('class' => 'post-thumbnail'));
        echo pulsegrid_get_tmdb_badges($post_id);
        echo '</div>';
    } else {
        echo '<div class="post-thumbnail-wrapper">';
        echo '<div class="post-thumbnail no-image">';
        echo '<div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); width: 100%; height: 200px; display: flex; align-items: center; justify-content: center; color: white; font-size: 0.9rem;">Sin imagen</div>';
        echo '</div>';
        echo '</div>';
    }
}
?>
