<?php
defined( 'ABSPATH' ) || exit; // Exit if accessed directly

// require_once dirname( __FILE__ ) . '/Widgets.php';
require_once dirname( __FILE__ ) . '/Rewrite.php';


/*-----------------------------------------------------------------------------------*/
# Theme Option
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( 'kanews_get_option' ) ) {
	function kanews_get_option( $option, $default = null ) {
		// Cache the theme settings
		if( ! empty( $GLOBALS['kanews_options'] ) ){
			$get_options = $GLOBALS['kanews_options'];
		}
		else{
			$get_options = get_option( 'kanews_options');
			$GLOBALS['kanews_options'] = $get_options;
		}

		if( isset( $get_options[ $option ] ) ) {
			return $get_options[ $option ];
		}

		if ( $default  ){
			return $default;
		}

		return false;
	}
}
if ( ! function_exists( 'kanews_get_option2' ) ) {
	function kanews_get_option2( $option, $default = null ) {
		// Cache the theme settings
		if( ! empty( $GLOBALS['kanews_translate'] ) ){
			$get_options = $GLOBALS['kanews_translate'];
		}
		else{
			$get_options = get_option( 'kanews_translate');
			$GLOBALS['kanews_translate'] = $get_options;
		}

		if( isset( $get_options[ $option ] ) ) {
			return $get_options[ $option ];
		}

		if ( $default  ){
			return $default;
		}

		return false;
	}
}

if ( ! function_exists( 'kanews_get_amp_option' ) ) {
	function kanews_get_amp_option( $option, $default = null ) {
		// Cache the theme settings
		if( ! empty( $GLOBALS['kanews_amp'] ) ){
			$get_options = $GLOBALS['kanews_amp'];
		}
		else{
			$get_options = get_option( 'kanews_amp');
			$GLOBALS['kanews_amp'] = $get_options;
		}

		if( isset( $get_options[ $option ] ) ) {
			return $get_options[ $option ];
		}

		if ( $default  ){
			return $default;
		}

		return false;
	}
}

/*-----------------------------------------------------------------------------------*/
# Lazy Load for entry images
/*-----------------------------------------------------------------------------------*/
function kanews_lazyload_active(){
	if( ! kanews_get_option('lazy') || is_admin() || is_feed() || is_preview() )
	return false;

	if( function_exists( 'is_amp_endpoint' ) && is_amp_endpoint() )
	return false;

	return true;
}

// Content
function kanews_lazyload_post_content( $content ) {
	if ( kanews_lazyload_active() ) {
		if ( function_exists( 'is_amp_endpoint' ) && is_amp_endpoint() ) {
			return $content;
		}
		if ( is_feed()
			|| intval( get_query_var( 'print' ) ) === 1
			|| intval( get_query_var( 'printpage' ) ) === 1
			|| strpos( $_SERVER['HTTP_USER_AGENT'], 'Opera Mini' ) !== false
		) {
			return $content;
		}

		$matches            = array();
		$resp_replace       = 'data-sizes="auto" data-srcset=';
		$skip_images_regex  = '/class=".*kanews-lazy.*"/';
		$skip_images_regex2 = '/kanews-ignore-lazy/';
		$placeholder        = kanews_lazyload_placeholder();
		preg_match_all( '/<iframe\s+.*?>/', $content, $matches_iframe );

		$search  = array();
		$replace = array();


		foreach ( $matches_iframe[0] as $iframe_html ) {
			// Eğer iframe wp_embed tarafından oluşturulmuşsa (class="wp-embedded-content" içeriyorsa), atla
			if ( strpos( $iframe_html, 'class="wp-embedded-content"' ) !== false ) {
				continue; // Site içi embed olduğu için lazy load uygulama
			}
			// Don't to the replacement if a skip class is provided and the image has the class.
			if ( ! preg_match( $skip_images_regex, $iframe_html ) && ! preg_match( $skip_images_regex2, $iframe_html ) ) {
				$replace_html = preg_replace( '/<iframe(.*?)src=/i', '<iframe$1src="' . $placeholder . '" data-src=', $iframe_html );

				$replace_html = kan_replace_class( $replace_html, 'kanews-lazy' );

				array_push( $search, $iframe_html );
				array_push( $replace, $replace_html );
			}
		} // End foreach().

		$content = str_replace( $search, $replace, $content );
	}
	return $content;
}


// Disable Srcset
function kanews_lazyload_disable_srcset( $sources ) {
	if( kanews_lazyload_active() ){
		return false;
	}
	return $sources;
}

function allow_data_protocol_urls( $allowed_protocols ) {
	return array_merge( $allowed_protocols, array( 'data' ) );
}

add_filter( 'kses_allowed_protocols', 'allow_data_protocol_urls', 10);

// Thumbnail
function kanews_add_lazyload_to_attachment_image( $attr, $attachment ) {
	if( ! kanews_lazyload_active() ) {
		return $attr;
	}

	$attr['class'] 	 	 .= ' kanews-lazy';  
	$attr['data-sizes'] = 'auto';
	$attr['data-src']   = $attr['src'];
	$attr['src'] 				= kanews_lazyload_placeholder();
	$classes 						= explode(" ", $attr['class']);

	if ( isset( $attr['srcset'] ) ) {
		unset( $attr['srcset'] );
	}
	
	if ( isset( $attr['loading'] ) ) {
		unset( $attr['loading'] );
	}

	foreach($classes as $sa) {
		if($sa == 'size-kanews-post-4' || $sa == 'size-kanews-post-6') {
			$attr['src'] =  kanews_lazyload_placeholder('2e3');
		} elseif($sa == 'size-kanews-post-8' ) {
			$attr['src'] =  kanews_lazyload_placeholder('3e1');
		} elseif($sa == 'size-kanews-post-1' || $sa == 'size-kanews-manset-4') {
			$attr['src'] =  kanews_lazyload_placeholder('3e2');
		}elseif($sa == 'size-kanews-manset-5') {
			$attr['src'] =  kanews_lazyload_placeholder('1e1');
		}
	}
	
  return $attr;
}

// SiteGround Lazy Load compatibility.
add_filter( 'sgo_lazy_load_exclude_classes', 'kan_exclude_from_sg' );
function kan_exclude_from_sg( $classes ) {
	$classes[] = 'kanews-lazy';
	$classes[] = 'kanews-ignore-lazyload';
	return $classes;
}

// JetPack Lazy Load compatibility.
add_filter( 'jetpack_lazy_images_blacklisted_classes', 'kan_exclude_from_jp_lazy_load', 999, 1 );
function kan_exclude_from_jp_lazy_load( $classes ) {
	$classes[] = 'kanews-lazy';
	$classes[] = 'kanews-ignore-lazy';
	return $classes;
}
/*-----------------------------------------------------------------------------------*/
# Header Center
/*-----------------------------------------------------------------------------------*/
function kanews_header_center_module() {
	$option = kanews_get_option('header-center');
	$currencies = (kanews_get_option('header-center-currencies') != '') ? kanews_get_option('header-center-currencies') : '';
	switch($option) {
		case 'search':
			echo kanews_header_search_form('style1');
		break;
		case 'custom':
			echo do_shortcode( kanews_get_option('header-center-custom') );
		break;
		case 'currencies': ?>
			<div class="site-currencies"><div class="d-flex"><?php Kanews\Currencies::get_currencies($currencies, true, true); ?></div></div>
		<?php break;
	}
}

/*-----------------------------------------------------------------------------------*/
# SubHeader Left Modules
/*-----------------------------------------------------------------------------------*/
function kanews_subheader_left_module() {
	$option = kanews_get_option('subheader-left', array());
	if(!is_array($option))
	$option = array($option);
	$currencies = (kanews_get_option('subheader-left-currencies') != '') ? kanews_get_option('subheader-left-currencies') : '';

	if(in_array('currencies', $option)) { ?>
		<div class="site-currencies"><div class="d-flex"><?php Kanews\Currencies::get_currencies($currencies, false); ?></div></div>
	<?php } if(in_array('breaking-news', $option)) {
		$cats     = (!empty(kanews_get_option('subheader-left-bn-cats'))) ? kanews_get_option('subheader-left-bn-cats') : '';
		$count    = (!empty(kanews_get_option('subheader-left-bn-count'))) ? kanews_get_option('subheader-left-bn-count') : '5';
		$sortby    = kanews_get_option('subheader-left-bn-sortby') == 'recent' ? 'DESC' : 'modified';
		$title    = kanews_translate('breaking-new-text', esc_html__( 'Son Gelişmeler', 'kanews' ));
		$query_args = array(
			'number'				=> $count,
			'id'    				=> $cats,
			'sortby' 				=> $sortby
		);

		if(is_singular())
		$query_args['exclude'] = array(get_the_ID());	
		
		$kanews_query = kan_query( $query_args );
		kanews_breaking_news_ticker($title, $kanews_query, true, true, $sortby );
	} if(in_array('menu', $option)) { ?>
		<div class="site-subheader-menu">
			<?php if ( has_nav_menu( 'subheader-left' ) ) :
				wp_nav_menu( array(
					'theme_location' => 'subheader-left',
					'menu_class'     => 'd-flex',
					'depth'     		 => '1',
					'container'      => false,
				));
			else: ?>
				<ul class="d-flex"><li><a href="<?php echo admin_url( 'nav-menus.php' ); ?>"><?php esc_html_e( 'Menü Oluştur', 'kanews' ); ?></a></li></ul>
			<?php endif; ?>
		</div>
	<?php }if(in_array('html', $option)) { ?>
		<?php echo kanews_get_option('subheader-left-editor'); ?>
	<?php }if(in_array('date', $option)) { ?>
		<?php echo do_shortcode('[date-today format="'.kanews_get_option('subheader-left-date-format', 'd M Y H:i').'"]'); ?>
	<?php } if(in_array('weather', $option)) { $city = ( is_user_logged_in() && !empty($city_meta = get_the_author_meta( 'my_city', get_current_user_id() )) ) ? $city_meta : kanews_get_option('subheader-weather-city', 'İstanbul');  ?>
		<div data-toggle="kanews-weather-select-city" class="kanews-city-weather-wrapper" data-city="<?php echo $city; ?>"></div>
		<?php echo kanews_get_turkey_cities('kanews-weather-select-city'); ?>
	<?php }
}

/*-----------------------------------------------------------------------------------*/
# SubHeader Right Modules
/*-----------------------------------------------------------------------------------*/
function kanews_subheader_right_module() {
	$option = kanews_get_option('subheader-right', array());
	$currencies = (kanews_get_option('subheader-right-currencies') != '') ? kanews_get_option('subheader-right-currencies') : '';
	if(!is_array($option))
	$option = array($option);

	if(in_array('weather', $option)) {  $city = ( is_user_logged_in() && !empty($city_meta = get_the_author_meta( 'my_city', get_current_user_id() )) ) ? $city_meta : kanews_get_option('subheader-weather-city2', 'İstanbul'); ?>
		<div data-toggle="kanews-weather-select-city2" class="kanews-city-weather-wrapper" data-city="<?php echo $city; ?>"></div>
		<?php echo kanews_get_turkey_cities('kanews-weather-select-city2'); ?>
	<?php } if(in_array('currencies', $option)) { ?>
		<div class="site-currencies"><div class="d-flex"><?php Kanews\Currencies::get_currencies($currencies, false); ?></div></div>
		<?php
	} if(in_array('menu', $option)) {  ?>
		<div class="site-subheader-menu">
			<?php if ( has_nav_menu( 'subheader-right' ) ) :
				wp_nav_menu( array(
					'theme_location' => 'subheader-right',
					'menu_class'     => 'd-flex',
					'depth'     		 => '1',
					'container'      => false,
				));
			else: ?>
				<ul class="d-flex"><li><a href="<?php echo admin_url( 'nav-menus.php' ); ?>"><?php esc_html_e( 'Menü Oluştur', 'kanews' ); ?></a></li></ul>
			<?php endif; ?>
		</div>
	<?php } if(in_array('html', $option)) {  ?>
		<?php echo kanews_get_option('subheader-right-editor'); ?>
	<?php } if(in_array('date', $option)) {  ?>
		<?php echo do_shortcode('[date-today format="'.kanews_get_option('subheader-right-date-format', 'd M Y H:i').'"]'); ?>
	<?php }

}

