<?php

namespace core_next;
class postList extends \WP_Widget
{
    function __construct()
    {
        $img_html = Theme::getWidgetIcon();
        parent::__construct(
            'core_next_post_list_widget',
            $img_html . 'CoreNext文章列表',
            array(
                'description' => '多功能文章列表小工具'
            )
        );
        add_action('widget_update_callback', [$this, 'updateWidgetCache'], 10, 2);

    }

    function updateCache()
    {

    }

    function updateWidgetCache($instance, $new_instance)
    {
        global $core_next_set;
        if ($core_next_set['widget_post_list_cache']) {
            $query = self::getPostQueryArr($new_instance);
            $post_query = Theme::Cache($this->id . '_query', function () use ($query) {
                return get_posts($query);
            }, true);
            Theme::Cache($this->id . '_post_list', function () use ($post_query) {
                $post_list = [];
                foreach ($post_query as $post) {
                    $post_list[] = WordPress::getWidgetPostMetaData($post);
                }
                return $post_list;
            }, true);
        }
        return $new_instance;
    }

    function form($instance)
    {
        $number = absint(isset($instance['number']) ? $instance['number'] : 5);
        $title = isset($instance['title']) ? $instance['title'] : '文章列表';
        $show_type = isset($instance['show_type']) ? $instance['show_type'] : 'random';
        $style = isset($instance['style']) ? $instance['style'] : 'first_img_text';
        $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($number); ?>"/>
        </div>
        <div class="widget-item">
            <div>排序方式</div>
            <select name="<?php echo $this->get_field_name('show_type'); ?>">
                <option value="new" <?php if ($show_type == 'new') echo 'selected' ?>>最新</option>
                <option value="view" <?php if ($show_type == 'view') echo 'selected' ?>>阅读量</option>
                <option value="comment" <?php if ($show_type == 'comment') echo 'selected' ?>>评论</option>
                <option value="like" <?php if ($show_type == 'like') echo 'selected' ?>>点赞</option>
                <option value="random" <?php if ($show_type == 'random') echo 'selected' ?>>随机</option>
            </select>
        </div>
        <div class="widget-item">
            <div>外观样式</div>
            <select name="<?php echo $this->get_field_name('style'); ?>">
                <option value="text" <?php if ($style == 'text') echo 'selected' ?>>文字</option>
                <option value="img_text" <?php if ($style == 'img_text') echo 'selected' ?>>图文列表</option>
                <option value="first_img_text" <?php if ($style == 'first_img_text') echo 'selected' ?>>首篇大图图文
                </option>
            </select>
        </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 getPostQueryArr($instance)
    {
        $show_type = $instance['show_type'] ?? 'random';
        $number = absint($instance['number'] ?? 5);
        $sticky = get_option('sticky_posts');

        if ($show_type === 'comment') {
            $query = array(
                'order' => 'DESC',
                'orderby' => 'comment_count',
                'numberposts' => $number,
                'exclude' => $sticky);
        } elseif ($show_type == 'view') {
            $query = array('order' => 'DESC', 'orderby' => 'meta_value_num', 'meta_key' => 'views',
                'numberposts' => $number, 'exclude' => $sticky);
        } elseif ($show_type == 'like') {
            $query = array('order' => 'DESC', 'orderby' => 'meta_value_num', 'meta_key' => 'cp_like',
                'numberposts' => $number, 'exclude' => $sticky);
        } elseif ($show_type == 'new') {
            $query = array('order' => 'DESC', 'orderby' => 'date',
                'numberposts' => $number, 'exclude' => $sticky);
        }
        else {
            $query = array('order' => 'DESC', 'orderby' => 'rand', 'numberposts' => $number, 'exclude' => $sticky);
        }
        return $query;
    }

    function widget($args, $instance)
    {
        global $core_next_set;
        $show_type = $instance['show_type'] ?? 'random';
        $this->widget_start($args, $instance);
        $style = $instance['style'] ?? 'first_img_text';
        $query = self::getPostQueryArr($instance);
        if ($core_next_set['widget_post_list_cache'] && $show_type !== 'random') {
            $post_query = Theme::Cache($this->id . '_query', function () use ($query) {
                return get_posts($query);
            });
            $post_list = Theme::Cache($this->id . '_post_list', function () use ($post_query) {
                $post_list = [];
                foreach ($post_query as $post) {
                    $post_list[] = WordPress::getWidgetPostMetaData($post);
                }
                return $post_list;
            });
        } else {
            $post_query = get_posts($query);
            $post_list = [];
            foreach ($post_query as $post) {
                $post_list[] = WordPress::getWidgetPostMetaData($post);
            }
        }
        if ($core_next_set['post_list_url_new_window']) {
            foreach ($post_list as &$item) {
                $item['target'] = '_blank';
            }
        } else {
            foreach ($post_list as &$item) {
                $item['target'] = 'self';
            }
        }
        $post_list = Theme::handleRandomThumbnail($post_list);
        if ($style == 'first_img_text') {
            $first_post = array_shift($post_list);
            echo '<div class="core-next-widget-post-list">';
            echo Template::getTemplateHtml('widget-post-list-first', $first_post);
            $i = 1;
            foreach ($post_list as $post) {
                $post['index'] = ++$i;
                echo Template::getTemplateHtml('widget-post-list', $post);
            }
            echo '</div>';
        } elseif ($style == 'img_text') {
            echo '<div class="core-next-widget-post-list">';
            $i = 0;
            foreach ($post_list as $post) {
                $post['index'] = ++$i;
                echo Template::getTemplateHtml('widget-post-list', $post);
            }
            echo '</div>';
        } else {
            echo '<div class="core-next-widget-post-list">';
            foreach ($post_list as $post) {
                echo Template::getTemplateHtml('widget-post-list-item', $post);
            }
            echo '</div>';
        }
        $this->widget_end($args);
    }

}