<?php

namespace core_next;

class tagCloud extends \WP_Widget
{
    function __construct()
    {
        $img_html = Theme::getWidgetIcon();
        parent::__construct(
            'core_next_tag_cloud',
             'CoreNext标签云',
            array(
                'description' => '标签云，你懂得'
            )
        );
    }

    function form($instance)
    {
        $num = absint($instance['number'] ?? 20);
        $title = $instance['title'] ?? '标签云';
        $on_top = !empty($instance['on_top']) ? 'checked' : '';
        ?>
        <div class="widget-item">
            <div>工具标题</div>
            <input class="widefat" name="<?php echo esc_attr($this->get_field_name('title')); ?>"
                   type="text" value="<?php echo esc_attr($title); ?>"/>
        </div>
        <div class="widget-item">
            <div>显示标签数量</div>
            <input class="widefat" name="<?php echo esc_attr($this->get_field_name('number')); ?>"
                   type="text" value="<?php echo esc_attr($num); ?>"/>
        </div>
        <div class="widget-item">
            <span>跟随页面展示   <input class="widefat" type="checkbox"
                                        name="<?php echo $this->get_field_name('on_top'); ?>"
                <?php echo $on_top; ?>></span>
        </div>
        <?php
    }

    public function widget_start($args, $instance)
    {
        $on_top = !empty($instance['on_top']) ? 'checked' : '';
        $html = $args['before_widget'];
        if ($on_top !== '') {
            $html = str_replace('<div', Theme::getWidgetStickyStyle(), $html);
        }
        echo $html;
        $title = apply_filters('widget_title', $instance['title']);
        echo $args['before_title'] . $title . $args['after_title'];
    }

    public function widget_end($args)
    {
        echo $args['after_widget'];
    }

    function widget($args, $instance)
    {
        $num = absint($instance['number'] ?? 20);
        $this->widget_start($args, $instance);
        $tags = get_terms(array(
            'taxonomy' => 'post_tag',
            'order' => 'DESC',
            'number' => $num,
        ));
        echo '<div class="corenext-tag-list">';
        if (!empty($tags) && !is_wp_error($tags)) {
            foreach ($tags as $tag) {
                echo '<a class="tag-item" href="' . esc_url(get_term_link($tag)) . '">' . esc_html($tag->name) . '</a>';
            }
        }
        echo '</div>';
        $this->widget_end($args);

    }
}