<?php

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

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

class kanews_widget_class_posts_x extends WP_Widget {
    public function __construct() {
		$widget_ops = array('classname' => 'kanews_widget_posts_x');
		$control_ops = array('id_base' => 'kanews_widget_posts_x');
        parent::__construct('kanews_widget_posts_x', ''.KAN_THEME_NAME .' - '.__("Son Yazılar", 'kanews'), $widget_ops, $control_ops);
        add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
	}

	private static function get_defaults() {
		return array(
			'title'            => '',
			'post_type'        => 'post',
			'style'            => '5',
			'categories'       => array(),
			'categories2'      => array(),
			'tags'             => '',
			'posts'            => 8,
			'sortby'           => 'recent',
			'date_range'       => '0',
			'offset'           => 0,
			'format'           => '0',
			'html_tag'         => 'h2',
			'dark_mode'        => 'off',
			'hide_ad'          => 'off',
			'disable_pagi'     => 'off',
			'hide_desktop'     => 'off',
			'hide_mobile'      => 'off',
			'accent-color'     => '',
			'bg-color'         => '',
			'bg-color2'        => '',
			'postnotin'        => 'off',
			'include_columist' => 'off',
			'pids'             => array(),
			'exclude_pids'     => array(),
		);
	}

    public function enqueue_scripts() {
        wp_enqueue_script( 'kanews-infinite-scroll' );
    }
  