/*-----------------------------------------------------------------------------------*/
# Mobile Menu
/*-----------------------------------------------------------------------------------*/
function kanews_mobile_menu() {
	if( ! kan_is_mobile() )
	return;
	$copyright = !empty(kanews_get_option('mobile-menu-footer-text')) ? kanews_get_option('mobile-menu-footer-text') : '';
	$style = !empty(kanews_get_option('mobile-menu-style')) ? kanews_get_option('mobile-menu-style') : '1';
	$search = '<div class="site-mobile-menu-header"><form id="search-autocomplete" role="search" method="get" action="' . esc_url( home_url( '/' ) ) . '">
		<input class="search-autocomplete" type="text" placeholder="' . esc_html__( 'Aramak istediğiniz kelimeyi yazın..', 'kanews' ).'" value="' . get_search_query() . '" name="s" />
	</form></div>';
	$args = array(
		'theme_location' => 'menu-2',
		'container_class'=> 'site-mobile-menu-nav',
		'depth'     		 => 3,
	);
	?>
	<div id="site-mobile-menu" class="site-mobile-menu-style-<?php echo $style; ?>">
		<div class="site-mobile-menu-overlay" data-toggle="site-mobile-menu"></div>
		<div class="site-mobile-menu-close" data-toggle="site-mobile-menu"><i class="icon-close"></i></div>
		<div class="site-mobile-menu-wrapper">
			<?php if(kanews_get_option('mobile-menu-search') != false) echo $search; ?>
			<div class="site-mobile-menu-inside">
				<?php if ( has_nav_menu( 'menu-2' ) ) : ?>
					<?php wp_nav_menu( $args ); ?>
				<?php endif; ?>
				
				<div class="site-mobile-menu-footer d-flex flex-column">
					<?php if( kanews_get_option('mode') || ( kanews_get_option('kanews-insights') == true && kanews_get_option('kanews-insights-button') == true && kanews_insights_control() == false )  ): ?>
						<ul class="site-mobile-footer-menu">
							<?php if(kanews_get_option('kanews-insights') == true && kanews_get_option('kanews-insights-button') == true && kanews_insights_control() == false): ?>
								<li class="d-flex align-items-center justify-content-between"><label><?php esc_html_e( 'Ücretli Üyelik', 'kanews' ); ?></label> <span><a href="<?php echo kanews_insights_page_url(); ?>"><?php esc_html_e( 'Başlat', 'kanews' ); ?></a></span> </li>
							<?php endif; ?>
							<?php if( kanews_get_option('mode') ) : ?>
								<li class="d-flex align-items-center justify-content-between site-mobile-theme-toggle">
									<label><?php esc_html_e( 'Gece Modu', 'kanews' ); ?></label>
									<div class="site-mobile-theme-toggle__control">
										<?php echo kanews_dark_mode_button(); ?>
									</div>
								</li>
							<?php endif; ?>
						</ul>
					<?php endif; ?>
					<?php 
					if($copyright != '') {
						$footer_vars = array( '%year%', '%site%', '%url%' );
						$footer_val  = array( date('Y') , get_bloginfo('name') , esc_url(home_url( '/' )) );
						echo '<p>'. str_replace( $footer_vars , $footer_val , $copyright) . '</p>'; 
					} 
					?>
					</div>
				
				
			</div>
		</div>
	</div>
	<?php 
}

/*-----------------------------------------------------------------------------------*/
# Home Archives
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( 'kanews_recent_posts' ) ) {
	function kanews_recent_posts($loc, $title = '', $htag = 'h4') {
		$style = (kanews_get_option($loc.'-recent-post-style') != '') ? kanews_get_option($loc.'-recent-post-style') : '1';
		$count = $counter = 0;

		if($loc == 'cat') {
			$category = get_query_var('cat');
			$custom_title = get_term_meta($category, 'recent-post-section-title', true);
			$title = $custom_title != '' ? $custom_title : $title;
			$style = get_term_meta($category, 'category-recent-posts-style', true) != '' ? get_term_meta($category, 'category-recent-posts-style', true) : kanews_get_option( 'cat-recent-post-style' );
		}

		if ($style == 'disable') {
			if( is_paged(  ) )
			$style = '5';
			else
			return;
		}

		$classes = 'kanews-section';

		if( $loc == 'search' )
		$style = (isset($_GET['style']) && $_GET['style'] == 'grid') ? '2' : '1';

		if( $loc == 'cat-ilan' )
		$style = '3';
		
		if( $style == '2' || $style == '3' || $style == '6')	
		$classes = 'kanews-section kanews-section-flat';
		
		
		echo '<div class="col-12">';
			echo '<div class="kanews-posts-style-'.$style.' '.$classes.'">';
				echo kanews_widget_title($title, $htag);
				
				if ( have_posts() ) : 
					echo '<div class="row" kanews-data-load-more>';
						while ( have_posts() ) : the_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;
							}
							if( $loc == 'cat-ilan' )
							$style = '3x';
							get_template_part('template-parts/archives/article', $style);
							if( $loc != 'cat-ilan' )
							Kanews\Ads::ad_archives($style, $counter);
						endwhile;
					echo '</div>';
					if( $loc == 'cat-ilan' )
					kanews_pagination('ilan');
					else
					kanews_pagination();
				else:
					if( $loc == 'cat-ilan' ) {
						$notfound = 'Bugün yayınlanmış bir ilan bulunmamaktadır.';
						echo '<div class="kanews-no-post">
						<p>'.$notfound.'</p>
						</div>';
					} else
					get_template_part('template-parts/archives/article', 'none');
				endif;
			echo '</div>';
		echo '</div>';
	}
}

/*-----------------------------------------------------------------------------------
# Widget Area: Home Top Full
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( 'kanews_home_page_top' ) ) {
	function kanews_home_page_top() {
		if ( is_home() && ! is_paged() ) { 
			echo '<div class="kanews-widget-area kanews-widgets-top">';
				dynamic_sidebar( 'home-top-full' );
			echo '</div>';
		} 
	}
}

/*-----------------------------------------------------------------------------------*/
# Widget Area: Home Bottom Full
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( 'kanews_home_page_bottom' ) ) {
	function kanews_home_page_bottom() {
		if ( is_home() && ! is_paged() ) { 
			echo '<div class="kanews-widget-area kanews-widgets-top">';
				dynamic_sidebar( 'home-bottom-full' );
			echo '</div>';
		} 
	}
}

/*-----------------------------------------------------------------------------------*/
# Widget Area: Home Content
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( 'kanews_home_page_content_start' ) ) {
	function kanews_home_page_content_start() {
		echo '<div class="kanews-widget-area kanews-widgets-content">';
	}
}	
if ( ! function_exists( 'kanews_home_page_content_end' ) ) {
	function kanews_home_page_content_end() {
		echo '</div>';
	}
}	

if ( ! function_exists( 'kanews_home_page_content' ) ) {
	function kanews_home_page_content() {
		echo '<div id="content" class="col-12 col-lg-8 kanews-sticky">';
			echo '<div class="row">';
				if(!is_paged())
				dynamic_sidebar( 'home-content' );
				$title = (kanews_get_option('home-recent-post-title')) ? kanews_get_option('home-recent-post-title') : '';
				kanews_recent_posts('home', $title);
			echo '</div>';
		echo '</div>';
	}
}

if ( ! function_exists( 'kanews_home_page_sidebar' ) ) {
	function kanews_home_page_sidebar() {
		if(kan_is_mobile() && !kanews_get_option('home-sidebar') )
		return;
		echo '<div id="sidebar" class="col-12 col-lg-4 kanews-sticky">';
			echo '<div class="row" role="complementary">';
				dynamic_sidebar( 'home-sidebar' );
			echo '</div>';
		echo '</div>';
	} 
}

/*-----------------------------------------------------------------------------------*/
# Widget Area: Cat Top Full
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( 'kanews_cat_page_top' ) ) {
	function kanews_cat_page_top() {
		$category = get_category(get_query_var('cat'),false);
		$meta = get_term_meta( $category->term_id, 'hidden-category-desc', true);
		$meta_footer = get_term_meta( $category->term_id, 'category-desc-on-footer', true);
		$follow         = kanews_get_option('follow-categories');


		if(category_description($category) && ! $meta_footer && ! $meta && $meta != 'yes' ) {
			echo '<div id="category-header" class="kanews-section kanews-section-flat kanews-article-content"><div class="col-12 entry-content-inner">
			<div class="d-flex align-items-center mb-1">
			<h2 class="mb-0">'.get_cat_name( $category->term_id ).'</h2>';
			if($follow) {
				if(is_user_logged_in()) {
					$user_cats 			= get_user_option( 'kanews_subscribe_category', get_current_user_id() ) ? get_user_option( 'kanews_subscribe_category', get_current_user_id() ) : array('');
					$follow_class = in_array($category->term_id, $user_cats) ? 'category-subscribed' : '';
					$follow_cat = '<span data-cat-id="'.$category->term_id.'" class="kanews-category-subscribe-button hf1s '.$follow_class.'" role="tooltip" data-microtip-position="bottom" aria-label="'.esc_html__( 'Takip Et', 'kanews' ).'"><div class="check"></div> <div id="kanews-loader"></div></span>';
				} else {
					$follow_cat = '<span class="kanews-category-subscribe-button" data-toggle="kanews-modal-login" role="tooltip" data-microtip-position="bottom" aria-label="'.esc_html__( 'Takip etmek için giriş yap', 'kanews' ).'"><i class="icon-add"></i></span>';
				}
				echo '<div style="margin-left: 10px"><div class="kanews-label kanews-label-sm kanews-label-bg">'.esc_html__( 'Takip Et', 'kanews' ).'</div>'.$follow_cat.'</div>';
			}
			echo '</div>';
			echo do_shortcode(category_description($category));
			echo '</div></div>';
			
		}
		$category = $category->slug;
		
		if( ! is_paged() ) {
			if (  is_active_sidebar( 'home-top-full-'.$category ) ) { 
				
				echo '<div class="kanews-widget-area kanews-widgets-top">';
					dynamic_sidebar( 'home-top-full-'.$category );
				echo '</div>';
			} else {
				echo '<div class="kanews-widget-area kanews-widgets-top">';
					dynamic_sidebar( 'category-top-full' );
				echo '</div>';
			}
		}
	}
}

/*-----------------------------------------------------------------------------------*/
# Widget Area: Cat Bottom Full
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( 'kanews_cat_page_bottom' ) ) {
	function kanews_cat_page_bottom() {
		$category = get_category(get_query_var('cat'),false);
		$meta = get_term_meta( $category->term_id, 'hidden-category-desc', true);
		$meta_footer = get_term_meta( $category->term_id, 'category-desc-on-footer', true);

		$category = $category->slug;
		if ( ! is_paged() && is_active_sidebar( 'home-top-full-'.$category  )) { 
			echo '<div class="kanews-widget-area kanews-widgets-top">';
				dynamic_sidebar( 'home-bottom-full-'.$category );
			echo '</div>';
		} else {
			echo '<div class="kanews-widget-area kanews-widgets-top">';
				dynamic_sidebar( 'category-bottom-full' );
			echo '</div>';
		}

		$category = get_category(get_queried_object_id(  ),false);
		
		if(category_description($category) && $meta_footer && ! $meta && $meta != 'yes' ) {
			echo '<div id="category-header" class="kanews-section kanews-section-flat kanews-article-content"><div class="col-12 entry-content-inner">
			<div class="d-flex align-items-center mb-1">
			<h2 class="mb-0">'.get_cat_name( $category->term_id ).'</h2>';
			if($follow) {
				if(is_user_logged_in()) {
					$user_cats 			= get_user_option( 'kanews_subscribe_category', get_current_user_id() ) ? get_user_option( 'kanews_subscribe_category', get_current_user_id() ) : array('');
					$follow_class = in_array($category->term_id, $user_cats) ? 'category-subscribed' : '';
					$follow_cat = '<span data-cat-id="'.$category->term_id.'" class="kanews-category-subscribe-button hf1s '.$follow_class.'" role="tooltip" data-microtip-position="bottom" aria-label="'.esc_html__( 'Takip Et', 'kanews' ).'"><div class="check"></div> <div id="kanews-loader"></div></span>';
				} else {
					$follow_cat = '<span class="kanews-category-subscribe-button" data-toggle="kanews-modal-login" role="tooltip" data-microtip-position="bottom" aria-label="'.esc_html__( 'Takip etmek için giriş yap', 'kanews' ).'"><i class="icon-add"></i></span>';
				}
				echo '<div style="margin-left: 10px"><div class="kanews-label kanews-label-sm kanews-label-bg">'.esc_html__( 'Takip Et', 'kanews' ).'</div>'.$follow_cat.'</div>';
			}
			echo '</div>';
			echo do_shortcode(category_description($category));
			echo '</div></div>';
			
		}
		
	}
}

/*-----------------------------------------------------------------------------------*/
# Widget Area: Cat Content
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( 'kanews_cat_page_content_start' ) ) {
	function kanews_cat_page_content_start() {
		echo '<div class="kanews-widget-area kanews-widgets-content">';
	}
}	
if ( ! function_exists( 'kanews_cat_page_content_end' ) ) {
	function kanews_cat_page_content_end() {
		echo '</div>';
	}
}	

