<?php

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

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

// Widget Class
class kanews_widget_class_video extends WP_Widget {

  // Create
	public function __construct(){
		$widget_ops = array('classname' => 'kanews_widget_video kan-section-flat');
		$control_ops = array('id_base' => 'kanews_widget_video');
		parent::__construct('kanews_widget_video', ''.KAN_THEME_NAME .' - '.__( "Video Galeri" , '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;
		}

		$title = apply_filters('widget_title', isset($instance['title']) ? $instance['title'] : '' );

		$subs_link = (isset($instance['subs_link'])) ? $instance['subs_link'] : '';
		$counter = (isset($instance['counter'])) ? $instance['counter'] : '+100K';
		$categories = (isset($instance['categories'])) ? $instance['categories'] : '';
    $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';
		$format = !empty($instance['format']) ? $instance['format'] : '';
		$post_type = !isset($instance['include_columist']) ? 'post' : array('post', 'columist');
		$is_do_not_dublicate = $instance['postnotin'] == 'on' ? true : false;
		$tags = (isset($instance['tags'])) ? $instance['tags'] : '';
		$autoplay = isset($instance['autoplay']) && $instance['autoplay'] == 'on';

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

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

		$thumbnail = 'kanews-manset-3';
		$col = 'col-12 col-lg-8';
		$col_sidebar = 'col-12 col-lg-4';
		
		if(isset($args['id']))
		$sidebar = explode('-', $args['id']);
		else
		$sidebar = array('0' => 'home', '1' => 'content');
		
		if($sidebar[1] == 'content') {
			$col = 'col-12 col-lg-7 no-gutter';
			$col_sidebar = 'col-12 col-lg-5 no-gutter';
		}elseif($sidebar[1] == 'sidebar') {
			$col = 'col-12 no-gutter';
			$col_sidebar = 'col-12 no-gutter';
			$thumbnail = 'kanews-manset-4';
		}

    if ($kanews_query->have_posts()) :
			$widget_id = '#'. $args['widget_id'];
			$output_css = '';
			if( $bg_color != '' && $bg_color2 != '') {
				$output_css .= "
				.light-mode $widget_id .kanews-video-playlist {
					background: linear-gradient(135deg,  $bg_color, $bg_color2 ) !important;
				}
				";
			}
			if( !empty($output_css) ) {
				echo "<style id='kanews-theme-inline-$widget_id' scoped type=\"text/css\">".( kan_minify_css($output_css) ) ."</style>";
			}
			?>
			<div id="<?php echo $args['widget_id']; ?>" class="col-12"> 
				<div class="kanews-video-playlist kanews-section">
					<?php if(!empty($title)) : ?>
						<div class="kanews-video-playlist-header">
							
							<h3 class="stroke-shadow"><?php echo $title; ?></h3>
							<?php if(!empty($subs_link)): ?>
								<a href="<?php echo $subs_link; ?>" class="kanews-subscribe-btn">
									<?php esc_html_e('Abone Ol', 'kanews'); ?>
									<?php if(!empty($counter)) : ?>
										<span class="counter"><?php echo $counter; ?></span>
									<?php endif; ?>
								</a>
							<?php endif; ?>
						</div>
					<?php endif; ?>

					<div class="d-flex flex-wrap">
						<div class="<?php echo $col; ?>">
							<div class="kanews-video-playlist-main">
								<?php 
								// İlk videoyu ana alana yerleştir
								if($kanews_query->have_posts()): 
									$kanews_query->the_post();
									global $post;
									$video_url = get_post_meta($post->ID, 'video_embed', true);
									if (empty($video_url)) {
										$video_url = get_post_meta($post->ID, 'iframe_src', true);
									}
									if (empty($video_url)) {
										$video_url = get_post_meta($post->ID, 'video_src', true);
									}
									
									if($video_url):
										// Video URL'sini temizle ve platform kontrolü yap
										$video_url = esc_url($video_url);
										
										if(strpos($video_url, 'youtube.com') !== false || strpos($video_url, 'youtu.be') !== false) {
											// YouTube video ID'sini al
											preg_match('/(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/', $video_url, $matches);
											$video_id = $matches[1];
											
											// YouTube Embed URL'sini oluştur
											$embed_url = 'https://www.youtube.com/embed/' . $video_id . '?enablejsapi=1&rel=0&showinfo=0';
											if ($autoplay) {
												$embed_url .= '&autoplay=1&mute=1';
											} else {
												$embed_url .= '&autoplay=0';
											}
											
											echo '<div class="kanews-video" data-video-id="' . esc_attr($video_id) . '" data-video-type="youtube">';
											echo '<iframe 
													src="' . esc_url($embed_url) . '" 
													frameborder="0" 
													allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" 
													allowfullscreen
													loading="lazy"></iframe>';
											echo '</div>';
						
											
										} elseif(strpos($video_url, 'vimeo.com') !== false) {
											// Vimeo video ID'sini al
											preg_match('/vimeo\.com\/([0-9]+)/', $video_url, $matches);
											$video_id = $matches[1];
											
											// Vimeo Embed URL'sini oluştur
											$embed_url = 'https://player.vimeo.com/video/' . $video_id;
											if ($autoplay) {
												$embed_url .= '?autoplay=1&muted=1';
											}
											
											echo '<div class="kanews-video" data-video-id="' . esc_attr($video_id) . '" data-video-type="vimeo">';
											echo '<iframe 
													width="100%" 
													height="100%" 
													src="' . esc_url($embed_url) . '" 
													frameborder="0" 
													allow="autoplay; fullscreen; picture-in-picture" 
													allowfullscreen></iframe>';
											echo '</div>';
										} else {
											// Diğer video platformları veya direkt iframe/video src için
											if (filter_var($video_url, FILTER_VALIDATE_URL)) {
												if (pathinfo($video_url, PATHINFO_EXTENSION)) {
													// Direkt video dosyası
													echo '<div class="kanews-video" data-video-type="direct">';
													$video_attrs = ' controls';
													if ($autoplay) {
														$video_attrs .= ' autoplay muted';
													}
													echo '<video width="100%" height="100%"' . $video_attrs . '>
															<source src="' . esc_url($video_url) . '" type="video/mp4">
															</video>';
													echo '</div>';
												} else {
													// iframe src
													echo '<div class="kanews-video" data-video-type="iframe">';
													echo '<iframe 
															src="' . esc_url($video_url) . '" 
															frameborder="0" 
															allowfullscreen></iframe>';
													echo '</div>';
												}
											}
										}

										echo '<div class="kanews-post-content">';
											echo '<div class="content-wrapper hidden-mobile">';
											echo kanews_primary_category($post->ID);
											the_title(sprintf('<h3 class="kanews-post-headline truncate-2"><a href="%s" rel="bookmark">', esc_url(get_permalink())), '</a></h3>');
											echo '</div>';
											// İçeriğe git butonu
											echo '<a href="' . esc_url(get_permalink()) . '" class="kanews-label">';
											echo '<span>' . esc_html__('İçeriğe Git', 'kanews') . '</span>';
											echo '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="5" y1="12" x2="19" y2="12"></line><polyline points="12 5 19 12 12 19"></polyline></svg>';
											echo '</a>';
											echo '</div>';
									else:
										// Video URL'si yoksa thumbnail göster
													?>
												<a href="<?php the_permalink(); ?>" class="kanews-post-href" aria-label="<?php the_title(); ?>"></a>		
												<?php kanews_post_thumbnail($thumbnail, 'kanews-post-thumb'); ?>
									<?php endif; ?>
									
									<?php if($is_do_not_dublicate) {
										Kanews\Helper::do_not_dublicate($post->ID);
									} ?>
								<?php endif; ?>
							</div>
						</div>

						<div class="<?php echo $col_sidebar; ?>">
							<div class="kanews-video-playlist-sidebar">
								<?php 
								// Diğer videoları listele
								$kanews_query->rewind_posts(); // Query'yi başa saralım
								while($kanews_query->have_posts()): 
									$kanews_query->the_post(); 
									global $post;
									$video_url = get_post_meta($post->ID, 'video_embed', true);
									if (empty($video_url)) {
										$video_url = get_post_meta($post->ID, 'iframe_src', true);
									}
									if (empty($video_url)) {
										$video_url = get_post_meta($post->ID, 'video_src', true);
									}

									// İlk video için active class ekleyelim
									$is_active = $kanews_query->current_post === 0 ? ' is-active' : '';
								?>
									<div class="kanews-post-item kanews-post-small-item<?php echo $is_active; ?>" data-video-url="<?php echo esc_url($video_url); ?>">
											<?php kanews_post_thumbnail('thumbnail', 'kanews-post-thumb'); ?>
											<div class="kanews-post-content">
											<h3 class="kanews-post-headline truncate-3 truncate">
												<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
											</h3>
										</div>
												</div>
								<?php 
									if($is_do_not_dublicate) {
										Kanews\Helper::do_not_dublicate($post->ID);
									}
								endwhile; 
								wp_reset_postdata(); 
								?>
							</div>
						</div>
					</div>

				</div>
			</div>
		<?php endif; ?>
	<?php }
  
  // Update Form
	public function update($new_instance, $old_instance)
	{
		$instance = $old_instance;
		$instance['title'] = strip_tags($new_instance['title']);
		$instance['subs_link'] = strip_tags($new_instance['subs_link']);
		$instance['counter'] = strip_tags($new_instance['counter']);	
		$instance['categories'] = $new_instance['categories'];
		$instance['tags'] = $new_instance['tags'];
		$instance['include_columist'] = $new_instance['include_columist'];
		$instance['posts'] = $new_instance['posts'];
		$instance['offset'] = $new_instance['offset'];
		$instance['sortby'] = $new_instance['sortby'];
		$instance['format'] = $new_instance['format'];
    $instance['postnotin'] = $new_instance['postnotin'];
		$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['autoplay'] = $new_instance['autoplay'];
		
		return $instance;
	}


  // Back-end
	public function form($instance)
	{
		$defaults = array( 
			'title' => '', 
			'subs_link' => '', 
			'postnotin'  => '', 
			'tags'  => array(), 
			'categories' => array(), 
			'posts' => 10, 
			'sortby' => 'recent', 
			'format' => 'video', 
			'date_range' => '0', 
			'offset' => '0',
			'counter' => '+100K',
			'bg-color' => '',
			'bg-color2' => '',
			'include_columist' => 'off',
			'hide_desktop' => 'off',
			'hide_mobile' => 'off',
			'autoplay' => '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_TEXT,
					'id' => $this->get_field_id('subs_link'),
					'name' => $this->get_field_name('subs_link'),
					'label' => __('Abone Ol Linki', 'kanews'),
					'value' => $instance['subs_link']
			 ],
				[
					'type' => Kanews_Form_Elements::TYPE_TEXT,
					'id' => $this->get_field_id('counter'),
					'name' => $this->get_field_name('counter'),
					'label' => __('Abone Sayısı', 'kanews'),
					'value' => $instance['counter']
				],
				[
					'type' => Kanews_Form_Elements::TYPE_TOGGLE,
					'id' => $this->get_field_id('autoplay'),
					'name' => $this->get_field_name('autoplay'),
					'label' => __('Otomatik Oynat', 'kanews'),
					'value' => $instance['autoplay']
				]
		 ]
		]);

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

		// Renk Ayarlarıı
		Kanews_Form_Elements::render_accordion_field([
			'title' => __('Renk Ayarlarıı', 'kanews'),
			'content' => [
				[
					'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']
			 ]
		 ]
		]);



	}
}