<?php
/**
 * Custom Widgets for PulseGrid Pro
 */

// Widget: Más Populares (Most Popular Posts)
class PulseGrid_Popular_Posts_Widget extends WP_Widget {
    public function __construct() {
        parent::__construct(
            'pulsegrid_popular_posts',
            __('PulseGrid - Más Populares', 'pulsegrid'),
            array('description' => __('Muestra los posts más populares por vistas', 'pulsegrid'))
        );
    }

    public function widget($args, $instance) {
        echo '<div class="sidebar-widget pulsegrid-popular-widget">';
        
        $title = !empty($instance['title']) ? $instance['title'] : __('Más Populares', 'pulsegrid');
        echo '<h3 class="widget-title pulsegrid-widget-title">' . esc_html($title) . '</h3>';

        $number = !empty($instance['number']) ? absint($instance['number']) : 4;
        $time_period = !empty($instance['time_period']) ? $instance['time_period'] : 'all';

        // Build date query based on time period
        $date_query = array();
        if ($time_period !== 'all') {
            $date_query = array(
                array(
                    'after' => $time_period,
                    'inclusive' => true,
                ),
            );
        }

        $query_args = array(
            'posts_per_page' => $number,
            'post_status' => 'publish',
            'orderby' => 'comment_count',
            'order' => 'DESC',
            'ignore_sticky_posts' => true,
            'meta_query' => array(
                'relation' => 'OR',
                array(
                    'key' => '_pulsegrid_exclude_from_latest',
                    'compare' => 'NOT EXISTS'
                ),
                array(
                    'key' => '_pulsegrid_exclude_from_latest',
                    'value' => '1',
                    'compare' => '!='
                )
            )
        );

        if (!empty($date_query)) {
            $query_args['date_query'] = $date_query;
        }

        $popular_posts = new WP_Query($query_args);

        if ($popular_posts->have_posts()) {
            echo '<div class="pulsegrid-posts-grid">';
            while ($popular_posts->have_posts()) {
                $popular_posts->the_post();
                echo '<div class="pulsegrid-post-card">';
                echo '<a href="' . get_permalink() . '">';
                
                // Thumbnail with badges
                if (has_post_thumbnail()) {
                    echo '<div class="pulsegrid-post-thumb">';
                    echo pulsegrid_post_thumbnail_with_badges('medium', get_the_ID());
                    echo '</div>';
                }
                
                // Title
                echo '<h4 class="pulsegrid-post-title">' . get_the_title() . '</h4>';
                echo '</a>';
                echo '</div>';
            }
            echo '</div>';
            wp_reset_postdata();
        }

        echo '</div>';
    }

    public function form($instance) {
        $title = !empty($instance['title']) ? $instance['title'] : __('Más Populares', 'pulsegrid');
        $number = !empty($instance['number']) ? absint($instance['number']) : 5;
        $time_period = !empty($instance['time_period']) ? $instance['time_period'] : 'all';
        ?>
        <p>
            <label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Título:', 'pulsegrid'); ?></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>
        <p>
            <label for="<?php echo $this->get_field_id('number'); ?>"><?php _e('Número de posts:', 'pulsegrid'); ?></label>
            <input class="tiny-text" id="<?php echo $this->get_field_id('number'); ?>" name="<?php echo $this->get_field_name('number'); ?>" type="number" step="1" min="1" value="<?php echo $number; ?>" size="3">
        </p>
        <p>
            <label for="<?php echo $this->get_field_id('time_period'); ?>"><?php _e('Período de tiempo:', 'pulsegrid'); ?></label>
            <select class="widefat" id="<?php echo $this->get_field_id('time_period'); ?>" name="<?php echo $this->get_field_name('time_period'); ?>">
                <option value="all" <?php selected($time_period, 'all'); ?>><?php _e('Todo el tiempo', 'pulsegrid'); ?></option>
                <option value="1 day ago" <?php selected($time_period, '1 day ago'); ?>><?php _e('Último día', 'pulsegrid'); ?></option>
                <option value="1 week ago" <?php selected($time_period, '1 week ago'); ?>><?php _e('Última semana', 'pulsegrid'); ?></option>
                <option value="1 month ago" <?php selected($time_period, '1 month ago'); ?>><?php _e('Último mes', 'pulsegrid'); ?></option>
            </select>
        </p>
        <?php
    }

    public function update($new_instance, $old_instance) {
        $instance = array();
        $instance['title'] = (!empty($new_instance['title'])) ? sanitize_text_field($new_instance['title']) : '';
        $instance['number'] = (!empty($new_instance['number'])) ? absint($new_instance['number']) : 5;
        $instance['time_period'] = (!empty($new_instance['time_period'])) ? sanitize_text_field($new_instance['time_period']) : 'all';
        return $instance;
    }
}

// Widget: Buscador (Search)
class PulseGrid_Search_Widget extends WP_Widget {
    public function __construct() {
        parent::__construct(
            'pulsegrid_search',
            __('PulseGrid - Buscador', 'pulsegrid'),
            array('description' => __('Formulario de búsqueda personalizado', 'pulsegrid'))
        );
    }

