<?php
/**
 * Kopa Widget Articles List
 *
 * @author 		Kopatheme
 * @category 	Widgets
 * @package 	KopaFramework/Widgets
 * @since    	1.0.0
 * @extends 	Kopa_Widget
 */

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

function kopa_widget_posttype_build_query( $query_args = array() ) {
    $default_query_args = array(
        'post_type'      => 'post',
        'posts_per_page' => -1,
        'post__not_in'   => array(),
        'ignore_sticky_posts' => 1,
        'categories'     => array(),
        'tags'           => array(),
        'relation'       => 'OR',
        'post_format' => '',
        'orderby'        => 'latest',
        'cat_name'       => 'category',
        'tag_name'       => 'post_tag'
    );

    $query_args = wp_parse_args( $query_args, $default_query_args );

    $args = array(
        'post_type'           => $query_args['post_type'],
        'posts_per_page'      => $query_args['posts_per_page'],
        'post_format' => $query_args['post_format'],
        'post__not_in'        => $query_args['post__not_in'],
        'ignore_sticky_posts' => $query_args['ignore_sticky_posts']
    );

    $tax_query = array();

    if ( $query_args['categories'] ) {
        $tax_query[] = array(
            'taxonomy' => $query_args['cat_name'],
            'field'    => 'id',
            'terms'    => $query_args['categories']
        );
    }
    if ( $query_args['tags'] ) {
        $tax_query[] = array(
            'taxonomy' => $query_args['tag_name'],
            'field'    => 'id',
            'terms'    => $query_args['tags']
        );
    }
    if ( $query_args['relation'] && count( $tax_query ) == 2 ) {
        $tax_query['relation'] = $query_args['relation'];
    }
    if ( $query_args['post_format'] ) {
        $tax_query[] = array(
            'taxonomy' => 'post_format',
            'field' => 'slug',
            'terms' => array( $query_args['post_format'] )
        );
    }

    if ( isset($query_args['date_query']) && $query_args['date_query'] ){
        global $wp_version;
        $timestamp =  $query_args['date_query'];
        if (version_compare($wp_version, '3.7.0', '>=')) {
            if (isset($timestamp) && !empty($timestamp)) {
                $y = date('Y', strtotime($timestamp));
                $m = date('m', strtotime($timestamp));
                $d = date('d', strtotime($timestamp));
                $args['date_query'] = array(
                    array(
                        'after' => array(
                            'year' => (int) $y,
                            'month' => (int) $m,
                            'day' => (int) $d
                        )
                    )
                );
            }
        }
    }


    if ( $tax_query ) {
        $args['tax_query'] = $tax_query;
    }

    switch ( $query_args['orderby'] ) {
        case 'popular':
            $args['meta_key'] = 'kopa_' . 'newmoment' . '_total_view';
            $args['orderby'] = 'meta_value_num';
            break;
        case 'most_comment':
            $args['orderby'] = 'comment_count';
            break;
        case 'random':
            $args['orderby'] = 'rand';
            break;
        default:
            $args['orderby'] = 'date';
            break;
    }
    return new WP_Query( $args );
}

