<?php

if ( ! defined( 'ABSPATH' ) ) {
	die();
}

if ( is_admin() || is_customize_preview() ) {
	require_once dirname(__FILE__) . '/widget-framework.php';
}

// Widget Class
class kanews_widget_class_posts_11 extends WP_Widget {

  // Create
	public function __construct(){
		$widget_ops = array('classname' => 'kanews_widget_posts_11 column_x_gutter kanews-section-flat');
		$control_ops = array('id_base' => 'kanews_widget_posts_11');
		parent::__construct('kanews_widget_posts_11', ''.KAN_THEME_NAME .' - '.__( "Yazılar" , 'kanews' ).' #11' , $widget_ops, $control_ops );
		add_action('admin_enqueue_scripts', array('Kanews_Form_Elements', 'enqueue_scripts'));
	}

	private static function get_defaults() {
		return array(
			'title'           => '',
			'grid'            => 'col-12',
			'style'           => '1',
			'html_tag'        => 'h4',
			'postnotin'       => 'off',
			'categories'      => array(),
			'tags'            => '',
			'posts'           => 6,
			'sortby'          => 'recent',
			'date_range'      => '0',
			'offset'          => '0',
			'format'          => '0',
			'load_more'       => 'on',
			'show_cat_color'  => 'on',
			'show_post_cat'   => 'on',
			'show_post_date'  => 'off',
			'cat_list'        => 'off',
			'hide_desktop'    => 'off',
			'hide_mobile'     => 'off',
			'accent-color'    => '',
			'bg-color'        => '',
			'bg-color2'       => '',
			'include_columist'=> 'off',
		);
	}