    public function widget($args, $instance) {
        echo '<div class="sidebar-widget pulsegrid-search-widget">';
        
        $title = !empty($instance['title']) ? $instance['title'] : __('Buscar', 'pulsegrid');
        echo '<h3 class="widget-title pulsegrid-widget-title">' . esc_html($title) . '</h3>';
        ?>
        <form role="search" method="get" class="pulsegrid-search-form" action="<?php echo home_url('/'); ?>">
            <div class="search-input-group">
                <input type="search" class="pulsegrid-search-input" placeholder="<?php echo esc_attr_x('Buscar contenido...', 'placeholder', 'pulsegrid'); ?>" value="<?php echo get_search_query(); ?>" name="s" />
                <button type="submit" class="pulsegrid-search-button">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <circle cx="11" cy="11" r="8"></circle>
                        <path d="m21 21-4.35-4.35"></path>
                    </svg>
                </button>
            </div>
        </form>
        <?php
        echo '</div>';
    }

    public function form($instance) {
        $title = !empty($instance['title']) ? $instance['title'] : __('Buscar', 'pulsegrid');
        ?>
        <p>
            <label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Título:', 'pulsegrid'); ?></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 = array();
        $instance['title'] = (!empty($new_instance['title'])) ? sanitize_text_field($new_instance['title']) : '';
        return $instance;
    }
}

// Widget: Últimos Comentarios (Recent Comments)
class PulseGrid_Recent_Comments_Widget extends WP_Widget {
    public function __construct() {
        parent::__construct(
            'pulsegrid_recent_comments',
            __('PulseGrid - Últimos Comentarios', 'pulsegrid'),
            array('description' => __('Muestra los comentarios más recientes', 'pulsegrid'))
        );
    }

    public function widget($args, $instance) {
        echo '<div class="sidebar-widget pulsegrid-comments-widget">';
        
        $title = !empty($instance['title']) ? $instance['title'] : __('Últimos Comentarios', 'pulsegrid');
        echo '<h3 class="widget-title pulsegrid-widget-title">' . esc_html($title) . '</h3>';

        $number = !empty($instance['number']) ? absint($instance['number']) : 5;

        $comments = get_comments(array(
            'number' => $number,
            'status' => 'approve',
            'post_status' => 'publish'
        ));

        if ($comments) {
            echo '<div class="pulsegrid-comments-list">';
            foreach ($comments as $comment) {
                $comment_excerpt = wp_trim_words($comment->comment_content, 15, '...');
                $avatar = get_avatar($comment, 50, '', '', array('class' => 'comment-avatar'));
                
                echo '<div class="pulsegrid-comment-item">';
                echo '<div class="comment-avatar-wrapper">' . $avatar . '</div>';
                echo '<div class="comment-content-wrapper">';
                echo '<div class="comment-author">' . esc_html($comment->comment_author) . '</div>';
                echo '<div class="comment-excerpt">' . esc_html($comment_excerpt) . '</div>';
                echo '<a href="' . get_comment_link($comment) . '" class="comment-post-link">';
                echo '→ ' . get_the_title($comment->comment_post_ID);
                echo '</a>';
                echo '</div>';
                echo '</div>';
            }
            echo '</div>';
        }

        echo '</div>';
    }

    public function form($instance) {
        $title = !empty($instance['title']) ? $instance['title'] : __('Últimos Comentarios', 'pulsegrid');
        $number = !empty($instance['number']) ? absint($instance['number']) : 5;
        ?>
        <p>
            <label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Título:', 'pulsegrid'); ?></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>
        <p>
            <label for="<?php echo $this->get_field_id('number'); ?>"><?php _e('Número de comentarios:', 'pulsegrid'); ?></label>
            <input class="tiny-text" id="<?php echo $this->get_field_id('number'); ?>" name="<?php echo $this->get_field_name('number'); ?>" type="number" step="1" min="1" value="<?php echo $number; ?>" size="3">
        </p>
        <?php
    }

    public function update($new_instance, $old_instance) {
        $instance = array();
        $instance['title'] = (!empty($new_instance['title'])) ? sanitize_text_field($new_instance['title']) : '';
        $instance['number'] = (!empty($new_instance['number'])) ? absint($new_instance['number']) : 5;
        return $instance;
    }
}

// Widget: Posts Recientes (Recent Posts)
class PulseGrid_Recent_Posts_Widget extends WP_Widget {
    public function __construct() {
        parent::__construct(
            'pulsegrid_recent_posts',
            __('PulseGrid - Posts Recientes', 'pulsegrid'),
            array('description' => __('Muestra los posts más recientes', 'pulsegrid'))
        );
    }

