<?php

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

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

// Widget Class
class kanews_widget_class_authors extends WP_Widget {

  // Create
	public function __construct(){
		$widget_ops = array('classname' => 'kanews_widget_authors');
		$control_ops = array('id_base' => 'kanews_widget_authors');
		parent::__construct('kanews_widget_authors', ''.KAN_THEME_NAME .' - '.__( "Yazarlar" , 'kanews' ), $widget_ops, $control_ops );
		add_action('admin_enqueue_scripts', array('Kanews_Form_Elements', 'enqueue_scripts'));

	}
  
  // Front-end
	public function widget($args, $instance)
	{
		$hide_mobile = isset($instance['hide_mobile']) ? 'on' : 'off';
		$hide_desktop = isset($instance['hide_desktop']) ? 'on' : 'off';
		

		if($hide_mobile == 'on') {
			if(kan_is_mobile())
			return;
		}

		if($hide_desktop == 'on') {
			if(!kan_is_mobile())
			return;
		}

		$others = isset($instance['others'])? $instance['others'] : 'off';

		$title = apply_filters('widget_title', isset($instance['title']) ? $instance['title'] : '' );
		$variations = (isset($instance['variations'])) ? $instance['variations'] : '1';
		$authors = isset($instance['authors']) ? $instance['authors'] : '';
		$role = isset($instance['role']) ? $instance['role'] : '';
		$number = (isset($instance['number'])) ? $instance['number'] : '5';
		$role__not_in = isset($instance['role__not_in']) ? $instance['role__not_in'] : '';

		$bg_color = !empty($instance['bg-color']) ? $instance['bg-color'] : '';
		$bg_color2 = !empty($instance['bg-color2']) ? $instance['bg-color2'] : '';
		$dark_mode = !isset($instance['dark_mode']) ? '' : 'dark-mode';


		$orderby = 'name';
		$uids = '';


		if(!empty($authors)) {
			$orderby = 'meta_value';
			$uids = explode(',', $authors);
		}
		
		$post_type = array('post', 'columist');
		
		$qargs = array(
				'include'       => $uids,
				'role__not_in'  => $role__not_in,
				'role'          => $role,
				'orderby'       => 'meta_value',
				'order'         => 'DESC',
				'meta_key'      => 'last_post_date',  // Son yayın tarihine göre sırala
				'meta_type'     => 'DATETIME',        // Tarih formatı
				'meta_query'    => array(
						array(
								'key'     => 'last_post_date',
								'value'   => current_time('mysql'), // Mevcut zaman
								'compare' => '<=',
								'type'    => 'DATETIME',
						)
				),
		);
		
		$wp_user_query = new WP_User_Query( $qargs );
		$authors = $wp_user_query->get_results();
		
	
    if ( empty( $authors ) ) {
			unset($qargs['meta_key']);
			unset($qargs['meta_type']);
			unset($qargs['meta_query']);
			$qargs['orderby'] = 'login';
			$qargs['order'] = 'DESC';
			// print_r($qargs);
			$wp_user_query = new WP_User_Query( $qargs );
			$authors = $wp_user_query->get_results();
		}



			$widget_id = '#'. $args['widget_id'];
			$output_css = '';

			if ( ! empty( $bg_color ) ){
				$output_css .= "
				.light-mode $widget_id .kanews-widget-header:after, .light-mode  $widget_id .kanews-btn {
						background-color: $bg_color !important;
					}

					.light-mode  $widget_id .kanews-btn{
						border-color: $bg_color;
					}
					
					.light-mode  $widget_id .kanews-btn:not(:hover) {
						color: $bg_color;
					}
				";
			}

			if( $bg_color2 != '') {
				$output_css .= "
				$widget_id .kanews-post-item {
				background: transparent !important
				}
				.light-mode $widget_id.kanews-section {
					background: $bg_color2 !important;
				}
				";
			}

			if( !empty($output_css) ) {
				echo "<style id='kanews-theme-inline-$widget_id' scoped type=\"text/css\">";
				echo ( kan_minify_css($output_css) ) ."</style>";
			}

			$show = 4;
			$col = 'col-12 col-lg-3';
			if(isset($args['id']))
			$sidebar = explode('-', $args['id']);
			else
			$sidebar = array('0' => 'home', '1' => 'content');
			
			if($sidebar[1] == 'sidebar') {
				$col = 'col-12';
				$show = 1;
			} elseif($sidebar[1] == 'content') {
				$col = 'col-12 col-lg-6';
				$show = 2;
			}

			$slick_options = [
				'slidesToShow'  => $show,
				'arrows'			  => true,
				'responsive' 			=> [
					[
						'breakpoint' 	 => 992,
						'settings'		 => [
							'slidesToShow' => 3
						]
					],
					[
						'breakpoint' 	 => 525,
						'settings'		 => [
							'slidesToShow' => 1
						]
					],
				]
			];
			?>

			<div class="col-12 <?php echo $dark_mode; ?>"> 
				<div id="<?php echo $args['widget_id']; ?>" class="kanews-section <?php if ( empty($instance['title']) && $variations == '1' ) : ?>kanews-section-flat<?php endif; ?> kanews_widget_authors_style_<?php echo $variations; ?> <?php echo $this->widget_options['classname']; ?>">

					<?php if ( ! empty($instance['title']) ) : ?>
						<div class="<?php echo $variations == 1 ? 'kanews-widget-header' : ''; ?>">
							<?php 
								echo ( $args['before_title'] . $title . $args['after_title'] );
							?>
									<?php if($others == 'on'): ?>
				
				<a class="kanews-btn kanews-btn-sm kanews-btn-block mt-0 <?php echo $variations == 1 ? 'color-white' : ''; ?>" href="<?php echo esc_url( get_post_type_archive_link( 'columist' ) ); ?>"><?php esc_html_e( 'Diğer Yazarlarımız', 'kanews' ); ?></a>

			<?php endif; ?>
						</div>
					<?php endif; 
					
					if( $variations == '1' ): 

						$slick_options = [
							'slidesToShow'  => $show,
							'responsive' 			=> [
								[
									'breakpoint' 	 => 992,
									'settings'		 => [
										'slidesToShow' => 3
									]
								],
								[
									'breakpoint' 	 => 525,
									'settings'		 => [
										'slidesToShow' => 2
									]
								],
							]
						];
						?>
						<div class="kanews-author-items">
							<div class="kanews-slider-wrapper kanews-slider-grid" data-slick='<?php echo wp_json_encode( $slick_options ); ?>'>
							
								<?php $counter = 0; foreach ( $authors as $author ) { $counter++;
									if( $counter <= $number ) :
										$last_post_id = get_user_meta( $author->ID, 'last_post_id', true );

										if ( $last_post_id ) {
											// Eğer last_post_id varsa, doğrudan bu ID'yi kullanarak sorgu yap
											$args = array(
												'p'         => $last_post_id,  // Belirli yazı ID'sine göre sorgu
												'post_type' => $post_type,
											);
										} else {
											// last_post_id yoksa, varsayılan sorgu çalışsın
											$args = array(
												'author'    => $author->ID,
												'post_type' => $post_type,
												'showposts' => 1,
											);
										}
										
										$kanews_query = new WP_Query( $args ); 

										if( ! $kanews_query->have_posts() ) {
											$args = array(
												'author'    => $author->ID,
												'post_type' => $post_type,
												'showposts' => 1,
											);
											$kanews_query = new WP_Query( $args ); 
										}
										
										?>
							
									<div class="<?php echo $col; ?> kanews-slider-col">
										<div class="kanews-author-item">
											<a href="<?php echo get_author_posts_url( get_the_author_meta( 'ID', $author->ID ) ); ?>">
												
												<div class="kanews-author-item-header row no-gutters">
													<div class="kanews-author-item-avatar col-auto">
														<?php echo kanews_user_avatar(get_the_author_meta('ID', $author->ID),'70', 'yes'); ?>
													</div>
													<div class="col	d-flex flex-column justify-content-center">
														<?php if(get_the_author_meta('first_name', $author->ID) && get_the_author_meta('last_name', $author->ID)): ?>
															<h3 class="kanews-post-headline"><?php echo esc_html(get_the_author_meta('first_name', $author->ID)); ?> <?php echo esc_html(get_the_author_meta('last_name', $author->ID)); ?></h3>
														<?php else: ?>
															<h3 class="kanews-post-headline"><?php echo esc_html(get_the_author_meta('display_name', $author->ID)); ?></h3>
														<?php endif; ?>
														<?php if( $description = get_the_author_meta('description', $author->ID) ) : ?>
															<p class="truncate truncate-2"><?php echo wp_trim_words($description, 5, '..'); ?></p>
														<?php endif; ?>
													</div>
												</div>
											</a>
											<div class="kanews-author-item-content">
												<?php if ( $kanews_query->have_posts() ) :?>
													<?php while($kanews_query->have_posts()): $kanews_query->the_post(); global $post; ?>
														<h4 class="kanews-post-headline truncate truncate-2"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
														<?php the_excerpt(); ?>
													<?php endwhile; wp_reset_postdata(); ?>
												<?php endif; ?>
											</div>
										</div>
									</div>
										
								<?php endif; } ?>
							</div>



						</div>

					<?php else: ?>
						<?php $counter = 0; foreach ( $authors as $author ) { $counter++;
							if( $counter <= $number ) :
								$last_post_id = get_user_meta( $author->ID, 'last_post_id', true );

								if ( $last_post_id ) {
									// Eğer last_post_id varsa, doğrudan bu ID'yi kullanarak sorgu yap
									$args = array(
										'p'         => $last_post_id,  // Belirli yazı ID'sine göre sorgu
										'post_type' => $post_type,
									);
								} else {
									// last_post_id yoksa, varsayılan sorgu çalışsın
									$args = array(
										'author'    => $author->ID,
										'post_type' => $post_type,
										'showposts' => 1,
									);
								}
								
								$kanews_query = new WP_Query( $args );
							
								?>

								<div class="kanews-post-item kanews-post-grid-item kanews-post-small-item">	
									<div class="kanews-post-thumb">
										<?php echo kanews_user_avatar(get_the_author_meta('ID', $author->ID),'70'); ?>	
									</div>
									<div class="kanews-post-content">
										<a class="kanews-post-headline" href="<?php echo get_author_posts_url( get_the_author_meta( 'ID', $author->ID ) ); ?>">
											<?php if(get_the_author_meta('first_name', $author->ID) && get_the_author_meta('last_name', $author->ID)): ?>
												<?php echo esc_html(get_the_author_meta('first_name', $author->ID)); ?> <?php echo esc_html(get_the_author_meta('last_name', $author->ID)); ?>
											<?php else: ?>
												<?php echo esc_html(get_the_author_meta('display_name', $author->ID)); ?>
											<?php endif; ?>
										</a>
										<?php if ( $kanews_query->have_posts() ) : ?>
											<?php while($kanews_query->have_posts()): $kanews_query->the_post(); global $post; ?>
												<a href="<?php the_permalink(); ?>">
													<h4 class="kanews-post-headline truncate truncate-2"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>

												</a>
											<?php endwhile; wp_reset_postdata(); ?>
										<?php endif; ?>
									</div>
								</div>
							<?php endif; 
						} ?>

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


		
			
	<?php
	}
  