if ( ! function_exists( 'kanews_cat_page_content' ) ) {
	function kanews_cat_page_content() {
		$category = get_category(get_query_var('cat'),false);
		$category = $category->slug;
		echo '<div id="content" class="col-12 col-lg-8 kanews-sticky">';
			echo '<div class="row">';
				if ( ! is_paged() && is_active_sidebar( 'home-content-'.$category ) ) { 
					dynamic_sidebar( 'home-content-'.$category );
				}elseif(!is_paged() && is_active_sidebar('category-content')) {
					dynamic_sidebar( 'category-content' );
				}
				$title = (kanews_get_option('home-recent-post-title')) ? kanews_get_option('home-recent-post-title') : '';
				kanews_recent_posts('cat', $title, 'h2');
			echo '</div>';
		echo '</div>';
	}
}

if ( ! function_exists( 'kanews_cat_page_sidebar' ) ) {
	function kanews_cat_page_sidebar() {
		if(kan_is_mobile() && !kanews_get_option('cat-sidebar') )
		return;
		$category = get_category(get_query_var('cat'),false);
		$category = $category->slug;

		echo '<div id="sidebar" class="col-12 col-lg-4 kanews-sticky">';
			echo '<div class="row" role="complementary">';
				if(is_active_sidebar( 'home-sidebar-'.$category ) ) {
					dynamic_sidebar( 'home-sidebar-'.$category );
				} else {
					dynamic_sidebar( 'home-sidebar-cat' );
				}
			echo '</div>';
		echo '</div>';
	} 
}

/*-----------------------------------------------------------------------------------*/
# Widget Area: Page Top Full
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( 'kanews_custom_page_top' ) ) {
	function kanews_custom_page_top() {
		$category = get_queried_object_id();
		if ( is_active_sidebar( 'home-top-full-'.$category ) ) { 
			echo '<div class="kanews-widget-area kanews-widgets-top">';
				dynamic_sidebar( 'home-top-full-'.$category );
			echo '</div>';
		} 
	}
}

/*-----------------------------------------------------------------------------------*/
# Widget Area: Page Bottom Full
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( 'kanews_custom_page_bottom' ) ) {
	function kanews_custom_page_bottom() {
		$category = get_queried_object_id();
		if ( is_active_sidebar( 'home-bottom-full-'.$category  )) { 
			echo '<div class="kanews-widget-area kanews-widgets-top">';
				dynamic_sidebar( 'home-bottom-full-'.$category );
			echo '</div>';
		} 
	}
}

/*-----------------------------------------------------------------------------------*/
# Widget Area: Page Content
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( 'kanews_custom_page_content_start' ) ) {
	function kanews_custom_page_content_start() {
		echo '<div class="kanews-widget-area kanews-widgets-content">';
	}
}	
if ( ! function_exists( 'kanews_custom_page_content_end' ) ) {
	function kanews_custom_page_content_end() {
		echo '</div>';
	}
}	

if ( ! function_exists( 'kanews_custom_page_content' ) ) {
	function kanews_custom_page_content() {
		$category = get_queried_object_id();
		if ( is_active_sidebar( 'home-content-'.$category ) ) { 
			echo '<div id="content" class="col-12 col-lg-8 kanews-sticky">';
				echo '<div class="row">';
				dynamic_sidebar( 'home-content-'.$category );
				echo '</div>';
			echo '</div>';
		}
	}
}

if ( ! function_exists( 'kanews_custom_page_sidebar' ) ) {
	function kanews_custom_page_sidebar() {
		if(kan_is_mobile() && kanews_get_option('home-sidebar') )
		return;
		$category = get_queried_object_id();
		if(is_active_sidebar( 'home-sidebar-'.$category ) ) {
			echo '<div id="sidebar" class="col-12 col-lg-4 kanews-sticky">';
				echo '<div class="row" role="complementary">';
					
					dynamic_sidebar( 'home-sidebar-'.$category );
	
				echo '</div>';
			echo '</div>';
		}
	} 
}

/*-----------------------------------------------------------------------------------*/
# Entry Header
/*-----------------------------------------------------------------------------------*/
function kanews_entry_header($video = NULL){ 
	$pid = get_the_ID();
	$default_options = [
		'excerpt'     => (kanews_get_option('show-post-excerpt') == false) ? false : true,
		'cat' 				=> (kanews_get_option('show-post-cat') == false) ? false : true,
		'author' 			=> (kanews_get_option('show-post-author') == false) ? false : true,
		'date' 				=> (kanews_get_option('show-post-date') == false) ? false : true,
		'update-date' => (kanews_get_option('show-post-update-date') == false) ? false : true,
		'post-views'  => (kanews_get_option('show-post-views') == false) ? false : true,
		'reading-time'=> (kanews_get_option('show-post-reading-time') == false) ? false : true,
		'show-more'   => (kanews_get_option('show-post-more') == false) ? false : true
	];
	$single_options = [
		'excerpt-text'=> get_post_field('post_excerpt', $pid) ? wp_strip_all_tags(get_post_field('post_excerpt', $pid)) : get_post_meta( $pid, 'kanews_post_excerpt', true ),
		'excerpt'     => get_post_meta( $pid, 'show_post_excerpt', true ),
		'cat'			    => get_post_meta( $pid, 'show_post_cat', true ),
		'author' 			=> get_post_meta( $pid, 'show_post_author', true ),
		'date' 			  => get_post_meta( $pid, 'show_post_date', true ),
		'update-date' => get_post_meta( $pid, 'show_post_update_date', true ),
		'post-views'  => get_post_meta( $pid, 'show_post_views', true ),
		'reading-time'=> get_post_meta( $pid, 'show_post_read_time', true ),
		'show-more'		=> get_post_meta( $pid, 'show_post_more', true ),
	];

	$ilan_no = get_post_meta( get_the_ID(), 'kanews_bik_id', true);
	?>
	<div class="kanews-article-header">

		<?php if( empty($ilan_no) ): ?>
			<?php do_action('kanews_entry_meta_above'); ?>
			<?php kanews_breadcrumb($pid); ?>

		<?php endif; ?>

		<?php if( $custom_post_title = get_post_meta( $pid, 'kanews_post_title', true ) ) : ?>
			<h1 class="kanews-article-title"><?php echo $custom_post_title; ?></h1>
		<?php else: ?>
			<?php the_title( '<h1 class="kanews-article-title">', '</h1>' ); ?>
		<?php endif; ?>

		<?php if( empty($ilan_no) ): ?>

			<?php if($single_options['excerpt'] == 'on' && $single_options['exceprt-text'] != '' ): ?>
				<p><?php echo $single_options['excerpt-text']; ?></p>
			<?php elseif($single_options['excerpt'] != 'off' && $default_options['excerpt'] != false && $single_options['excerpt-text'] != ''  ): ?>
				<p><?php echo $single_options['excerpt-text']; ?></p>
			<?php endif; ?>
				
			<div class="kanews-article-meta">
				<div class="row justify-content-between align-items-center">
					<div class="kanews-article-meta-left col-12 col-lg">
						<div class="kanews-article-meta-left-inner d-flex">
		
							<?php if ( ! is_singular('columist') ) : ?>
								<?php if ( function_exists( 'coauthors_posts_links' ) ) : 
									$coauthors = get_coauthors();

									if ( ! $coauthors ) {
										return;
									}

									foreach( $coauthors as $coauthor ) { 

										$avatar = coauthors_get_avatar( $coauthor, 150, '', $coauthor->display_name, '' ); ?>
										<?php if($single_options['author'] == 'on' ): ?>
										<div class="kanews-post-author"><div class="author-avatar circle-animation"><svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" style="enable-background:new -580 439 577.9 194;" xml:space="preserve"> <circle cx="50" cy="50" r="40"></circle> </svg><?php echo $avatar; ?></div></div>
										<?php elseif($single_options['author'] != 'off' && $default_options['author'] != false  ): ?>
										<div class="kanews-post-author"><div class="author-avatar circle-animation"><svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" style="enable-background:new -580 439 577.9 194;" xml:space="preserve"> <circle cx="50" cy="50" r="40"></circle> </svg><?php echo $avatar; ?></div></div>
										<?php endif; ?>
										<?php } ?>
									

									<?php else: ?>
										<?php if($single_options['author'] == 'on' ): ?>
											<div class="kanews-post-author"><?php echo kanews_user_avatar( get_the_author_meta( 'ID' ), 48, 'hidden-mobile', 'yes'); ?></div>
										<?php elseif($single_options['author'] != 'off' && $default_options['author'] != false  ): ?>
											<div class="kanews-post-author"><?php echo kanews_user_avatar( get_the_author_meta( 'ID' ), 48, 'hidden-mobile', 'yes'); ?></div>
										<?php endif; ?>
									<?php endif; ?>
									
							<?php endif; ?>
							<div class="kanews-article-meta-left-text">
								<?php if ( ! is_singular('columist') ) : ?>
									<?php if($single_options['author'] == 'on' ): ?>
										<?php if ( function_exists( 'coauthors_posts_links' ) ) : ?>
										<div class="kanews-post-author-name author vcard"><?php echo sprintf(__( '%s tarafından hazırlandı', 'kanews' ), coauthors_posts_links( null, ' '.esc_html__( 've', 'kanews' ).' ', null, null, false )); ?></div>
										<?php else: ?>
										<div class="kanews-post-author-name author vcard"><?php echo sprintf(__( '%s tarafından yayınlandı', 'kanews' ), '<a href="'.esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ).'">'.get_the_author().'</a>'); ?></div>
										<?php endif; ?>
									<?php elseif($single_options['author'] != 'off' && $default_options['author'] != false  ): ?>
										<?php if ( function_exists( 'coauthors_posts_links' ) ) : ?>
										<div class="kanews-post-author-name author vcard"><?php echo sprintf(__( '%s tarafından hazırlandı', 'kanews' ), coauthors_posts_links( null, ' '.esc_html__( 've', 'kanews' ).' ', null, null, false )); ?></div>
										<?php else: ?>
										<div class="kanews-post-author-name author vcard"><?php echo sprintf(__( '%s tarafından yayınlandı', 'kanews' ), '<a href="'.esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ).'">'.get_the_author().'</a>'); ?></div>
										<?php endif; ?>
									<?php endif; ?>
								<?php endif; ?>
								
								<?php if($single_options['date'] == 'on' ): ?>
									<?php kanews_posted_on(); ?>
								<?php elseif($single_options['date'] != 'off' && $default_options['date'] != false  ): ?>
									<?php kanews_posted_on(); ?>
								<?php endif; ?>

								<?php if($single_options['update-date'] == 'on' ): ?>
									<?php kanews_post_updated(); ?>
								<?php elseif($single_options['update-date'] != 'off' && $default_options['update-date'] != false  ): ?>
									<?php kanews_post_updated(); ?>
								<?php endif; ?>
							</div>
						</div>
					</div>
					<div class="kanews-article-meta-right col-12 col-lg-auto">
						
						<?php if($single_options['reading-time'] == 'on' ): ?>
							<?php kanews_post_reading_time(get_post($pid)); ?>
						<?php elseif($single_options['reading-time'] != 'off' && $default_options['reading-time'] != false  ): ?>
							<?php kanews_post_reading_time(get_post($pid)); ?>
						<?php endif; ?>
						<?php if($single_options['post-views'] == 'on' ): ?>
							<?php echo Kanews\PostViews::get_post_views($pid, '', true, true); ?>
						<?php elseif($single_options['post-views'] != 'off' && $default_options['post-views'] != false  ): ?>
							<?php echo Kanews\PostViews::get_post_views($pid, '', true, true); ?>
						<?php endif; ?>
					</div>
				</div>
			</div>
			<?php do_action('kanews_entry_meta_below'); ?>
		<?php endif; ?>

		
	</div>
<?php }