class Kopa_Widget_Articles_List extends Kopa_Widget {
	/**
	 * Constructor
	 */
	public function __construct() {

        //Tags Array
        $tags = get_tags();
        $arr_tags = array(
            '' => __('----SELECT----', 'kopa-framework')
            );
        foreach ($tags as $category) 
            $arr_tags[$category->term_id] = $category->name.' ('.$category->count.')';

        //Categories Array
        $categories = get_categories();
        $arr_cats = array(
            '' => __('----SELECT----', 'kopa-framework')
            );
        foreach ($categories as $category)
            $arr_cats[$category->term_id] = $category->name.' ('.$category->count.')';

		$this->widget_cssclass    = 'kopa-widget-article_list';
		$this->widget_description = __( 'Display article list with 7 style: Show posts with small thumbnail; Carousel - All post in a row, a column.', 'newmoment' );
		$this->widget_id          = 'kopa-widget-article_list';
		$this->widget_name        = __( 'Kopa Widget Article List', 'newmoment' );
		// $this->widget_width       = 400;
		$this->settings           = array(
			'title'  => array(
				'type'  => 'text',
				'std'   => __( 'Kopa Widget Article List', 'newmoment' ),
				'label' => __( 'Title:', 'newmoment' )
			),
            'categories' => array(
                'type'    => 'multiselect',
                'label'   => __( 'Categories:', 'newmoment' ),
                'std'     => null,
                'options' => $arr_cats,
            ),
            'relation' => array(
                'type'    => 'select',
                'label'   => __( 'Relation:', 'newmoment' ),
                'options' => array(
                    'OR'  => __( 'OR', 'newmoment' ),
                    'AND' => __( 'AND', 'newmoment' ),
                )
            ),
            'tags' => array(
                'type'    => 'multiselect',
                'label'   => __( 'Tags:', 'newmoment' ),
                'std'     => null,
                'options' => $arr_tags,
            ),
            'orderby' => array(
                'type'    => 'select',
                'std'     => 'latest',
                'label'   => __( 'Orderby:', 'newmoment' ),
                'options' => array(
                    'latest'       => __('Latest', 'newmoment'),
                    'popular'      => __('Popular by view count', 'newmoment'),
                    'most_comment' => __('Popular by comment count', 'newmoment'),
                    'random'       => __('Random', 'newmoment')
                )
            ),
            'timestamp' => array(
                'type'  => 'select',
                'std'   => '',
                'label' => __( 'Timestamp (ago):', 'newmoment' ),
                'options' => array(
                    ''          => __('-- Select --', 'newmoment'),
                    '-1 week'   => __('1 week', 'newmoment'),
                    '-2 week'   => __('2 weeks', 'newmoment'),
                    '-3 week'   => __('3 weeks', 'newmoment'),
                    '-1 month'  => __('1 months', 'newmoment'),
                    '-2 month'  => __('2 months', 'newmoment'),
                    '-3 month'  => __('3 months', 'newmoment'),
                    '-4 month'  => __('4 months', 'newmoment'),
                    '-5 month'  => __('5 months', 'newmoment'),
                    '-6 month'  => __('6 months', 'newmoment'),
                    '-7 month'  => __('7 months', 'newmoment'),
                    '-8 month'  => __('8 months', 'newmoment'),
                    '-9 month'  => __('9 months', 'newmoment'),
                    '-10 month' => __('10 months', 'newmoment'),
                    '-11 month' => __('11 months', 'newmoment'),
                    '-1 year'   => __('1 year', 'newmoment'),
                    '-2 year'   => __('2 years', 'newmoment'),
                    '-3 year'   => __('3 years', 'newmoment'),
                    '-4 year'   => __('4 years', 'newmoment'),
                    '-5 year'   => __('5 years', 'newmoment'),
                    '-6 year'   => __('6 years', 'newmoment'),
                    '-7 year'   => __('7 years', 'newmoment'),
                    '-8 year'   => __('8 years', 'newmoment'),
                    '-9 year'   => __('9 years', 'newmoment'),
                    '-10 year'  => __('10 years', 'newmoment'),
                )
            ),
			'posts_per_page' => array(
				'type'  => 'number',
				'step'  => 1,
				'min'   => 1,
				'max'   => '',
				'std'   => 5,
				'label' => __( 'Number of items:', 'newmoment' )
			),
            'limit' => array(
                'type'  => 'number',
                'step'  => 1,
                'min'   => 1,
                'max'   => '',
                'std'   => 5,
                'label' => __( 'Custom post excerpt length ( Actice with type : Show posts in one column, first post is featured, Grid layout with 2 columns, first column is featured, Show posts in one column ):', 'newmoment' )
            ),  	
            'type' => array(
                'type'    => 'select',
                'std'     => '',
                'label'   => __( 'Type:', 'newmoment' ),
                'options' => array(
                    'normal'                    => __('Show posts with small thumbnail', 'newmoment'),
                    'carousel_one_row_one_col'  => __('Carousel - All post in a row, a column', 'newmoment')
                )
            ),
		);
		parent::__construct();
	}