    public function widget($args, $instance) {
        echo '<div class="sidebar-widget pulsegrid-recent-widget">';
        
        $title = !empty($instance['title']) ? $instance['title'] : __('Posts Recientes', 'pulsegrid');
        echo '<h3 class="widget-title pulsegrid-widget-title">' . esc_html($title) . '</h3>';

        $number = !empty($instance['number']) ? absint($instance['number']) : 4;

        $recent_posts = new WP_Query(array(
            'posts_per_page' => $number,
            'post_status' => 'publish',
            'ignore_sticky_posts' => true,
            'meta_query' => array(
                'relation' => 'OR',
                array(
                    'key' => '_pulsegrid_exclude_from_latest',
                    'compare' => 'NOT EXISTS'
                ),
                array(
                    'key' => '_pulsegrid_exclude_from_latest',
                    'value' => '1',
                    'compare' => '!='
                )
            )
        ));

        if ($recent_posts->have_posts()) {
            echo '<div class="pulsegrid-posts-grid">';
            while ($recent_posts->have_posts()) {
                $recent_posts->the_post();
                echo '<div class="pulsegrid-post-card">';
                echo '<a href="' . get_permalink() . '">';
                
                // Thumbnail with badges
                if (has_post_thumbnail()) {
                    echo '<div class="pulsegrid-post-thumb">';
                    echo pulsegrid_post_thumbnail_with_badges('medium', get_the_ID());
                    echo '</div>';
                }
                
                // Title
                echo '<h4 class="pulsegrid-post-title">' . get_the_title() . '</h4>';
                echo '</a>';
                echo '</div>';
            }
            echo '</div>';
            wp_reset_postdata();
        }

        echo '</div>';
    }

    public function form($instance) {
        $title = !empty($instance['title']) ? $instance['title'] : __('Posts Recientes', 'pulsegrid');
        $number = !empty($instance['number']) ? absint($instance['number']) : 5;
        ?>
        <p>
            <label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Título:', 'pulsegrid'); ?></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>
        <p>
            <label for="<?php echo $this->get_field_id('number'); ?>"><?php _e('Número de posts:', 'pulsegrid'); ?></label>
            <input class="tiny-text" id="<?php echo $this->get_field_id('number'); ?>" name="<?php echo $this->get_field_name('number'); ?>" type="number" step="1" min="1" value="<?php echo $number; ?>" size="3">
        </p>
        <?php
    }

    public function update($new_instance, $old_instance) {
        $instance = array();
        $instance['title'] = (!empty($new_instance['title'])) ? sanitize_text_field($new_instance['title']) : '';
        $instance['number'] = (!empty($new_instance['number'])) ? absint($new_instance['number']) : 5;
        return $instance;
    }
}

// Widget: Etiquetas (Tags Cloud)
class PulseGrid_Tags_Widget extends WP_Widget {
    public function __construct() {
        parent::__construct(
            'pulsegrid_tags',
            __('PulseGrid - Etiquetas', 'pulsegrid'),
            array('description' => __('Muestra una nube de etiquetas', 'pulsegrid'))
        );
    }

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

        $tags = get_tags(array(
            'orderby' => 'count',
            'order' => 'DESC',
            'number' => 30
        ));

        if ($tags) {
            echo '<div class="tagcloud">';
            foreach ($tags as $tag) {
                $tag_link = get_tag_link($tag->term_id);
                echo '<a href="' . esc_url($tag_link) . '" class="tag-cloud-link tag-link-' . $tag->term_id . '" style="font-size: ' . (12 + ($tag->count * 2)) . 'px;">';
                echo esc_html($tag->name);
                echo '</a> ';
            }
            echo '</div>';
        }

        echo $args['after_widget'];
    }

    public function form($instance) {
        $title = !empty($instance['title']) ? $instance['title'] : __('Etiquetas', 'pulsegrid');
        ?>
        <p>
            <label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Título:', 'pulsegrid'); ?></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 = array();
        $instance['title'] = (!empty($new_instance['title'])) ? sanitize_text_field($new_instance['title']) : '';
        return $instance;
    }
}

// Unregister Default WordPress Widgets
function pulsegrid_unregister_default_widgets() {
    unregister_widget('WP_Widget_Search');
    unregister_widget('WP_Widget_Recent_Posts');
    unregister_widget('WP_Widget_Recent_Comments');
    unregister_widget('WP_Widget_Tag_Cloud');
    unregister_widget('WP_Widget_Archives');
    unregister_widget('WP_Widget_Categories');
    unregister_widget('WP_Widget_Meta');
    unregister_widget('WP_Widget_Calendar');
    unregister_widget('WP_Widget_Pages');
    unregister_widget('WP_Widget_RSS');
    unregister_widget('WP_Widget_Text');
    unregister_widget('WP_Widget_Media_Audio');
    unregister_widget('WP_Widget_Media_Image');
    unregister_widget('WP_Widget_Media_Video');
    unregister_widget('WP_Widget_Media_Gallery');
    unregister_widget('WP_Widget_Custom_HTML');
    unregister_widget('WP_Nav_Menu_Widget');
}
add_action('widgets_init', 'pulsegrid_unregister_default_widgets', 11);

// Register Custom Widgets
function pulsegrid_register_custom_widgets() {
    register_widget('PulseGrid_Popular_Posts_Widget');
    register_widget('PulseGrid_Search_Widget');
    register_widget('PulseGrid_Recent_Comments_Widget');
    register_widget('PulseGrid_Recent_Posts_Widget');
    register_widget('PulseGrid_Tags_Widget');
}
add_action('widgets_init', 'pulsegrid_register_custom_widgets');