/*-----------------------------------------------------------------------------------*/
# Entry Assets
/*-----------------------------------------------------------------------------------*/
function kanews_entry_assets($video = false){ 
	$pid = get_the_ID();
	$default_options = [
		'post-like'  => (kanews_get_option('post-like') == false) ? false : true,
		'post-share'  => (kanews_get_option('show-post-share') == false) ? false : true,
		'post-assets' => (kanews_get_option('show-post-assets') == false) ? false : true,
	];
	$single_options = [
		'post-share'  => get_post_meta( $pid, 'show_post_share', true ),
		'post-like'  => get_post_meta( $pid, 'show_post_like', true ),
		'post-assets' => get_post_meta( $pid, 'show_post_assets', true ),
	];
	$speech = get_post_meta( $pid, 'post_text_to_speech', true );
	$speech2 = get_post_meta( $pid, 'post_text_to_speech2', true );

	$ilan_no = get_post_meta( get_the_ID(), 'kanews_bik_id', true);
	?>


	<div class="kanews-article-action">
		<div class="row justift-content-between align-items-center">
			<?php if( empty($ilan_no) ) : ?>
			<div class="kanews-article-action-left flex-wrap col-12 col-lg d-flex align-items-center">
				<?php if(kanews_get_option('google-news-link') != ''): ?>
					<a class="kanews-service-link googlenews" target="_blank" rel="nofollow noopener" title="<?php esc_html_e( 'Google News ile Abone Ol', 'kanews' ); ?>" href="<?php echo kanews_get_option('google-news-link'); ?>"></a>
				<?php endif; ?>
				<?php if(kanews_get_option('news-services') && is_array(kanews_get_option('news-services'))): ?>
					<?php foreach( kanews_get_option('news-services') as $service ): ?>
						<?php if( $service['title'] != '' && $service['img'] != '' && $service['url'] != '' ): ?>
							<a target="_blank" rel="nofollow noopener" class="kanews-service-link" title="<?php echo esc_attr(sprintf( esc_html__('%s ile Abone Ol', 'kanews' ), $service['title'])); ?>" href="<?php echo esc_url($service['url']); ?>"><img loading="true" src="<?php echo $service['img']; ?>" alt="service" /></a>
						<?php endif; ?>
					<?php endforeach; ?>
				<?php endif; ?>
				<?php if( !empty($speech2) ) : ?>
					<div class="audio-icon" data-microtip-position="bottom" role="tooltip" aria-label="<?php echo esc_attr__( 'Sesli Dinle', 'kanews' ); ?>" data-src="<?php echo $speech2; ?>">
						<i class="icon-mic icon-2x"></i>
						<svg class="progress-circle" viewBox="0 0 36 36">
								<circle cx="18" cy="18" r="16"></circle>
						</svg>
					</div>

					<audio id="audio-player" style="display:none;"></audio>

					<script>
						document.addEventListener('DOMContentLoaded', function() {
						window.kanAudioPlayer = new KanAudioPlayer({
							playingIconURL: '<?php echo KAN_TEMPLATE_URL; ?>/assets/img/static/sound.gif',
							playLabel: 'Oynat',
							pauseLabel: 'Durdur'
						});
						});
					</script>
				<?php elseif((isset($speech['id']) && $speech['id'] != '') ): ?>

					<div class="audio-icon" data-microtip-position="bottom" role="tooltip" aria-label="<?php echo esc_attr__( 'Sesli Dinle', 'kanews' ); ?>" data-src="<?php echo (is_numeric(get_post_meta( $pid, 'post_text_to_speech', true )))  ? wp_get_attachment_url(get_post_meta( $pid, 'post_text_to_speech', true )) : get_post_meta( $pid, 'post_text_to_speech', true )['url']; ?>">
						<i class="icon-mic icon-2x"></i>
						<svg class="progress-circle" viewBox="0 0 36 36">
								<circle cx="18" cy="18" r="16"></circle>
						</svg>
					</div>

					<audio id="audio-player" style="display:none;"></audio>

					<script>
						document.addEventListener('DOMContentLoaded', function() {
							window.kanAudioPlayer = new KanAudioPlayer({
								playingIconURL: '<?php echo KAN_TEMPLATE_URL; ?>/assets/img/static/sound.gif',
								playLabel: 'Oynat',
								pauseLabel: 'Durdur'
							});
						});

					</script>

				<?php endif; ?>
			</div>
			<?php endif; ?>
			
			<div class="kanews-article-action-right col-12 col-lg-auto">
				<div class="d-flex align-items-center flex-wrap">
					<?php if( empty($ilan_no) ) : ?>
						<a class="kanews-label" title="<?php esc_html_e( 'Yorum Yap', 'kanews' ); ?>" href="#respond">
<svg width="24" height="24" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M7.04004 16C7.03989 19.3447 8.90259 22.4109 11.8709 23.9523C14.8392 25.4937 18.4189 25.2534 21.1546 23.3293L24.96 23.68V16C24.96 11.0516 20.9485 7.04004 16 7.04004C11.0516 7.04004 7.04004 11.0516 7.04004 16Z" stroke="currentColor" stroke-width="1.92" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M12.1602 17.5998C11.63 17.5998 11.2002 18.0296 11.2002 18.5598C11.2002 19.0899 11.63 19.5198 12.1602 19.5198V17.5998ZM17.2802 19.5198C17.8104 19.5198 18.2402 19.0899 18.2402 18.5598C18.2402 18.0296 17.8104 17.5998 17.2802 17.5998V19.5198ZM12.1602 13.7598C11.63 13.7598 11.2002 14.1896 11.2002 14.7198C11.2002 15.2499 11.63 15.6798 12.1602 15.6798V13.7598ZM19.8402 15.6798C20.3704 15.6798 20.8002 15.2499 20.8002 14.7198C20.8002 14.1896 20.3704 13.7598 19.8402 13.7598V15.6798ZM12.1602 19.5198H17.2802V17.5998H12.1602V19.5198ZM12.1602 15.6798H19.8402V13.7598H12.1602V15.6798Z" fill="currentColor"/>
</svg>
<span><?php echo comments_number( '0', '1', '%' ); ?></span></a>
								
					<?php endif; ?>

					
					
					<?php if($single_options['post-share'] == 'on' ): ?>
						<?php kanews_post_share($pid);?>
					<?php elseif($single_options['post-share'] != 'off' && $default_options['post-share'] != false  ): ?>
						<?php kanews_post_share($pid);?>
					<?php endif; ?>

					<?php if( empty($ilan_no) ) : ?>
						<?php kanews_like_button($pid); ?>
						<?php if( kanews_get_option('login-system') ) : ?>
						<?php echo kanews_add_bookmark($pid); ?>
						<?php endif; ?>
					<?php endif; ?>
				</div>
			</div>
		</div>
	</div>
	
<?php }

/*-----------------------------------------------------------------------------------*/
# List Comments
/*-----------------------------------------------------------------------------------*/
function pressfore_comment_time_output($date, $d, $comment){
	return sprintf( _x( '%s önce', '%s = human-readable time difference', 'kanews' ), human_time_diff( get_comment_time( 'U' ), current_time( 'timestamp' ) ) );
}
// add_filter('get_comment_date', 'pressfore_comment_time_output', 10, 3);
if (!function_exists('kanews_list_comments')) :
    function kanews_list_comments($comment, $args, $depth)
    {
			$GLOBALS['comment'] = $comment;
			switch ($comment->comment_type) :
					case 'pingback' :
					case 'trackback' :
					default :
						kanews_get_comment($comment, $args, $depth);
						break;
			endswitch;
    }
endif;

function kanews_get_comment($comment, $args, $depth) {
	?>
	<li <?php comment_class(); ?>  id="comment-<?php comment_ID(); ?>" data-id="<?php comment_ID(); ?>">
		<div class="site-comment-post">
				<div class="comment-author-avatar">
					<?php echo kanews_user_avatar($comment->user_id, 48); ?>
				</div>
				<div class="comment-content" itemtype="http://schema.org/Comment" itemscope="itemscope" itemprop="comment">
					<div class="comment-inner">
					<div class="comment-meta">
						<span class="comment-author" itemprop="author" itemscope itemtype="http://schema.org/Person">
							<?php 
								// $comment_url = $comment->comment_author_url;
								$comment_author = '<span itemprop="name">'.get_comment_author().'</span>';
								echo $comment_author.kanews_user_subscribe_badge($comment->user_id).user_badge($comment->user_id);
								
							?>
						</span>
						<span class="comment-dot">•</span>
						<span class="comment-date"> 
							<a href="<?php echo htmlspecialchars( get_comment_link( $comment->comment_ID ) ); ?>">
								<?php echo get_comment_date('j F Y, H:i'); ?>
							</a>
							<meta itemprop="datePublished" content="<?php echo get_comment_date('c'); ?>">
						</span>
					</div>
					<div class="comment-text" itemprop="text">
						<?php if ('0' == $comment->comment_approved) : ?>
							<p class="comment-awaiting-moderation"><?php _e(
								'Yorumunuz editörümüz tarafından incelendikten sonra yayına alınacaktır.',
								'kanews'
							); ?></p>
						<?php endif; ?>
						<?php comment_text(); ?>
					</div>
					</div>
					<div class="comment-action">
						<?php comment_reply_link( array_merge($args, array(
							'reply_text' => __('Cevapla', 'kanews'),
							'respond_id' => 'respond',    
							'depth'      => $depth,
							'max_depth'  => $args['max_depth']
							)
						)); ?>
						<?php echo get_simple_likes_button( get_comment_ID(), 1 ); ?>
						<?php edit_comment_link(__('Düzenle', 'kanews'), '', '') ?>
					</div>

					<?php if(isset($args['has_children']) && $args['has_children'] == 1): ?>
						<div class="comment-show-more"><a href="javascript:void(0);" class="kanews-comment-show-more color-info"><i class="icon-caret icon-180deg"></i> <span><?php echo kanews_translate('show-text', esc_html__( 'Yanıtları Göster', 'kanews' )); ?></span></a></div>
					<?php endif; ?>
				</div>
		
		</div>
		</li>
	<?php 
}

function child_comment_counter($id){
	global $wpdb;
	$query = "SELECT COUNT(comment_post_id) AS count FROM `wp_comments` WHERE `comment_approved` = 1 AND `comment_parent` = ".$id;
	$children = $wpdb->get_row($query);
	return $children->count;
}

/*-----------------------------------------------------------------------------------*/
# Cookie Box
/*-----------------------------------------------------------------------------------*/
add_action('kanews_footer', 'kanews_cookie_box');
function kanews_cookie_box() { 
	if(!kanews_get_option('privacy-policy') || kanews_get_option('privacy-policy-page') == '' )
	return;
	?>
	<div id="kanews-cookie-box">
		<div class="kanews_cookie-box">
			<div class="kanews-cookie-box">
				<p><?php echo kanews_translate('privacy-policy-text', esc_html__( 'Bu web sitesinde en iyi deneyimi yaşamanızı sağlamak için çerezler kullanılmaktadır.', 'kanews' )); ?></p>
				
			</div>
			<div class="d-flex justify-content-between mt-1 align-items-center">
			<?php if(kanews_get_option('privacy-policy-page')): ?>
			<a href="<?php echo get_page_link(kanews_get_option('privacy-policy-page')); ?>"><?php esc_html_e( 'Gizlilik Politikası', 'kanews' ); ?></a>
			<?php endif; ?>
			<button onClick="purecookieDismiss();" role="button" class="kanews-btn"><?php esc_html_e( 'Kabul', 'kanews' ); ?></button>
			</div>
		</div>
	</div>
<?php }

/*-----------------------------------------------------------------------------------*/
# Page Header
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( 'kanews_page_header' ) ) {
	function kanews_page_header($pid, $title = '', $class = '', $desc = '', $bread = true) {
		if(get_post_meta($pid, 'page_header', true) == 'off') 
		return;
		?>
		<div class="kanews-page-header <?php echo $class; ?>">
			<div class="container">
				<div class="row">
					<?php if( $bread && kanews_get_option('breadcrumb') ) : ?>
					<div class="col-12 kanews-flat-breadcrumb">
            <?php kanews_breadcrumb(get_the_ID()); ?>
					</div>
					<?php endif; ?>
					<?php if($title == ''): ?>
						<div class="col"><h1 class="kanews-page-title"><?php the_title(); ?></h1><?php if($desc != ''): echo '<h2>'.$desc.'</h2>'; endif; ?></div>
					<?php else: ?>
						<div class="col"><h1 class="kanews-page-title"><?php echo $title; ?></h1><?php if($desc != ''): echo '<h2>'.$desc.'</h2>'; endif; ?></div>
					<?php endif; ?>
				</div>
			</div>
		</div>
	<?php }
}

/*-----------------------------------------------------------------------------------*/
# Page Header for Firma
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( 'kanews_page_header_cpt' ) ) {
	function kanews_page_header_cpt($title = '', $description = '', $cpt = '') {
		$page_title = !empty($title) ? $title : esc_html__('Firma Rehberi', 'kanews');
		$page_description = !empty($description) ? $description : esc_html__('Binlerce firmanın bilgilerine ulaşın, işletmenizi ücretsiz ekleyin.', 'kanews');
		
		// Pass variables to template
		set_query_var('page_title', $page_title);
		set_query_var('page_description', $page_description);
		
		get_template_part('template-parts/header/page-header', $cpt);
	}
}