	public static function post_content($query, $style, $counter = 0, $page = 1) {
		
		while ( $query->have_posts() ){
			$query->the_post();
			global $post;
			$counter++;

			$cat_color = get_term_meta( (int) Kanews\Helper_Wp::primary_category_id($post->ID), '_category_color', true );
			$col = 'col-6 col-md-4 col-lg-3';
			$thumbnail = 'kanews-manset-5';
			$big_class = '';

			if($style['sidebar'] == 'full') {
				if($counter % 5 == 1) {
					$big_class = 'kanews-post-big';
					$col = 'col-12 col-md-6';
					$thumbnail = 'kanews-manset-3';
				}
			} elseif($style['sidebar'] == 'content') {
				$col = 'col-6 col-md-4';
				if($counter % 5== 1) {
					$big_class = 'kanews-post-big';
					$col = 'col-12 col-md-8';
					$thumbnail = 'kanews-manset-3';
				}
			} else {
				$col = 'col-12';
				$thumbnail = 'kanews-manset-3';
			}

			extract($style);

			
			?>

				<?php if( $layout == 1 ) :?>
					<div class="kanews-animation-col-<?php echo $page; ?> <?php echo $col; ?>">
						<div class="kanews-post-overlay <?php echo $big_class; ?>" <?php if($cat_color && $show_cat_color == 'on') {echo 'style="--gradient-start-color: #'.$cat_color.'"';} ?>>
							<a href="<?php the_permalink(); ?>" class="kanews-post-href" aria-label="<?php the_title(); ?>"></a>		
							<?php kanews_post_thumbnail($thumbnail, 'kanews-post-thumb'); ?>
							<?php do_action('kanews_post_hook'); ?>
							<div class="kanews-post-content">
								<?php if($show_post_cat != 'off'): ?>
									<?php echo kanews_primary_category($post->ID); ?>
								<?php endif; ?>
								<?php if($show_post_date != 'off'): ?>
									<?php echo kanews_post_date('post', 'span'); ?>
								<?php endif; ?>
								<?php the_title( sprintf( '<h3 class="kanews-post-headline truncate truncate-3"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h3>' ); ?>
														
							</div>
						</div>
					</div>
				<?php else: ?>
					<?php if( $counter == 1 ) : ?>
						<div class="kanews-grid-col-first">
							<div class="kanews-post-item kanews-post-grid-item">
								<a href="<?php the_permalink(); ?>" class="kanews-post-href" aria-label="<?php echo esc_attr(get_the_title()); ?>"></a>	
								<?php do_action('kanews_post_hook'); ?>
								<?php kanews_post_thumbnail('kanews-manset-3', 'kanews-post-thumb'); ?>
								<div class="kanews-post-content">
								<?php if($show_post_cat != 'off'): ?>
										<?php echo kanews_primary_category($post->ID); ?>
									<?php endif; ?>
									<?php the_title( sprintf( '<h3 class="kanews-post-headline truncate truncate-3"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h3>' ); ?>
									<?php if($show_post_date != 'off'): ?>
										<?php echo kanews_post_date(); ?>
									<?php endif; ?>
									<?php echo wpautop( wp_trim_words( strip_shortcodes(get_the_content($post->ID)), 25, '...' ) ); ?>
      <?php echo kanews_read_more(); ?>
								</div>
							</div>
						</div>
					<?php else: ?>
						<div class="<?php echo $counter < 6 ? 'kanews-grid-col-second' : 'kanews-grid-col-other'; ?>">
							<div class="kanews-post-item kanews-post-grid-item">
								<a href="<?php the_permalink(); ?>" class="kanews-post-href" aria-label="<?php echo esc_attr(get_the_title()); ?>"></a>	
								<?php do_action('kanews_post_hook'); ?>
								<?php kanews_post_thumbnail('kanews-post-1', 'kanews-post-thumb'); ?>
								<div class="kanews-post-content">
								<?php if($show_post_cat != 'off'): ?>
										<?php echo kanews_primary_category($post->ID); ?>
									<?php endif; ?>
									<?php the_title( sprintf( '<h3 class="kanews-post-headline truncate truncate-2"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a><h3>' ); ?>
									<?php if($show_post_date != 'off'): ?>
										<?php echo kanews_post_date(); ?>
									<?php endif; ?>
								</div>
							</div>
						</div>
					<?php endif; ?>
				<?php endif; ?>

			<?php
			if( $style['is_do_not_dublicate'] ){
				Kanews\Helper::do_not_dublicate( $post->ID );
			}
		}
		wp_reset_postdata();
	}
  
  // Front-end
	public function widget($args, $instance)
	{
		$instance = Kanews_Widget_Helper::normalize_instance( $instance, self::get_defaults() );

		if ( ! Kanews_Widget_Helper::should_render_widget( $instance ) ) {
			return;
		}
		
		$grid = (!empty($instance['grid'])) ? $instance['grid'] : 'col-12';
		$title = apply_filters('widget_title', isset($instance['title']) ? $instance['title'] : '' );


		$style = (isset($instance['style'])) ? $instance['style'] : '1';
		$post_type = !isset($instance['include_columist']) ? 'post' : array('post', 'columist');
		$categories = (isset($instance['categories'])) ? $instance['categories'] : '';
		$tags = (isset($instance['tags'])) ? $instance['tags'] : '';
    $posts = (isset($instance['posts'])) ? $instance['posts'] : '5';
    $offset = (isset($instance['offset'])) ? $instance['offset'] : '';
    $date_range = (isset($instance['date_range']) && $instance['date_range'] != '0') ? $instance['date_range'] : null;
    $sortby = (isset($instance['sortby'])) ? $instance['sortby'] : 'recent';
		$is_do_not_dublicate = $instance['postnotin'] == 'on' ? true : false;

		$format = !empty($instance['format']) ? $instance['format'] : '';

		$load_more = isset($instance['load_more']) ? 'on' : 'off';
		$show_cat_color = isset($instance['show_cat_color']) ? 'on' : 'off';
		$show_post_cat = isset($instance['show_post_cat']) ? 'on' : 'off';
		$show_post_date = isset($instance['show_post_date']) ? 'on' : 'off';

		$bg_color = !empty($instance['bg-color']) ? $instance['bg-color'] : '';
		$bg_color2 = !empty($instance['bg-color2']) ? $instance['bg-color2'] : '';
		$accent_color = !empty($instance['accent-color']) ? $instance['accent-color'] : '';
		$cat_list = !isset($instance['cat_list']) ? false : true;
		$categories_for_list = is_array( $categories ) ? $categories : ( '' !== $categories ? array( $categories ) : array() );


		if ($load_more === 'on') {
			wp_enqueue_script('kanews-infinite-scroll');
		}

		$query_args = array(
			'post_type'			=> $post_type,
			'number'				=> $posts,
			'id'    				=> is_category() ? get_queried_object_id() : $categories,
			'sortby' 				=> $sortby,
			'tags_ids' 			=> $tags,
			'offset' 				=> $offset,
			'range'				  => $date_range,
			'format'				=> $format
		);
		$kanews_query = kan_query( $query_args );

		if(isset($args['id']))
		$sidebar = explode('-', $args['id']);
		else
		$sidebar = array('0' => 'home', '1' => 'content');

		$style_args = array(
			'sidebar' => isset($sidebar[2]) ? $sidebar[2] : $sidebar[1],
			'show_post_cat' => $show_post_cat,
			'show_post_date' => $show_post_date,
			'show_cat_color' => $show_cat_color,
			'is_do_not_dublicate' => $is_do_not_dublicate,
			'layout' => $style,
		);

		?>

		<?php if ($kanews_query->have_posts()) : 
			$widget_id = '#'. $args['widget_id'];
			$output_css = '';
			if( $bg_color != '' && $bg_color2 != '') {
				$output_css .= "
				.light-mode $widget_id .kanews-post-overlay {
					--gradient-start-color: $bg_color;
					--gradient-end-color: $bg_color2;
				}
				";
			}

			if( $accent_color != '') {
				$output_css .= "
				$widget_id {
					--kan-theme-color: $accent_color
				}
				";
			}

			if( !empty($output_css) ) {
				echo "<style id='kanews-theme-inline-$widget_id' scoped type=\"text/css\">".( kan_minify_css($output_css) ) ."</style>";
			}
			?>
			<div class="<?php echo $grid; ?>"> 
				<div id="<?php echo $this->id; ?>" class="kanews-section <?php echo $this->widget_options['classname']; ?> kanews_posts_11__<?php echo $style; ?> widget-area-<?php echo $style_args['sidebar']; ?>">
					<?php if ( ! empty($instance['title']) ):
						echo ( $args['before_title'] . $title . $args['after_title'] );
					endif; ?>

					<?php if ( $cat_list && count( $categories_for_list ) > 1 ) : ?>

					<div class="kanews_widget_posts_6">
						<div class="kanews-tab">
							<ul class="nav nav-tabs d-flex flex-wrap">

								<?php $number= 0; foreach( $categories_for_list as $category ) {  $number++;?>
									<li class="nav-item">
										<a href="<?php echo get_category_link($category); ?>" class="nav-link">	<?php echo get_cat_name($category); ?></a>
									</li>
								<?php } ?>
							</ul>
						</div>
					</div>

					<?php endif; ?>
						
					<?php if( $style_args['layout'] == 2 ) :?> 
						

					
						<div class="kanews_widget_posts_6">
							<div class="kanews-tab">
								<ul class="nav nav-tabs d-flex flex-wrap">

									<?php 
									if( $categories == '' ) {
										$categories = get_categories( array(
											'orderby' => 'count',
											'order'   => 'DESC',
											'number'  => 7 //
										) );
									}

									if( is_category( ) ) {
										
										$categories = get_categories( array(
											'orderby' => 'count',
											'order'   => 'DESC',
											'number'  => 7,
											'child_of' => get_queried_object_id()
										) );
									}

									foreach( $categories as $category ) : ?>
										<li class="nav-item">
											<?php if( ! is_object($category) ) : ?>
											<a href="<?php echo get_category_link( $category ); ?>" class="nav-link"><?php echo get_cat_name( $category ); ?></a>
											<?php else: ?>
											<a href="<?php echo esc_url(Kanews\Helper_Wp::get_term_link($category, 'category')); ?>" class="nav-link"><?php echo $category->name; ?></a>
											<?php endif; ?>
										</li>
									<?php endforeach; ?>

								</ul>

							</div>
						</div>
					<?php endif; ?>

					<div class="row kanews-widget-ajax-posts" <?php if($load_more=='on'): ?>data-query="<?php echo str_replace( '"', '\'', wp_json_encode( $query_args )); ?>" data-style="<?php echo str_replace( '"', '\'', wp_json_encode( $style_args )); ?>" data-current="1"<?php endif; ?>>
						<?php self::post_content($kanews_query, $style_args, 0, 1); ?>
					</div>
					<?php if($load_more == 'on'): ?>
						<div class="row">
							<div class="col-12 d-flex align-items-center justify-content-center">
									<button class="kanews-label kanews-label-widget kanews-widget-ajax-button">
										<?php esc_html_e( 'Daha Fazla Göster', 'kanews' ); ?> 
										<div id="kanews-loader"></div> 
									</button>
								
							</div>
						</div>
					<?php endif; ?>
				</div>
			</div>
			<script>
			</script>
		<?php endif;
	}
  
  // Update Form
	public function update($new_instance, $old_instance)
	{
		$instance = $old_instance;

		$instance['title'] = $new_instance['title'];
		$instance['grid'] = $new_instance['grid'];
		$instance['html_tag'] = $new_instance['html_tag'];

		$instance['categories'] = $new_instance['categories'];
		$instance['tags'] = $new_instance['tags'];
		$instance['posts'] = $new_instance['posts'];
		$instance['offset'] = $new_instance['offset'];
		$instance['sortby'] = $new_instance['sortby'];
    $instance['postnotin'] = $new_instance['postnotin'];
		$instance['date_range'] = $new_instance['date_range'];
		$instance['format'] = $new_instance['format'];
		$instance['style'] = $new_instance['style'];

		$instance['load_more'] = $new_instance['load_more'];
		$instance['show_cat_color'] = $new_instance['show_cat_color'];
		$instance['show_post_cat'] = $new_instance['show_post_cat'];
		$instance['show_post_date'] = $new_instance['show_post_date'];
		$instance['include_columist'] = $new_instance['include_columist'];

		$instance['cat_list'] = $new_instance['cat_list'];
		$instance['hide_desktop'] = $new_instance['hide_desktop'];
		$instance['hide_mobile'] = $new_instance['hide_mobile'];
		$instance['bg-color'] = $new_instance['bg-color'];
		$instance['bg-color2'] = $new_instance['bg-color2'];
		$instance['accent-color'] = $new_instance['accent-color'];
		
		return $instance;
	}
	
  // Back-end
	public function form($instance) {
		$defaults = self::get_defaults();
		$instance = wp_parse_args((array) $instance, $defaults); 

		// Genel Ayarlar Accordion
		Kanews_Form_Elements::render_accordion_field(array(
			'title' => __('Genel Ayarlar', 'kanews'),
			'content' => array(
				array(
					'type' => Kanews_Form_Elements::TYPE_TEXT,
					'id' => $this->get_field_id('title'),
					'name' => $this->get_field_name('title'),
					'label' => __('Başlık', 'kanews'),
					'value' => $instance['title']
				),
				array(
					'type' => Kanews_Form_Elements::TYPE_SELECT,
					'id' => $this->get_field_id('style'),
					'name' => $this->get_field_name('style'),
					'label' => __('Varyasyon', 'kanews'),
					'value' => $instance['style'],
					'options' => array(
						'1' => '1',
						'2' => '2'
					)
				),
				array(
					'type' => Kanews_Form_Elements::TYPE_SELECT,
					'id' => $this->get_field_id('html_tag'),
					'name' => $this->get_field_name('html_tag'),
					'label' => __('Yazı Başlığı HTML Tag', 'kanews'),
					'value' => $instance['html_tag'],
					'options' => array(
						'div' => 'Div',
						'h1' => 'H1',
						'h2' => 'H2',
						'h4' => 'h4',
						'h4' => 'H4',
						'h5' => 'H5',
						'h6' => 'H6'
					)
				)
			)
		));

		// Sıralama Ayarları - Global metod kullanımı
		Kanews_Form_Elements::render_posts_sorting_settings($this, $instance);

		// İçerik Ayarları Accordion
		Kanews_Form_Elements::render_accordion_field(array(
			'title' => __('İçerik Ayarları', 'kanews'),
			'content' => array(
				array(
					'type' => Kanews_Form_Elements::TYPE_TOGGLE,
					'id' => $this->get_field_id('load_more'),
					'name' => $this->get_field_name('load_more'),
					'label' => __('Daha Fazla Yükle', 'kanews'),
					'value' => $instance['load_more']
				),
				array(
					'type' => Kanews_Form_Elements::TYPE_TOGGLE,
					'id' => $this->get_field_id('show_cat_color'),
					'name' => $this->get_field_name('show_cat_color'),
					'label' => __('Kategori Rengi ile Kapla', 'kanews'),
					'value' => $instance['show_cat_color']
				),
				array(
					'type' => Kanews_Form_Elements::TYPE_TOGGLE,
					'id' => $this->get_field_id('show_post_date'),
					'name' => $this->get_field_name('show_post_date'),
					'label' => __('Yazı Tarihini Göster', 'kanews'),
					'value' => $instance['show_post_date']
				),
				array(
					'type' => Kanews_Form_Elements::TYPE_TOGGLE,
					'id' => $this->get_field_id('show_post_cat'),
					'name' => $this->get_field_name('show_post_cat'),
					'label' => __('Yazı Kategorisini Göster', 'kanews'),
					'value' => $instance['show_post_cat']
				),
				array(
					'type' => Kanews_Form_Elements::TYPE_TOGGLE,
					'id' => $this->get_field_id('cat_list'),
					'name' => $this->get_field_name('cat_list'),
					'label' => __('Kategorileri Listele', 'kanews'),
					'value' => $instance['cat_list']
				)
			)
		));

		// Görünüm Ayarları Accordion
		Kanews_Form_Elements::render_accordion_field(array(
			'title' => __('Görünüm Ayarları', 'kanews'),
			'content' => array(
				array(
					'type' => Kanews_Form_Elements::TYPE_COLOR,
					'id' => $this->get_field_id('accent-color'),
					'name' => $this->get_field_name('accent-color'),
					'label' => __('Birincil Renk', 'kanews'),
					'value' => $instance['accent-color']
				),
				array(
					'type' => Kanews_Form_Elements::TYPE_COLOR,
					'id' => $this->get_field_id('bg-color'),
					'name' => $this->get_field_name('bg-color'),
					'label' => __('Arkaplan Rengi', 'kanews'),
					'value' => $instance['bg-color']
				),
				array(
					'type' => Kanews_Form_Elements::TYPE_COLOR,
					'id' => $this->get_field_id('bg-color2'),
					'name' => $this->get_field_name('bg-color2'),
					'label' => __('Arkaplan Rengi 2', 'kanews'),
					'value' => $instance['bg-color2']
				),
				array(
					'type' => Kanews_Form_Elements::TYPE_TOGGLE,
					'id' => $this->get_field_id('hide_desktop'),
					'name' => $this->get_field_name('hide_desktop'),
					'label' => __('Masaüstünde Gizle', 'kanews'),
					'value' => $instance['hide_desktop']
				),
				array(
					'type' => Kanews_Form_Elements::TYPE_TOGGLE,
					'id' => $this->get_field_id('hide_mobile'),
					'name' => $this->get_field_name('hide_mobile'),
					'label' => __('Mobilde Gizle', 'kanews'),
					'value' => $instance['hide_mobile']
				)
			)
		));
	}
}
?>