  // 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;
		}

        $title = apply_filters('widget_title', isset($instance['title']) ? $instance['title'] : '');
        $include_columist = isset($instance['include_columist']) && $instance['include_columist'] == 'on' ? true : false;
        $post_type = (isset($instance['post_type'])) ? $instance['post_type'] : 'post';
        if( $include_columist ){
            $post_type = array('post', 'columist');
        }
        $style = (isset($instance['style'])) ? $instance['style'] : '5';
        $categories = (isset($instance['categories'])) ? $instance['categories'] : '';
        $tags = (isset($instance['tags'])) ? $instance['tags'] : '';
        $posts = (isset($instance['posts'])) ? $instance['posts'] : '5';
        $date_range = (isset($instance['date_range']) && $instance['date_range'] != '0') ? $instance['date_range'] : null;
        $sortby = (isset($instance['sortby'])) ? $instance['sortby'] : 'recent';
        $format = !empty($instance['format']) ? $instance['format'] : '';
        $html = !empty($instance['html']) ? $instance['html'] : 'h2';
        $is_do_not_dublicate = isset($instance['postnotin']) && $instance['postnotin'] == 'on' ? true : false;


        $dark_mode = !isset($instance['dark_mode']) ? '' : 'dark-mode';
        $hide_ad = !isset($instance['hide_ad']) ? true : false;
        $disable_pagi = isset($instance['disable_pagi']) ? true : false;

        $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'] : '';

        $query_args = array(
        'post_type' => $post_type,
        'number' => $posts,
        'id' => $categories,
        'sortby' => $sortby,
        'tags_ids' => $tags,
        'pagi' => 1,
        'range' => $date_range,
        'format' => $format
        );
        $kanews_query = kan_query($query_args);
	
		$count = $counter = 0;
		$classes = '';

		$flat = '';
		if ($style == '3' || $style == '2') {
		$flat = 'equal-height';
		$classes = 'kanews-section-flat column_x_gutter';
        } elseif ($style == '6')
		$flat = 'no-gutters';

    if ($kanews_query->have_posts()) : 
            $widget_id = '#' . $args['widget_id'];
			$output_css = '';
            if ($bg_color != '' && $bg_color2 != '') {
				$output_css .= "
				.light-mode $widget_id.kanews-section:not(.kanews-posts-style-6) {
					background: linear-gradient(135deg,  $bg_color, $bg_color2 ) !important;
				}
				.light-mode $widget_id .kanews-post-item {
					background: transparent;
				}
				.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="col-12 <?php echo $dark_mode; ?>"> 
                <div id="<?php echo $this->id; ?>" class="kanews-section <?php echo $this->widget_options['classname']; ?> <?php echo 'kanews-posts-style-' . $style . ' ' . $classes; ?>">
                    <?php if (!empty($instance['title'])):
                        echo ($args['before_title'] . $title . $args['after_title']);
					endif; ?>
          <div class="row <?php echo $flat; ?>" kanews-data-load-more data-status="1">
                        <?php while ($kanews_query->have_posts()): $kanews_query->the_post();
                            global $post;
                            $counter++;
							global $wp_query;
							global $paged;
                            $per_page = $wp_query->query_vars['posts_per_page'];
							
                            if ($paged != 0 && !isset($one_time)) {
                                $counter = $counter + (( $paged * $per_page ) - $per_page);
								$one_time = 1;
							}
							get_template_part('template-parts/archives/article', $style, array('tag' => $html));
                            if (!$hide_ad)
							Kanews\Ads::ad_archives($style, $counter);
							?>
                        <?php
												if( $is_do_not_dublicate ){
													Kanews\Helper::do_not_dublicate( $post->ID );
												}
											endwhile; 
												
												?>
          </div>
        </div>
            
            <?php if ( ! $disable_pagi ): ?>
						<?php
				$paged = 1;
				$format = '';
                if (get_query_var('paged')) {
                    $paged = get_query_var('paged');
					$format = '/page/%#%';
                } elseif (get_query_var('page')) {
                    $paged = get_query_var('page');
					$format = '/page/%#%';
				}
					$total_pages = $kanews_query->max_num_pages;
                if ($total_pages > 1) {
						echo '<nav class="navigation pagination" style="width: 100%" hidden role="navigation"><div class="nav-links">';
						echo paginate_links(array(
                        'base' => str_replace(999999999, '%#%', esc_url(get_pagenum_link(999999999))),
							'format' => $format,
							'current' => $paged,
							'total' => $total_pages,
                        'prev_text' => '<i class="icon-arrow"></i>',
                        'next_text' => '<i class="icon-arrow icon-90deg"></i>',
						));
						echo '</div></nav>';
					}
				?> 
			<div id="load-more-posts-button-wrapper">
				<div style="display:none" class="page-load-status">
					<div class="loader-ellips infinite-scroll-request">
						<svg version="1.1" id="loader-1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="40px" height="40px" viewBox="0 0 40 40" enable-background="new 0 0 40 40" xml:space="preserve"> <path opacity="0.2" fill="#000" d="M20.201,5.169c-8.254,0-14.946,6.692-14.946,14.946c0,8.255,6.692,14.946,14.946,14.946 s14.946-6.691,14.946-14.946C35.146,11.861,28.455,5.169,20.201,5.169z M20.201,31.749c-6.425,0-11.634-5.208-11.634-11.634 c0-6.425,5.209-11.634,11.634-11.634c6.425,0,11.633,5.209,11.633,11.634C31.834,26.541,26.626,31.749,20.201,31.749z"/> <path fill="#000" d="M26.013,10.047l1.654-2.866c-2.198-1.272-4.743-2.012-7.466-2.012h0v3.312h0 C22.32,8.481,24.301,9.057,26.013,10.047z"> <animateTransform attributeType="xml" attributeName="transform" type="rotate" from="0 20 20" to="360 20 20" dur="0.5s" repeatCount="indefinite"/> </path> </svg>
					</div>
					<p class="infinite-scroll-last"><?php _e('Daha fazla gösterilecek yazı bulunamadı!', 'kanews'); ?></p>
					<p class="infinite-scroll-error"><?php _e('Tekrar deneyiniz.', 'kanews'); ?></p>
				</div>
			</div>
			<?php endif; ?>
						</div>
            <?php wp_reset_postdata();
        endif; ?>
	<?php }
  
  // Update Form
    public function update($new_instance, $old_instance) {
		$instance = $old_instance;
		$instance['title'] = $new_instance['title'];
		$instance['post_type'] = $new_instance['post_type'];
		$instance['style'] = $new_instance['style'];
		$instance['categories'] = $new_instance['categories'];
		$instance['posts'] = $new_instance['posts'];
		$instance['tags'] = $new_instance['tags'];
		$instance['sortby'] = $new_instance['sortby'];
		$instance['date_range'] = $new_instance['date_range'];
		$instance['format'] = $new_instance['format'];
		$instance['html_tag'] = $new_instance['html_tag'];
		$instance['dark_mode'] = $new_instance['dark_mode'];
		$instance['hide_ad'] = $new_instance['hide_ad'];
		$instance['disable_pagi'] = $new_instance['disable_pagi'];
		$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'];
        $instance['offset'] = $new_instance['offset'];
        $instance['postnotin'] = $new_instance['postnotin'];
        $instance['include_columist'] = $new_instance['include_columist'];
        $instance['pids'] = $new_instance['pids'];
        $instance['exclude_pids'] = $new_instance['exclude_pids'];
        $instance['categories2'] = $new_instance['categories2'];
		
		return $instance;
	}

  // Back-end
    public function form($instance) {
		$defaults = self::get_defaults();
		$instance = wp_parse_args((array) $instance, $defaults); 

        // Genel Ayarlar
        Kanews_Form_Elements::render_accordion_field([
            'title' => __('Genel Ayarlar', 'kanews'),
            'content' => [
                [
                    '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']
                ],
                [
                    'type' => Kanews_Form_Elements::TYPE_SELECT,
                    'id' => $this->get_field_id('style'),
                    'name' => $this->get_field_name('style'),
                    'label' => __('Görünüm', 'kanews'),
                    'value' => $instance['style'],
                    'options' => [
                        '1' => '1',
                        '2' => '2',
                        '3' => '3',
                        '4' => '4',
                        '5' => '5',
                        '6' => '6'
                    ]
                ],
                [
                    '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' => [
                        'div' => 'Div',
                        'h1' => 'H1',
                        'h2' => 'H2',
                        'h4' => 'h4',
                        'h4' => 'H4',
                        'h5' => 'H5',
                        'h6' => 'H6'
                    ]
                ],
                [
                    'type' => Kanews_Form_Elements::TYPE_SELECT,
                    'id' => $this->get_field_id('post_type'),
                    'name' => $this->get_field_name('post_type'),
                    'label' => __('Yazı Türü', 'kanews'),
                    'value' => $instance['post_type'],
                    'options' => [
                        'post' => __('Haber', 'kanews'),
                        'columist' => __('Köşe Yazısı', 'kanews')
                    ]
                ]
            ]
        ]);

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

        // İçerik Ayarları
        Kanews_Form_Elements::render_accordion_field([
            'title' => __('İçerik Ayarları', 'kanews'),
            'content' => [
                [
                    'type' => Kanews_Form_Elements::TYPE_TOGGLE,
                    'id' => $this->get_field_id('dark_mode'),
                    'name' => $this->get_field_name('dark_mode'),
                    'label' => __('Koyu Mod', 'kanews'),
                    'value' => $instance['dark_mode']
                ],
                [
                    'type' => Kanews_Form_Elements::TYPE_TOGGLE,
                    'id' => $this->get_field_id('hide_ad'),
                    'name' => $this->get_field_name('hide_ad'),
                    'label' => __('Arşiv Reklamlarını Gizle', 'kanews'),
                    'value' => $instance['hide_ad']
                ],
                [
                    'type' => Kanews_Form_Elements::TYPE_TOGGLE,
                    'id' => $this->get_field_id('disable_pagi'),
                    'name' => $this->get_field_name('disable_pagi'),
                    'label' => __('Sayfalama Yapma', 'kanews'),
                    'value' => $instance['disable_pagi']
                ]
            ]
        ]);

        // Görünüm Ayarları
        Kanews_Form_Elements::render_accordion_field([
            'title' => __('Görünüm Ayarları', 'kanews'),
            'content' => [
                [
                    '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']
                ],
                [
                    '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']
                ],
                [
                    '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']
                ]
            ]
        ]);

        // Görünürlük Ayarları
        Kanews_Form_Elements::render_accordion_field([
            'title' => __('Görünürlük Ayarları', 'kanews'),
            'content' => [
                [
                    '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']
                ],
                [
                    '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']
                ]
            ]
        ]);
    }
}