	/**
	 * widget function.
	 *
	 * @see WP_Widget
	 * @access public
	 * @param array $args
	 * @param array $instance
	 * @return void
	 */
	public function widget( $args, $instance ) {

		if ( $this->get_cached_widget( $args ) )
			return;

		ob_start();
		extract( $args );

		$title       = apply_filters( 'widget_title', $instance['title'], $instance, $this->id_base );

        $query_args['categories'] = $instance['categories'];
        $query_args['relation'] = esc_attr($instance['relation']);
        $query_args['tags'] = $instance['tags'];
        $query_args['posts_per_page'] = (int) $instance['posts_per_page'];

        if (isset($instance['timestamp'])){
            $query_args['date_query'] = $instance['timestamp'];
        }

        $query_args['orderby'] = $instance['orderby'];
        $type = $instance['type'];
        $limit = $instance['limit'];
        $number_of_post = (int) $instance['posts_per_page'];

        $status = kopa_get_option( 'kopa_status_default_thumbnail', true );
        if($status == 'enable') {
            $status = true;
        }else {
            $status = false;
        }

        $posts = kopa_widget_posttype_build_query($query_args);
        $count_post = count($posts->posts);
        ?>

        <?php if ( 'carousel_one_row_one_col' === $type ) : ?>
            <div class="widget kopa-carousel-list-4-widget">
                
                <?php if($title) { ?>
                    <h3 class="widget-title"><?php echo $title; ?>
                        <span class="left-corner"></span>
                        <span class="right-corner"></span>
                    </h3>
                <?php } ?>

                <div class="owl-carousel kopa-carousel-4">
                    <?php while($posts->have_posts()) : $posts->the_post(); ?>
                    <div class="item">
                        
                        <article class="entry-item">
                            <?php if(has_post_thumbnail() || $status == true) : ?>
                                <div class="entry-thumb">
                                    <a href="<?php the_permalink(); ?>">
                                        <?php the_post_thumbnail('kopa-size-9'); ?>
                                    </a>
                                </div>
                            <?php endif; ?>
                            <h5 class="entry-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h5>
                        </article>

                    </div>
                    <?php endwhile; ?>
                </div>
                <!-- kopa-carousel-4 -->

            </div>
            <!-- kopa-carousel-list-4-widget -->
        <?php endif; ?>

        <?php if ( 'normal' === $type ) : ?>
            <div class="widget kopa-article-list-4-widget">  
                <?php if($title) { ?>
                    <h3 class="widget-title"><?php echo $title; ?>
                        <span class="left-corner"></span>
                        <span class="right-corner"></span>
                    </h3>
                <?php } ?>
                <ul>
                    <?php while($posts->have_posts()) : $posts->the_post(); ?>
                    <li>
                        <article class="entry-item">
                            <?php if(has_post_thumbnail() || $status == true) : ?>
                                <div class="entry-thumb">
                                    <a href="<?php the_permalink(); ?>">
                                        <?php the_post_thumbnail('kopa-size-10'); ?>
                                    </a>
                                </div>
                            <?php endif; ?>
                            <div class="entry-content">
                                <h6 class="entry-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h6>
                                <footer>
                                    <span class="entry-time"><i class="fa fa-clock-o"></i><span><?php echo get_the_time(); ?></span></span>
                                    <span class="entry-meta">|</span>
                                    <span class="entry-date"><i class="fa fa-calendar"></i><span><?php echo get_the_date(); ?></span></span>
                                </footer>
                            </div>
                        </article>
                    </li>
                    <?php endwhile; ?>
                </ul>
            </div>
        <?php endif; ?>
		<?php
		wp_reset_postdata();

        $content = ob_get_clean();

        echo $content;

        $this->cache_widget( $args, $content );
	}
}

register_widget( 'Kopa_Widget_Articles_List' );