  // Update Form
	public function update($new_instance, $old_instance)
	{
		$instance = $old_instance;

		$instance['title'] = $new_instance['title'];
		$instance['authors'] = $new_instance['authors'];
		$instance['role'] = $new_instance['role'];
		$instance['role__not_in'] = $new_instance['role__not_in'];
		$instance['variations'] = $new_instance['variations'];

		$instance['bg-color'] = $new_instance['bg-color'];
		$instance['bg-color2'] = $new_instance['bg-color2'];
		$instance['hide_desktop'] = $new_instance['hide_desktop'];
		$instance['hide_mobile'] = $new_instance['hide_mobile'];
		$instance['others'] = $new_instance['others'];
		$instance['number'] = $new_instance['number'];
		$instance['dark_mode'] = $new_instance['dark_mode'];

		return $instance;
	}

  // Back-end
	public function form($instance)
	{
		$defaults = array( 
			'title' => esc_html__('Yazarlarımızdan', 'kanews'), 
			'role' => '', 
			'role__not_in' => '', 
			'bg-color' => '', 
			'bg-color2' => '', 
			'authors' => '', 
			'variations' => '1', 
			'number' => 5, 
			'others' => '',
			'dark_mode' => 'off',
			'hide_desktop' => 'off',
			'hide_mobile' => 'off',
		);
		$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('variations'),
					'name' => $this->get_field_name('variations'),
					'label' => __('Görünüm', 'kanews'),
					'value' => $instance['variations'],
					'options' => [
						'1' => '1',
						'2' => '2'
					]
				],
				[
					'type' => Kanews_Form_Elements::TYPE_NUMBER,
					'id' => $this->get_field_id('number'),
					'name' => $this->get_field_name('number'),
					'label' => __('Yazar Sayısı', 'kanews'),
					'value' => $instance['number']
				],
				[
					'type' => Kanews_Form_Elements::TYPE_TOGGLE,
					'id' => $this->get_field_id('others'),
					'name' => $this->get_field_name('others'),
					'label' => __('Diğer Yazarlarımız', 'kanews'),
					'value' => $instance['others']
				],
			]
		]);

		// Yazar Ayarları
		Kanews_Form_Elements::render_accordion_field([
			'title' => __('Yazar Ayarları', 'kanews'),
			'content' => [
				[
					'type' => Kanews_Form_Elements::TYPE_TEXT,
					'id' => $this->get_field_id('authors'),
					'name' => $this->get_field_name('authors'),
					'label' => __('Gösterilecek Yazarlar', 'kanews'),
					'description' => __('Yazar idlerini virgül ile ayırarak girin', 'kanews'),
					'value' => $instance['authors']
				],
				[
					'type' => Kanews_Form_Elements::TYPE_SELECT,
					'id' => $this->get_field_id('role'),
					'name' => $this->get_field_name('role'),
					'label' => __('Gösterilecek Rol', 'kanews'),
					'value' => $instance['role'],
					'options' => [
						'' => __('Hepsi', 'kanews'),
						'Administrator' => __('Yönetici', 'kanews'),
						'Editor' => __('Editör', 'kanews'),
						'Author' => __('Yazar', 'kanews'),
						'columist' => __('Köşe Yazarı', 'kanews'),
						'Contributor' => __('İçerik Sağlayıcı', 'kanews'),
						'Subscriber' => __('Üye', 'kanews')
					]
				],
				[
					'type' => Kanews_Form_Elements::TYPE_SELECT,
					'id' => $this->get_field_id('role__not_in'),
					'name' => $this->get_field_name('role__not_in'),
					'label' => __('Gösterilmeyecek Rol', 'kanews'),
					'value' => $instance['role__not_in'],
					'options' => [
						'' => __('Seçim Yapın', 'kanews'),
						'Administrator' => __('Yönetici', 'kanews'),
						'Editor' => __('Editör', 'kanews'),
						'Author' => __('Yazar', 'kanews'),
						'columist' => __('Köşe Yazarı', 'kanews'),
						'Contributor' => __('İçerik Sağlayıcı', 'kanews'),
						'Subscriber' => __('Üye', 'kanews')
					]
				]
			]
		]);

		// Görünüm Ayarları
		Kanews_Form_Elements::render_accordion_field([
			'title' => __('Görünüm 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_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_mobile'),
					'name' => $this->get_field_name('hide_mobile'),
					'label' => __('Mobilde Gizle', 'kanews'),
					'value' => $instance['hide_mobile']
				],
				[
					'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']
				]
			]
		]);
	}
}
?>