/*-----------------------------------------------------------------------------------*/
# Entry Related Articles
/*-----------------------------------------------------------------------------------*/
function kanews_entry_related_articles(){
	$pid = get_the_ID();
	$style = kanews_get_option('related-posts2-style') ? kanews_get_option('related-posts2-style') : '1';
	$count = kanews_get_option('related-posts2-count') != '' ? kanews_get_option('related-posts2-count') : '4';
	$sortby = kanews_get_option('related-posts2-sortby') != '' ? kanews_get_option('related-posts2-sortby') : 'cat';

	if($style == 'disable' || !is_singular('post') || is_paged())
	return false;

	if( !empty(get_post_meta( $pid, 'kanews_bik_id', true)) )
	return;

	$tags = wp_get_post_terms( get_queried_object_id(), 'post_tag', ['fields' => 'ids'] );
  $categories = get_the_category($pid); if ($categories) {$category_ids = array(); foreach($categories as $individual_category) $category_ids[] = $individual_category->term_id;}

	$kanews_query = new WP_Query(
		array( 
			'tax_query' => [
				[
					'taxonomy' => 'post_tag',
					'terms'    => $tags
				]
			],
			'showposts' => $count,
			'orderby' => 'modified',
			'ignore_sticky_posts'=>1,
			'post__not_in' => array($pid),
		)
	);

	if($sortby == 'cat') {
		$kanews_query = new WP_Query(
      array( 
        'category__in' => $category_ids,
        'showposts'    => $count,
        'ignore_sticky_posts'=>1,
        'post__not_in' => array($pid),
      )
    );
	}

	switch($style) {
    case '1':
      $classes = 'kanews-post-grid-item';
      $col = 'col-6 col-md-4';
      $thumbnail = 'kanews-post-1';
    break;
    case '3':
      $classes = 'kanews-post-small-item';
      $col = 'col-12 col-md-6';
      $thumbnail = 'thumbnail';
    break;
    default:
      $classes = 'kanews-post-grid-item kanews-post-small-item';
      $col = 'col-12 col-md-6';
      $thumbnail = 'thumbnail';
    break;
  }

	$out = '';
	$tag = 'div';
	$default = kanews_get_option('default-thumbnail');
	$image_url = '';

	$GLOBALS['related_post_not_in'] = wp_list_pluck( $kanews_query->posts, 'ID' );
	$GLOBALS['related_post_not_in'][] = $pid;

	if ($kanews_query->have_posts()) {
    $out .= '<div id="related-articles" class="column_x_gutter">';
			$out .= kanews_widget_title(kanews_translate('related-posts2-title', esc_html__( 'Göz Atın', 'kanews' )), 'div', 'kanews-section-flat-heading');
			$out .='<div class="row equal-height">';
				while($kanews_query->have_posts()): $kanews_query->the_post(); global $post;
					$default = kanews_get_option('default-thumbnail') ? kanews_get_option('default-thumbnail') : '';
					if (has_post_thumbnail() ) {
						$image_id = get_post_thumbnail_id($post->ID);  
						$image_url = wp_get_attachment_image_src($image_id, $thumbnail);  
						$image_url = isset($image_url[0]) ? $image_url[0] : ''; 
					} elseif($default != '') {
						$image_url = wp_get_attachment_image_src($default['id'], $thumbnail);  
						$image_url = isset($image_url[0]) ? $image_url[0] : ''; 
					}
					$out .= '<div class="'.$col.'">';
						$out .= '<div class="kanews-post-item '.$classes.'">';
							$out .= '<a aria-label="'.esc_attr(get_the_title($post->ID)).'" href="' . esc_url(get_permalink($post->ID)) . '" class="kanews-post-href"></a>';
							if( $style != '3' && $image_url != '' ) {
								$out .= '<div class="kanews-post-thumb">';
									$out .= '<img alt="thumbnail" height="90" width="150" src="'.esc_url($image_url).'" />';
								$out .= '</div>';
							}
							$out .= '<div class="kanews-post-content">';
								$out .= '<'.$tag.' class="kanews-post-headline truncate truncate-3"><a href="' . esc_url(get_permalink($post->ID)) . '">' . esc_html(get_the_title($post->ID)) . '</a></'.$tag.'>';
							$out .= '</div>';
						$out .= '</div>';
					$out .= '</div>';
				endwhile; wp_reset_postdata();
			$out .= '</div>';
		$out .= '</div>';
	}

	return $out;

}

function kanews_entry_related_articles_insert( $insertion, $paragraph_id, $content ) {
	global $post;
	if(is_object($post) && get_post_meta( $post->ID, 'show_posts_related2', true ) == 'off')
	return $content;
	$closing_p = '</p>';
	$paragraphs = explode( $closing_p, $content );
	foreach ($paragraphs as $index => $paragraph) {
		if ( trim( $paragraph ) ) {
			$paragraphs[$index] .= $closing_p;
		}
		if ( $paragraph_id == $index + 1 ) {
			$paragraphs[$index] .= $insertion;
		}
	} 
	return implode( '', $paragraphs );
}

add_filter('the_content', 'kanews_entry_related_articles_out');
function kanews_entry_related_articles_out( $content ) {
	global $post;
	if(is_object($post) && get_post_meta( $post->ID, 'show_posts_related2', true ) == 'off')
	return $content;
	$position = kanews_get_option('related-posts2-plimit') ? kanews_get_option('related-posts2-plimit') : '5';
	$style = kanews_get_option('related-posts2-style') ? kanews_get_option('related-posts2-style') : '';
	$insert = kanews_entry_related_articles();

	if($style == 'disable')
	return $content;
  else
	return kanews_entry_related_articles_insert( $insert, $position, $content );
}



/*-----------------------------------------------------------------------------------*/
# Smart List #1
/*-----------------------------------------------------------------------------------*/
function kanews_smart_list_v1() {
	global $post;
	
	if(!$post)
	return;

	$gallery_content = explode("<!--nextpage-->",$post->post_content);
}

add_filter( 'post_gallery', 'kanews_post_gallery', 10, 2 );
function kanews_post_gallery( $output, $attr) {
    global $post, $wp_locale;

    static $instance = 0;
    $instance++;

    extract(shortcode_atts(array(
        'order'      => 'ASC',
        'orderby'    => 'menu_order ID',
        'id'         => $post->ID,
        'itemtag'    => 'dl',
        'icontag'    => 'dt',
        'captiontag' => 'dd',
        'columns'    => 3, // Changing the default thumbs per row
        'size'       => 'wpf-thumb', // Making the thumbnail size my custom one
        'include'    => '',
        'exclude'    => ''
    ), $attr));

    $id = intval($id);
    if ( 'RAND' == $order )
        $orderby = 'none';

    if ( !empty($include) ) {
        $include = preg_replace( '/[^0-9,]+/', '', $include );
        $_attachments = get_posts( array('include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );

        $attachments = array();
        foreach ( $_attachments as $key => $val ) {
            $attachments[$val->ID] = $_attachments[$key];
        }
    } elseif ( !empty($exclude) ) {
        $exclude = preg_replace( '/[^0-9,]+/', '', $exclude );
        $attachments = get_children( array('post_parent' => $id, 'exclude' => $exclude, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
    } else {
        $attachments = get_children( array('post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
    }

    if ( empty($attachments) )
        return '';

    if ( is_feed() ) {
        $output = "\n";
        foreach ( $attachments as $att_id => $attachment )
            $output .= wp_get_attachment_link($att_id, $size, true) . "\n";
        return $output;
    }

    $selector = "gallery-{$instance}";
		$count = sizeof( $attachments ) - 5;
		$hidden = '';

    $output = apply_filters('gallery_style', "<div id='$selector' class='kanews-gallery kanews-gallery-lightbox d-flex justify-content-between align-items-center kanews-galleryid-{$id}'><div class='kanews-gallery-thumbs'>");

    $i = 0;
    foreach ( $attachments as $id => $attachment ) { $i++;
			$attachment_link = wp_get_attachment_url($id, $size, false, false);
			$preview_link = isset($attr['link']) && 'file' == $attr['link'] ? wp_get_attachment_image($id, 'thumbnail', false, false) : wp_get_attachment_image($id, 'thumbnail', true, false);
			if($i > 5)
			$hidden = 'is-hidden';
			$output .= "<figure class='kanews-gallery-item {$hidden}' title='".esc_attr($attachment->post_excerpt)."' content='".esc_attr(wpautop( $attachment->post_content ))."' data-mfp-src='{$attachment_link}'>";
				if($i == 5)
				$output .= "<span class='kanews-gallery-count d-flex align-items-center justify-content-center'>+ {$count}</span>";
				$output .= $preview_link;
				if ( trim($attachment->post_excerpt && trim($attachment->post_content)) ) {
					$output .= "
					<figcaption class='kanews-gallery-caption d-none'>
					<h3>" . $attachment->post_excerpt . "</h3>
					" . wpautop($attachment->post_content) . "
					</figcaption>";
				}

			$output .= "</figure>";
    }

    $output .= "</div><div class='kanews-gallery-text'>".esc_html__( 'Galeriyi Görüntüle', 'kanews' )."</div></div>\n";

    return $output;
}

/*-----------------------------------------------------------------------------------*/
# Header Top Modules
/*-----------------------------------------------------------------------------------*/
function kanews_header_top_modules() {

	if(!kanews_get_option('header-top-modules', false))
	return;
	
	$slick_options = [
		'slidesToShow'  =>  6,
		'responsive' 			=> [
			[
				'breakpoint' 	 => 992,
				'settings'		 => [
					'slidesToShow' => 3
				]
			],
			[
				'breakpoint' 	 => 525,
				'settings'		 => [
					'slidesToShow' => 2
				]
			],
		]
	];
	$slick_json =  wp_json_encode( $slick_options );

	$page = kanews_get_option('header-top-module-page', '');
	$page_id = get_queried_object_id();
	$page_link = $page != '' ? get_page_link($page) : '#';

	if(!is_home() && $page_id == $page)
	return;

	switch(kanews_get_option('header-top-module', 'currencies')) {
		case 'currencies':
			$currencies = kanews_get_option('header-top-module-currencies') != '' ? kanews_get_option('header-top-module-currencies') : false;
			$data = Kanews\Currencies::update();

			if(!$currencies)
			return;
			
			echo "<div id='kanews-top' class='kanews-ticker-y ".(!kanews_get_option('header-top-modules-mobile', false) ? 'hidden-mobile' : '')." data-slick='$slick_json'>";
			echo '<div id="kanews-loader"><div class="kanews-loader-2 kanews-loader-sm">Loading...</div></div>';
			foreach($currencies as $currency){
				

				$icon = '<svg class="icon-trending" xmlns="http://www.w3.org/2000/svg" height="16" width="18" fill="currentColor"><path d="M3.062 15 2 13.938l5.854-5.855 3.167 3.167 4.417-4.396H13v-1.5h5v5h-1.5V7.917l-5.479 5.458-3.167-3.167Z"/></svg>';
				$index = 'try';
				if ($data->$currency->change_percent < 0)  {
					$class = 'border-danger color-danger';
					$icon = '<svg class="icon-trending icon-180deg" xmlns="http://www.w3.org/2000/svg" height="16" width="18" fill="currentColor"><path d="M3.062 15 2 13.938l5.854-5.855 3.167 3.167 4.417-4.396H13v-1.5h5v5h-1.5V7.917l-5.479 5.458-3.167-3.167Z"/></svg>';
				} else 
					$class = 'border-success color-success';
					if($currency == 'usd') {
						$img1 = kanews_get_local_image('https://s3-symbol-logo.tradingview.com/country/TR.svg', array('alt' => 'tr', 'width' => 18, 'height' => 18), '1e1');
						$img2 = kanews_get_local_image('https://s3-symbol-logo.tradingview.com/country/US.svg', array('alt' => $currency, 'width' => 18, 'height' => 18), '1e1');
					}elseif($currency == 'euro'){
						$img1 = kanews_get_local_image('https://s3-symbol-logo.tradingview.com/country/TR.svg', array('alt' => 'tr', 'width' => 18, 'height' => 18), '1e1');
						$img2 = kanews_get_local_image('https://s3-symbol-logo.tradingview.com/country/EU.svg', array('alt' => $currency, 'width' => 18, 'height' => 18), '1e1');
					}elseif($currency == 'gbp'){
						$img1 = kanews_get_local_image('https://s3-symbol-logo.tradingview.com/country/TR.svg', array('alt' => 'tr', 'width' => 18, 'height' => 18), '1e1');
						$img2 = kanews_get_local_image('https://s3-symbol-logo.tradingview.com/country/GB.svg', array('alt' => $currency, 'width' => 18, 'height' => 18), '1e1');
					}elseif($currency == 'chf'){
						$img1 = kanews_get_local_image('https://s3-symbol-logo.tradingview.com/country/TR.svg', array('alt' => 'tr', 'width' => 18, 'height' => 18), '1e1');
						$img2 = kanews_get_local_image('https://s3-symbol-logo.tradingview.com/country/CH.svg', array('alt' => $currency, 'width' => 18, 'height' => 18), '1e1');
					}elseif($currency == 'cny'){
						$img1 = kanews_get_local_image('https://s3-symbol-logo.tradingview.com/country/TR.svg', array('alt' => 'tr', 'width' => 18, 'height' => 18), '1e1');
						$img2 = kanews_get_local_image('https://s3-symbol-logo.tradingview.com/country/CN.svg', array('alt' => $currency, 'width' => 18, 'height' => 18), '1e1');
					}elseif($currency == 'jpy'){
						$img1 = kanews_get_local_image('https://s3-symbol-logo.tradingview.com/country/TR.svg', array('alt' => 'tr', 'width' => 18, 'height' => 18), '1e1');
						$img2 = kanews_get_local_image('https://s3-symbol-logo.tradingview.com/country/JP.svg', array('alt' => $currency, 'width' => 18, 'height' => 18), '1e1');
					}elseif($currency == 'rub'){
						$img1 = kanews_get_local_image('https://s3-symbol-logo.tradingview.com/country/TR.svg', array('alt' => 'tr', 'width' => 18, 'height' => 18), '1e1');
						$img2 = kanews_get_local_image('https://s3-symbol-logo.tradingview.com/country/RU.svg', array('alt' => $currency, 'width' => 18, 'height' => 18), '1e1');
					}elseif($currency == 'eur-usd'){
						$img1 = kanews_get_local_image('https://s3-symbol-logo.tradingview.com/country/TR.svg', array('alt' => 'tr', 'width' => 18, 'height' => 18), '1e1');
						$img2 = kanews_get_local_image('https://s3-symbol-logo.tradingview.com/country/EU.svg', array('alt' => $currency, 'width' => 18, 'height' => 18), '1e1');
					}elseif($currency == 'ise-100'){
						$img1 = kanews_get_local_image('https://s3-symbol-logo.tradingview.com/country/TR.svg', array('alt' => 'bist-100', 'width' => 18, 'height' => 18), '1e1');
						$img2 = '';
					}elseif($currency == 'gau'){
						$img1 = kanews_get_local_image('https://s3-symbol-logo.tradingview.com/metal/gold.svg', array('alt' => 'gau', 'width' => 18, 'height' => 18), '1e1');
						$img2 = '';
					}elseif($currency == 'ukoil'){
						$img2 = kanews_get_local_image('https://s3-symbol-logo.tradingview.com/crude-oil.svg', array('alt' => 'gau', 'width' => 18, 'height' => 18), '1e1');
						$img1 = kanews_get_local_image('https://s3-symbol-logo.tradingview.com/country/US.svg', array('alt' => 'usd', 'width' => 18, 'height' => 18), '1e1');
						$index = 'usd';
					}elseif($currency == 'btc'){
						$index = kanews_get_option('crypto-page-index', 'try');
						$img2 = kanews_get_local_image('https://s3-symbol-logo.tradingview.com/crypto/XTVCBTC.svg', array('alt' => $currency, 'width' => 18, 'height' => 18), '1e1');
						$img1 = kanews_get_local_image('https://s3-symbol-logo.tradingview.com/country/TR.svg', array('alt' => 'tr', 'width' => 18, 'height' => 18), '1e1');
					}elseif($currency == 'eth'){
						$index = kanews_get_option('crypto-page-index', 'try');
						$img2 = kanews_get_local_image('https://s3-symbol-logo.tradingview.com/crypto/XTVCETH.svg', array('alt' => $currency, 'width' => 18, 'height' => 18), '1e1');
						$img1 = kanews_get_local_image('https://s3-symbol-logo.tradingview.com/country/TR.svg', array('alt' => 'tr', 'width' => 18, 'height' => 18), '1e1');
					}elseif($currency == 'xrp'){
						$index = kanews_get_option('crypto-page-index', 'try');
						$img2 = kanews_get_local_image('https://s3-symbol-logo.tradingview.com/crypto/XTVCXRP.svg', array('alt' => $currency, 'width' => 18, 'height' => 18), '1e1');
						$img1 = kanews_get_local_image('https://s3-symbol-logo.tradingview.com/country/TR.svg', array('alt' => 'tr', 'width' => 18, 'height' => 18), '1e1');
					}elseif($currency == 'bch'){
						$index = kanews_get_option('crypto-page-index', 'try');
						$img2 = kanews_get_local_image('https://s3-symbol-logo.tradingview.com/crypto/XTVCBCH.svg', array('alt' => $currency, 'width' => 18, 'height' => 18), '1e1');
						$img1 = kanews_get_local_image('https://s3-symbol-logo.tradingview.com/country/TR.svg', array('alt' => 'tr', 'width' => 18, 'height' => 18), '1e1');
					}elseif($currency == 'ltc'){
						$index = kanews_get_option('crypto-page-index', 'try');
						$img2 = kanews_get_local_image('https://s3-symbol-logo.tradingview.com/crypto/XTVCLTC.svg', array('alt' => $currency, 'width' => 18, 'height' => 18), '1e1');
						$img1 = kanews_get_local_image('https://s3-symbol-logo.tradingview.com/country/TR.svg', array('alt' => 'tr', 'width' => 18, 'height' => 18), '1e1');
					}elseif($currency == 'bnb'){
						$index = kanews_get_option('crypto-page-index', 'try');
						$img2 = kanews_get_local_image('https://s3-symbol-logo.tradingview.com/crypto/XTVCBNB.svg', array('alt' => $currency, 'width' => 18, 'height' => 18), '1e1');
						$img1 = kanews_get_local_image('https://s3-symbol-logo.tradingview.com/country/TR.svg', array('alt' => 'tr', 'width' => 18, 'height' => 18), '1e1');
					}elseif($currency == 'sol'){
						$index = kanews_get_option('crypto-page-index', 'try');
						$img2 = kanews_get_local_image('https://s3-symbol-logo.tradingview.com/crypto/XTVCSOL.svg', array('alt' => $currency, 'width' => 18, 'height' => 18), '1e1');
						$img1 = kanews_get_local_image('https://s3-symbol-logo.tradingview.com/country/TR.svg', array('alt' => 'tr', 'width' => 18, 'height' => 18), '1e1');
					}elseif($currency == 'avax'){
						$img2 = kanews_get_local_image('https://s3-symbol-logo.tradingview.com/crypto/XTVCAVAX.svg', array('alt' => $currency, 'width' => 18, 'height' => 18), '1e1');
						$img1 = kanews_get_local_image('https://s3-symbol-logo.tradingview.com/country/TR.svg', array('alt' => 'tr', 'width' => 18, 'height' => 18), '1e1');
						$index = kanews_get_option('crypto-page-index', 'try');
					}elseif($currency == 'ada'){
						$img2 = kanews_get_local_image('https://s3-symbol-logo.tradingview.com/crypto/XTVCADA.svg', array('alt' => $currency, 'width' => 18, 'height' => 18), '1e1');
						$img1 = kanews_get_local_image('https://s3-symbol-logo.tradingview.com/country/TR.svg', array('alt' => 'tr', 'width' => 18, 'height' => 18), '1e1');
						$index = kanews_get_option('crypto-page-index', 'try');
					}elseif($currency == 'dot'){
						$img2 = kanews_get_local_image('https://s3-symbol-logo.tradingview.com/crypto/XTVCDOT.svg', array('alt' => $currency, 'width' => 18, 'height' => 18), '1e1');
						$img1 = kanews_get_local_image('https://s3-symbol-logo.tradingview.com/country/TR.svg', array('alt' => 'tr', 'width' => 18, 'height' => 18), '1e1');
						$index = kanews_get_option('crypto-page-index', 'try');
					}elseif($currency == 'doge'){
						$img2 = kanews_get_local_image('https://s3-symbol-logo.tradingview.com/crypto/XTVCDOGE.svg', array('alt' => $currency, 'width' => 18, 'height' => 18), '1e1');
						$img1 = kanews_get_local_image('https://s3-symbol-logo.tradingview.com/country/TR.svg', array('alt' => 'tr', 'width' => 18, 'height' => 18), '1e1');
						$index = kanews_get_option('crypto-page-index', 'try');
					}elseif($currency == 'shib'){
						$img2 = kanews_get_local_image('https://s3-symbol-logo.tradingview.com/crypto/XTVCSHIB.svg', array('alt' => $currency, 'width' => 18, 'height' => 18), '1e1');
						$img1 = kanews_get_local_image('https://s3-symbol-logo.tradingview.com/country/TR.svg', array('alt' => 'tr', 'width' => 18, 'height' => 18), '1e1');
						$index = kanews_get_option('crypto-page-index', 'try');
					}
					
					if($index!='try' & $currency != 'ukoil')
						$img1 = '';
				
				?>
				
				<a href="<?php echo $page_link; ?>" class="kanews-inline-card-item no-gutters">
					<div class="kanews-inline-card-icon col-auto">
						<span class="hbfdg12">
							<?php echo $img1; ?>
							<?php echo $img2; ?>
						</span>
					</div>
					<div class="kanews-inline-card-summary col">
						<div class="kanews-inline-card-title d-flex justify-content-between"><div><?php echo $data->$currency->name; ?></div><div><?php echo $data->$currency->change_percent.'%';  ?></div></div>
						<div class="kanews-inline-card-content">
							<div class="kanews-inline-card-content-item d-flex justify-content-between">
								<div><?php echo $data->$currency->full;?></div>
								<div class="<?php echo $class; ?>"><?php echo number_format((float)  $data->$currency->value, 2,",",".");?> <?php echo strtoupper($index); ?> <?php echo $icon; ?></div>
							</div>
						</div>
					</div>
				</a>
				<?php 
			}
			echo '</div>';
			
		break; case 'scores':
			$leagues = [
				'4c1nfi2j1m731hcay25fcgndq', // AV
				'482ofyysbdbeoxauk19yg7tdt', // TR
				'2o9svokc5s7diish3ycrzk7jm', // PTT
				'2nttcoriwf5co73vmz1vr8frm', // PTT 2
				'7af85xa75vozt2l4hzi6ryts7', // TR CUP
				'2kwbbcootiqqgmrzs6o5inle5', // Premier
				'7ntvbsyq31jnzoqoa8850b9b8', // Premier 2
				'4c1nfi2j1m731hcay25fcgndq', // UEFA
				'6by3h89i2eykc341oz7lv1ddd', // BUNDesliga
				'34pl8szyvrbwcmfkuocjm3r6t', // La Liga
				'1r097lpxe0xn03ihb7wi98kao', // Seria a
				'dm5ka0os1e3dxcp3vh05kmp33', // FR
				'akmkihra9ruad09ljapsm84b3', // HOL
				'8tddm56zbasf57jkkay4kbf11', // EURO
				'gfskxsdituog2kqp9yiu7bzi', // EURO EL
				'70excpe1synn9kadnbppahdn7', // DK
				'39q1hq42hxjfylxb7xpe9bvf9', // DK EL
				'595nsvo7ykvoe690b1e4u5n56', // Ulus
				'c7b8o53flg36wbuevfzy3lb10', // Konferans  
				'a0f4gtru0oyxmpvty4thc5qkc', // Süper Kupa  
				'4oogyu6o156iphvdvphwpck10', // ŞL  
				'cesdwwnxbc5fmajgroc0hqzy2', // Dünya Hazırlık  
			];


			$counter = 0;
			$lig = 'all';
			date_default_timezone_set('Europe/Istanbul');

			$date = date('Y-m-d');
			$outlist = '';
			

			$cons_matches = kanews_live_score_data($date, $leagues);
			$cons_matches = json_decode($cons_matches, true);


			foreach ($leagues as $key => $value) {
				if($cons_matches) {
					$matches = array_values(kanews_live_score_filter_by_league_name($cons_matches, $value));
					if(is_array($matches)  && !empty($matches)) {
						// print_r($matches);
						foreach ($matches as $match) {
							
							if($match['type'] == 1) {
								$counter++;
								$outlist .= '<a href="'.$page_link.'" class="kanews-inline-card-item no-gutters">
								<div class="kanews-inline-card-summary col">
									<div class="kanews-inline-card-title d-flex justify-content-between">';
									$outlist .= '<div>'.explode('-', $date)[0].'-'.explode('-', $date)[2].'</div>';
									if(isset($match['min']) && !empty($match['min'])) {
										if( $match['min'] == 'MS' )
										$outlist .= '<div class="kanews-gc-label color-success">'.$match['min'].' </div>';
									 else
									 	$outlist .= '<div class="kanews-gc-label color-danger">'.$match['min'].' </div>';
									} else {
										$outlist .= '<span class="kanews-gc-label color-dark">'.$match['start'].'</span>';
									}
			
									
									$outlist .= '</div>
									<div class="kanews-inline-card-content">
										<div class="kanews-inline-card-content-item d-flex justify-content-between">
											<div>'.kanews_get_local_image($match['home-logo'], $attr = array('width' => 18, 'height' => 18, 'alt' => 'logo'), '1e1').$match['home'].'</div>
											<div>'.( $match['home-score'] ? $match['home-score'] : '-' ).'</div>
										</div>
										<div class="kanews-inline-card-content-item d-flex justify-content-between">
											<div>'.kanews_get_local_image($match['away-logo'], $attr = array('width' => 18, 'height' => 18, 'alt' => 'logo'), '1e1').$match['away'].'</div>
											<div>'.( $match['away-score'] ? $match['away-score'] : '-' ) .'</div>
										</div>
									</div>
								</div></a>';
							}
						}
							
					}
				}
			}

			if($counter>0)
			echo "<div id='kanews-top' class='kanews-ticker-y hidden-mobile k23j-k-r14' data-slick='$slick_json'><div id='kanews-loader'><div class='kanews-loader-2 kanews-loader-sm'>Loading...</div></div>$outlist</div>";
		break;
	}


}


/*-----------------------------------------------------------------------------------*/
# Kategoriyi Tüm WpQuery Sorgularından Çıkart
/*-----------------------------------------------------------------------------------*/
add_action( 'pre_get_posts', 'kanews_query_exclude_category_posts' );
function kanews_query_exclude_category_posts( $query ) {
	if ( is_admin()
		|| is_category() 
		|| is_archive() 
		|| is_feed() 
		|| empty(kanews_get_option('excluded-categories', array()))
	) {
		return;
	}

	$query->set( 'category__not_in', kanews_get_option('excluded-categories', array()) );
}


// add_action('kanews_header_after', 'kanews_header_prayer_module');
function kanews_header_prayer_module() {

	$country = 'Turkey';
	$region = kanews_get_option('header-prayer-page-city', 'İstanbul');
	$city = kanews_get_option('header-prayer-page-city2', '') != '' ? kanews_get_option('header-prayer-page-city2', '') : $region; 
	$date = date('Y-m-d');
	
	
	if( $region == 'Kocaeli' && $region == $city )
	$city = 'İzmit';

	
	if( ! kanews_get_option('header-prayer', false) )
	return;

	$data = kanews_prayer_times_api( $country, $region, $city, $date, 30);
	$data['times'][$date] = [
		'00:00','00:00','00:00','00:00','00:00','00:00','00:00'
	];
	$data['place'] = [
		'city' => $city
	];
	
	$page_link = kanews_get_option('header-prayer-page') ? get_page_link(kanews_get_option('header-prayer-page')) : '#';


	?>
<div class="container mt-2">
  <div class="row">
    <div class="col-12">
			<div class="kanews-section kanews-section-flat" id="ramazan-prayer" data-ready="false" data-timezone-offset="180"
         data-country="Turkey"
         data-region="<?php echo esc_attr($region); ?>"
         data-city="<?php echo esc_attr( $city ); ?>"
         data-date="<?php echo esc_attr( $date ); ?>"
         data-days="30">

				<section class="prayer-times prayer-header">
					<ul class="d-flex">
						<li id="prayer-imsak" class="time hidden-mobile">
							<div class="progress"></div>
							<span class="prayer-name"><?php esc_html_e( 'İmsak', 'kanews' ); ?></span>
							<span class="prayer-time"><?php echo $data['times'][$date][0]; ?></span>
						</li>
						<li id="prayer-gunes" class="time hidden-mobile">
							<div class="progress"></div>
							<span class="prayer-name"><?php esc_html_e( 'Güneş', 'kanews' ); ?></span>
							<span class="prayer-time"><?php echo $data['times'][$date][1]; ?></span>
						</li>
						<li id="prayer-ogle" class="time hidden-mobile">
							<div class="progress"></div>
							<span class="prayer-name"><?php esc_html_e( 'Öğle', 'kanews' ); ?></span>
							<span class="prayer-time"><?php echo $data['times'][$date][2]; ?></span>
						</li>
						<li id="prayer-ikindi" class="time hidden-mobile">
							<div class="progress"></div>
							<span class="prayer-name"><?php esc_html_e( 'İkindi', 'kanews' ); ?></span>
							<span class="prayer-time"><?php echo $data['times'][$date][3]; ?></span>
						</li>
						<li id="prayer-aksam" class="time hidden-mobile">
							<div class="progress"></div>
							<span class="prayer-name"><?php esc_html_e( 'Akşam', 'kanews' ); ?></span>
							<span class="prayer-time"><?php echo $data['times'][$date][4]; ?></span>
						</li>
						<li id="prayer-yatsi" class="time hidden-mobile">
							<div class="progress"></div>
							<span class="prayer-name"><?php esc_html_e( 'Yatsı', 'kanews' ); ?></span>
							<span class="prayer-time"><?php echo $data['times'][$date][5]; ?></span>
						</li>
						<li class="remaining-time dev-ramazan">
							<div class="progress remaining-time-progress" style="width: 0%;"></div>
							<div class="time-wrap">
								<div class="timeago d-flex">
									<span class="prayer-name" id="prayerNameOld">İFTARA KALAN SÜRE</span>
									<span class="prayer-time" id="prayerTimeOld">00:00:00</span>
								</div>
							</div>
						</li>
					</ul>
					<a class="prayer-more" href="<?php echo esc_url($page_link); ?>" target="_blank">
						<span>İMSAKİYE 2025 - <?php echo $data['place']['city']; ?></span>
					</a>
				</section>
			</div>
		</div>
	</div>
</div>

<script type="text/javascript">
	document.addEventListener('DOMContentLoaded', function() {

// Verilerin çekileceği API URL'i
const apiUrl = '<?php echo get_template_directory_uri(); ?>/inc/api/prayer/api.php';

// HTML elementini seçme
const prayerTimesElement = document.querySelector('#ramazan-prayer');

// Verileri data attribute'lardan alıp objeye aktarma
const params = {
    timezoneOffset: parseInt(prayerTimesElement.getAttribute('data-timezone-offset')),
    country: prayerTimesElement.getAttribute('data-country'),
    region: prayerTimesElement.getAttribute('data-region'),
    city: prayerTimesElement.getAttribute('data-city'),
    date: prayerTimesElement.getAttribute('data-date'),
    days: parseInt(prayerTimesElement.getAttribute('data-days'))
};

// API'den veri çekme işlemi
fetch(apiUrl + '?' + new URLSearchParams(params))
    .then(response => response.json())
    .then(data => {
        // Verileri kullanarak HTML içeriğini güncelleme
        document.getElementById('prayer-imsak').querySelector('.prayer-time').textContent = data['times']['<?php echo $date; ?>'][0];
        document.getElementById('prayer-gunes').querySelector('.prayer-time').textContent = data['times']['<?php echo $date; ?>'][1];
        document.getElementById('prayer-ogle').querySelector('.prayer-time').textContent = data['times']['<?php echo $date; ?>'][2];
        document.getElementById('prayer-ikindi').querySelector('.prayer-time').textContent = data['times']['<?php echo $date; ?>'][3];
        document.getElementById('prayer-aksam').querySelector('.prayer-time').textContent = data['times']['<?php echo $date; ?>'][4];
        document.getElementById('prayer-yatsi').querySelector('.prayer-time').textContent = data['times']['<?php echo $date; ?>'][5];

				// var tis = '19:33:31';
		let launchTime2 = document.getElementById('prayer-aksam').querySelector('.prayer-time').innerHTML;

if (document.querySelector('#prayer-aksam .prayer-time').textContent.trim().length > 0) {


let launchTime = new Date();

const [launchHour, launchMinute] = launchTime2.split(":");
launchTime.setHours(launchHour);
launchTime.setMinutes(launchMinute);
launchTime.setSeconds(0);

let launchTimex = document.querySelector('#prayer-imsak .prayer-time').innerHTML;

const [launchHourx, launchMinutex] = launchTimex.split(":");


const interval = setInterval(() => {
		const now = new Date();
		let distance = launchTime - now;

		// zaman farkını hesaplama
		if ( ( distance < 0 || (now.getHours() < launchHourx ) && now.getHours() != launchHour) ) {
			
			let launchTime = new Date();
			if( now.getHours() > launchHourx )
			launchTime.setDate(launchTime.getDate() + 1);

			launchTime.setHours(launchHourx);
			launchTime.setMinutes(launchMinutex);
			launchTime.setSeconds(0);
	
			distance = launchTime - now;
			document.getElementById('prayerNameOld').innerHTML = 'SAHURA KALAN SÜRE';
		}

		// saat, dakika ve saniye hesaplama
		let hours = Math.floor(distance / (1000 * 60 * 60));
		let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
		let seconds = Math.floor((distance % (1000 * 60)) / 1000);

		if (hours < 10) {
				hours = "0" + hours;
		}

		if (minutes < 10) {
				minutes = "0" + minutes;
		}

		if (seconds < 10) {
				seconds = "0" + seconds;
		}

		// sonucu HTML'de gösterme
		document.getElementById('prayerTimeOld').innerHTML = `${hours}:${minutes}:${seconds}`;


		// const totalDistance = launchTime - new Date(); // Hedef zaman ve şu anki zaman arasındaki fark
		// const progressPercentage = (totalDistance - distance) / totalDistance * 100; // İlerleme yüzdesi

		// $('.remaining-time-progress').css('width', progressPercentage + '%');

		// zamanlayıcıyı durdurma
		if (distance < 0) {
				clearInterval(interval);
				document.getElementById('prayerTimeOld').innerHTML = '00:00:00';
		}
}, 1000);
}

    })
    .catch(error => console.error('Veri çekme hatası:', error));
	});
		</script>
	<?php 
}

add_action('kanews_header_after', 'kanews_header_prayer_module2');
function kanews_header_prayer_module2() {

	$country = 'Turkey';
	$region = kanews_get_option('header-prayer-page-city', 'İstanbul');
	$city = kanews_get_option('header-prayer-page-city2', '') != '' ? kanews_get_option('header-prayer-page-city2', '') : $region; 
	$date = date('Y-m-d');
	
	
	if( $region == 'Kocaeli' && $region == $city )
	$city = 'İzmit';

	
	if( ! kanews_get_option('header-prayer', false) )
	return;

	$data = kanews_prayer_times_api( $country, $region, $city, $date, 30);

	
	$page_link = kanews_get_option('header-prayer-page') ? get_page_link(kanews_get_option('header-prayer-page')) : '#';


	?>
<div class="container mt-2">
  <div class="row">
    <div class="col-12">
			<div class="kanews-section kanews-section-flat" id="prayer-countdown" data-ready="false" data-timezone-offset="180"
         data-country="Turkey"
         data-region="<?php echo esc_attr($region); ?>"
         data-city="<?php echo esc_attr( $city ); ?>"
         data-date="<?php echo esc_attr( $date ); ?>"
         data-days="30">

				<section class="prayer-times prayer-header">
					<ul class="d-flex">
						<li id="prayer-imsak" class="time hidden-mobile">
							<div class="progress"></div>
							<span class="prayer-name"><?php esc_html_e( 'İmsak', 'kanews' ); ?></span>
							<span class="prayer-time"><?php echo $data['times'][$date][0]; ?></span>
						</li>
						<li id="prayer-gunes" class="time hidden-mobile">
							<div class="progress"></div>
							<span class="prayer-name"><?php esc_html_e( 'Güneş', 'kanews' ); ?></span>
							<span class="prayer-time"><?php echo $data['times'][$date][1]; ?></span>
						</li>
						<li id="prayer-ogle" class="time hidden-mobile">
							<div class="progress"></div>
							<span class="prayer-name"><?php esc_html_e( 'Öğle', 'kanews' ); ?></span>
							<span class="prayer-time"><?php echo $data['times'][$date][2]; ?></span>
						</li>
						<li id="prayer-ikindi" class="time hidden-mobile">
							<div class="progress"></div>
							<span class="prayer-name"><?php esc_html_e( 'İkindi', 'kanews' ); ?></span>
							<span class="prayer-time"><?php echo $data['times'][$date][3]; ?></span>
						</li>
						<li id="prayer-aksam" class="time hidden-mobile">
							<div class="progress"></div>
							<span class="prayer-name"><?php esc_html_e( 'Akşam', 'kanews' ); ?></span>
							<span class="prayer-time"><?php echo $data['times'][$date][4]; ?></span>
						</li>
						<li id="prayer-yatsi" class="time hidden-mobile">
							<div class="progress"></div>
							<span class="prayer-name"><?php esc_html_e( 'Yatsı', 'kanews' ); ?></span>
							<span class="prayer-time"><?php echo $data['times'][$date][5]; ?></span>
						</li>
						<li class="remaining-time dev-prayer">
							<div class="progress remaining-time-progress" style="width: 0%;"></div>
							<div class="time-wrap">
								<div class="timeago d-flex">
									<span class="prayer-name" id="nextPrayerName">SONRAKİ NAMAZA KALAN SÜRE</span>
									<span class="prayer-time" id="nextPrayerTime">00:00:00</span>
								</div>
							</div>
						</li>
					</ul>
					<a class="prayer-more" href="<?php echo esc_url($page_link); ?>" target="_blank">
						<span>İMSAKİYE 2025 - <?php echo isset($data['place']['city']) ? $data['place']['city'] : ''; ?></span>
					</a>
				</section>
			</div>
		</div>
	</div>
</div>

<script type="text/javascript">
	document.addEventListener('DOMContentLoaded', function() {

// Verilerin çekileceği API URL'i
const apiUrl = '<?php echo get_template_directory_uri(); ?>/inc/api/prayer/api.php';

// HTML elementini seçme
const prayerTimesElement = document.querySelector('#prayer-countdown');

// Verileri data attribute'lardan alıp objeye aktarma
const params = {
    timezoneOffset: parseInt(prayerTimesElement.getAttribute('data-timezone-offset')),
    country: prayerTimesElement.getAttribute('data-country'),
    region: prayerTimesElement.getAttribute('data-region'),
    city: prayerTimesElement.getAttribute('data-city'),
    date: prayerTimesElement.getAttribute('data-date'),
    days: parseInt(prayerTimesElement.getAttribute('data-days'))
};

// API'den veri çekme işlemi
fetch(apiUrl + '?' + new URLSearchParams(params))
    .then(response => response.json())
    .then(data => {
        // Verileri kullanarak HTML içeriğini güncelleme
        document.getElementById('prayer-imsak').querySelector('.prayer-time').textContent = data['times']['<?php echo $date; ?>'][0];
        document.getElementById('prayer-gunes').querySelector('.prayer-time').textContent = data['times']['<?php echo $date; ?>'][1];
        document.getElementById('prayer-ogle').querySelector('.prayer-time').textContent = data['times']['<?php echo $date; ?>'][2];
        document.getElementById('prayer-ikindi').querySelector('.prayer-time').textContent = data['times']['<?php echo $date; ?>'][3];
        document.getElementById('prayer-aksam').querySelector('.prayer-time').textContent = data['times']['<?php echo $date; ?>'][4];
        document.getElementById('prayer-yatsi').querySelector('.prayer-time').textContent = data['times']['<?php echo $date; ?>'][5];

        // Namaz vakitlerini diziye ekleme
        const prayerTimes = [
            { name: 'İmsak', time: data['times']['<?php echo $date; ?>'][0] },
            { name: 'Güneş', time: data['times']['<?php echo $date; ?>'][1] },
            { name: 'Öğle', time: data['times']['<?php echo $date; ?>'][2] },
            { name: 'İkindi', time: data['times']['<?php echo $date; ?>'][3] },
            { name: 'Akşam', time: data['times']['<?php echo $date; ?>'][4] },
            { name: 'Yatsı', time: data['times']['<?php echo $date; ?>'][5] }
        ];

        // Şu anki zamanı alma
        const now = new Date();
        const currentHour = now.getHours();
        const currentMinute = now.getMinutes();
        const currentTime = currentHour * 60 + currentMinute;

        // Sonraki namaz vaktini bulma
        let nextPrayer = null;
        let nextPrayerTime = null;
        let previousPrayer = null;
        let previousPrayerTime = null;

        for (let i = 0; i < prayerTimes.length; i++) {
            const [prayerHour, prayerMinute] = prayerTimes[i].time.split(':').map(Number);
            const prayerTimeInMinutes = prayerHour * 60 + prayerMinute;

            if (prayerTimeInMinutes > currentTime) {
                nextPrayer = prayerTimes[i];
                nextPrayerTime = prayerTimeInMinutes;
                
                // Önceki namazı bul
                if (i > 0) {
                    previousPrayer = prayerTimes[i-1];
                    const [prevHour, prevMinute] = previousPrayer.time.split(':').map(Number);
                    previousPrayerTime = prevHour * 60 + prevMinute;
                } else {
                    // Eğer ilk namaz ise, önceki namaz son namazdır
                    previousPrayer = prayerTimes[prayerTimes.length - 1];
                    const [prevHour, prevMinute] = previousPrayer.time.split(':').map(Number);
                    previousPrayerTime = prevHour * 60 + prevMinute;
                }
                
                break;
            }
        }

        // Eğer sonraki namaz bulunamazsa (yani tüm namazlar geçmişse), ertesi günün ilk namazına kadar sayım yap
        if (!nextPrayer) {
            nextPrayer = prayerTimes[0];
            const [prayerHour, prayerMinute] = nextPrayer.time.split(':').map(Number);
            nextPrayerTime = prayerHour * 60 + prayerMinute;
            
            // Önceki namaz son namazdır
            previousPrayer = prayerTimes[prayerTimes.length - 1];
            const [prevHour, prevMinute] = previousPrayer.time.split(':').map(Number);
            previousPrayerTime = prevHour * 60 + prevMinute;
            
            // Ertesi gün için zaman ayarlama
            const tomorrow = new Date();
            tomorrow.setDate(tomorrow.getDate() + 1);
            tomorrow.setHours(prayerHour, prayerMinute, 0);
            
            // Geri sayım fonksiyonu
            const countdown = () => {
                const now = new Date();
                const distance = tomorrow - now;
                
                // Saat, dakika ve saniye hesaplama
                let hours = Math.floor(distance / (1000 * 60 * 60));
                let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
                let seconds = Math.floor((distance % (1000 * 60)) / 1000);
                
                // Sıfır ekleme
                if (hours < 10) hours = "0" + hours;
                if (minutes < 10) minutes = "0" + minutes;
                if (seconds < 10) seconds = "0" + seconds;
                
                // Sonucu HTML'de gösterme
                document.getElementById('nextPrayerName').innerHTML = nextPrayer.name + ' NAMAZINA KALAN SÜRE';
                document.getElementById('nextPrayerTime').innerHTML = `${hours}:${minutes}:${seconds}`;
                
                // İlerleme çubuğu hesaplama
                const totalTimeBetweenPrayers = 24 * 60 - previousPrayerTime + nextPrayerTime;
                const elapsedTimeSincePreviousPrayer = (now.getHours() * 60 + now.getMinutes()) - previousPrayerTime;
                const progressPercentage = (elapsedTimeSincePreviousPrayer / totalTimeBetweenPrayers) * 100;
                
                // İlerleme çubuğunu güncelleme
                document.querySelector('.remaining-time-progress').style.width = Math.min(100, Math.max(0, progressPercentage)) + '%';
                
                // Zamanlayıcıyı durdurma
                if (distance < 0) {
                    clearInterval(interval);
                    document.getElementById('nextPrayerTime').innerHTML = '00:00:00';
                }
            };
            
            // İlk çalıştırma
            countdown();
            
            // Her saniye güncelleme
            const interval = setInterval(countdown, 1000);
        } else {
            // Sonraki namaz için geri sayım
            const countdown = () => {
                const now = new Date();
                const [prayerHour, prayerMinute] = nextPrayer.time.split(':').map(Number);
                
                const prayerDate = new Date();
                prayerDate.setHours(prayerHour, prayerMinute, 0);
                
                const distance = prayerDate - now;
                
                // Saat, dakika ve saniye hesaplama
                let hours = Math.floor(distance / (1000 * 60 * 60));
                let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
                let seconds = Math.floor((distance % (1000 * 60)) / 1000);
                
                // Sıfır ekleme
                if (hours < 10) hours = "0" + hours;
                if (minutes < 10) minutes = "0" + minutes;
                if (seconds < 10) seconds = "0" + seconds;
                
                // Sonucu HTML'de gösterme
                document.getElementById('nextPrayerName').innerHTML = nextPrayer.name + ' İÇİN KALAN SÜRE';
                document.getElementById('nextPrayerTime').innerHTML = `${hours}:${minutes}:${seconds}`;
                
                // İlerleme çubuğu hesaplama
                const totalTimeBetweenPrayers = nextPrayerTime - previousPrayerTime;
                const elapsedTimeSincePreviousPrayer = (now.getHours() * 60 + now.getMinutes()) - previousPrayerTime;
                const progressPercentage = (elapsedTimeSincePreviousPrayer / totalTimeBetweenPrayers) * 100;
                
                // İlerleme çubuğunu güncelleme
                document.querySelector('.remaining-time-progress').style.width = Math.min(100, Math.max(0, progressPercentage)) + '%';
                
                // Zamanlayıcıyı durdurma
                if (distance < 0) {
                    clearInterval(interval);
                    document.getElementById('nextPrayerTime').innerHTML = '00:00:00';
                    
                    // Sayfayı yenileme
                    setTimeout(() => {
                        location.reload();
                    }, 1000);
                }
            };
            
            // İlk çalıştırma
            countdown();
            
            // Her saniye güncelleme
            const interval = setInterval(countdown, 1000);
        }
    })
    .catch(error => console.error('Veri çekme hatası:', error));
	});
		</script>
	<?php 
}

function secim_2024_geri_sayim( $return = true, $id = 'secim2024' ) {

	ob_start();

	$tarih = 'Mar 31, 2024 09:00:00';
	$current_time = strtotime("now");

	if ($current_time > strtotime("Mar 14, 2024 23:00:00")) {
			$tarih = 'Mar 31, 2024 23:00:00';
	}

	?>
	<div id="<?php echo $id; ?>" class="secim2024"></div>
	<script>
		
		// Set the date we're counting down to
		var countDownDate = new Date("<?php echo $tarih; ?>").getTime();

		// Update the count down every 1 second
		var x = setInterval(function () {

				// Get today's date and time
				var now = new Date().getTime();

				// Find the distance between now and the count down date
				var distance = countDownDate - now;

				// Time calculations for days, hours, minutes and seconds
				var days = Math.floor(distance / (1000 * 60 * 60 * 24));
				var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
				var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
				var seconds = Math.floor((distance % (1000 * 60)) / 1000);

				// Display the result in the element with id="demo"
				document.getElementById("<?php echo $id; ?>").innerHTML = "<div class='fajmk3'>Seçime Son</div><div><span>"+days + "</span> gün</div><div><span>" + hours + "</span> saat</div><div><span>" +
						minutes + "</span> dakika</div><div><span>" + seconds + "</span> saniye</div>";
				document.getElementById("<?php echo $id; ?>").style.opacity = "1";

				// If the count down is finished, write some text
				if (distance < 0) {
						clearInterval(x);
						document.getElementById("<?php echo $id; ?>").innerHTML = "EXPIRED";
				}
		}, 1000);
		
</script>
	<?php 
	if( $return )
	return ob_get_clean();
	else 
	echo ob_get_clean();
}

add_action( 'widgets_init', 'kanews_mega_menu_widget' );
add_filter( 'walker_nav_menu_start_el', 'kanews_mega_menu_walker_nav_menu_start_el', 10, 4 );
add_filter( 'nav_menu_submenu_css_class', 'kanews_mega_menu_nav_menu_submenu_css_class', 10, 3);

function kanews_mega_menu_nav_menu_submenu_css_class( $classes, $args, $depth) {
	$a = array();
	foreach($classes as $class) {
		$a[] = 'kanews-mega-menu-'.$class;
	}
	return $classes;
}

function kanews_mega_menu_widget() {
	$locations = get_nav_menu_locations();
	foreach ($locations as $key => $location) {
		$menu = get_term( $location , 'nav_menu' );

		if ( $menu && ! is_wp_error($menu) && $items = wp_get_nav_menu_items( $menu->name ) ) {
			foreach ( $items as $item ) {
				if ( in_array( 'kanews-mega-menu', $item->classes ) ) {
					register_sidebar( array(
						'id'   => 'kanews-mega-menu-widget-area-' . $item->ID,
						'name' => $item->title . ' - Mega Menu',
						'description' => '',
						'class' => '',
						'before_widget' => '<div class="widget %2$s">',
						'after_widget' => "</div>\n",
						'before_title' => '<h4 class="widgettitle">',
						'after_title' => "</h4>\n",
					) );
				}
			}
		}
	}
}

function kanews_mega_menu_walker_nav_menu_start_el($item_output, $item, $depth, $args ) {
	if ( in_array( 'kanews-mega-menu', $item->classes ) ) {
		ob_start();
		if ( is_active_sidebar( 'kanews-mega-menu-widget-area-' . $item->ID ) ) {
			echo '<div class="kanews-mega-menu-block">';
			dynamic_sidebar( 'kanews-mega-menu-widget-area-' . $item->ID );
			echo '</div>';
		}
		$html = ob_get_contents();
		ob_end_clean();
		$item_output = $item_output.$html;
	}

	return $item_output;
}


// Son gönderi yayınlanma tarihini yazar meta alanına kaydet
function update_author_last_post_date( $post_id, $post, $update ) {
	// Sadece 'post' ve 'columist' türleri için çalışsın
	if ( ! in_array( $post->post_type, array( 'post', 'columist' ) ) ) {
			return;
	}
	
	// Yalnızca yazı yayınlandığında çalışsın
	if ( $post->post_status !== 'publish' ) {
		return;
	}


	$author_id = $post->post_author;

	update_user_meta( $author_id, 'last_post_date', $post->post_date );
	update_user_meta( $author_id, 'last_post_id', $post_id );

}
add_action( 'wp_insert_post', 'update_author_last_post_date', 10, 3 );




$theme_widgets = array(
	'imagebox',
	'firma',
	'ilan',
	'secim2023',
	'services',
	'survey',
	'term-images'
);

if( ! empty( $theme_widgets ) && is_array( $theme_widgets ) ){
	foreach ( $theme_widgets as $widget ){
		locate_template( "framework/widgets/$widget.php", true, true );
	}
}