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

/*-----------------------------------------------------------------------------------*/
# Turkey Cities
/*-----------------------------------------------------------------------------------*/
function kanews_get_turkey_cities($id, $custom = '') {
	$out = '';
	$custom = $custom ? 'kf241fv' : '';
	$out .= '<div id="'.$id.'" class="kanews-waether-cities kanews-scroll '.$custom.'">';
	$out .= '<input placeholder="'.esc_html__( 'Şehir ara', 'kanews' ).'" id="kanews-weather-search" />';
  $out .= '<div class="kanews-weather-city" data-city="İstanbul">İstanbul</div><div class="kanews-weather-city" data-city="Ankara">Ankara</div><div class="kanews-weather-city" data-city="İzmir">İzmir</div><div class="kanews-weather-city" data-city="Adana">Adana</div><div class="kanews-weather-city" data-city="Adıyaman">Adıyaman</div><div class="kanews-weather-city" data-city="Afyonkarahisar">Afyonkarahisar</div><div class="kanews-weather-city" data-city="Ağrı">Ağrı</div><div class="kanews-weather-city" data-city="Aksaray">Aksaray</div><div class="kanews-weather-city" data-city="Amasya">Amasya</div><div class="kanews-weather-city" data-city="Antalya">Antalya</div><div class="kanews-weather-city" data-city="Ardahan">Ardahan</div><div class="kanews-weather-city" data-city="Artvin">Artvin</div><div class="kanews-weather-city" data-city="Aydın">Aydın</div><div class="kanews-weather-city" data-city="Balıkesir">Balıkesir</div><div class="kanews-weather-city" data-city="Bartın">Bartın</div><div class="kanews-weather-city" data-city="Batman">Batman</div><div class="kanews-weather-city" data-city="Bayburt">Bayburt</div><div class="kanews-weather-city" data-city="Bilecik">Bilecik</div><div class="kanews-weather-city" data-city="Bingöl">Bingöl</div><div class="kanews-weather-city" data-city="Bitlis">Bitlis</div><div class="kanews-weather-city" data-city="Bolu">Bolu</div><div class="kanews-weather-city" data-city="Burdur">Burdur</div><div class="kanews-weather-city" data-city="Bursa">Bursa</div><div class="kanews-weather-city" data-city="Çanakkale">Çanakkale</div><div class="kanews-weather-city" data-city="Çankırı">Çankırı</div><div class="kanews-weather-city" data-city="Çorum">Çorum</div><div class="kanews-weather-city" data-city="Denizli">Denizli</div><div class="kanews-weather-city" data-city="Diyarbakır">Diyarbakır</div><div class="kanews-weather-city" data-city="Düzce">Düzce</div><div class="kanews-weather-city" data-city="Edirne">Edirne</div><div class="kanews-weather-city" data-city="Elazığ">Elazığ</div><div class="kanews-weather-city" data-city="Erzincan">Erzincan</div><div class="kanews-weather-city" data-city="Erzurum">Erzurum</div><div class="kanews-weather-city" data-city="Eskişehir">Eskişehir</div><div class="kanews-weather-city" data-city="Gaziantep">Gaziantep</div><div class="kanews-weather-city" data-city="Giresun">Giresun</div><div class="kanews-weather-city" data-city="Gümüşhane">Gümüşhane</div><div class="kanews-weather-city" data-city="Hakkâri">Hakkâri</div><div class="kanews-weather-city" data-city="Hatay">Hatay</div><div class="kanews-weather-city" data-city="Iğdır">Iğdır</div><div class="kanews-weather-city" data-city="Isparta">Isparta</div><div class="kanews-weather-city" data-city="Kahramanmaraş">Kahramanmaraş</div><div class="kanews-weather-city" data-city="Karabük">Karabük</div><div class="kanews-weather-city" data-city="Karaman">Karaman</div><div class="kanews-weather-city" data-city="Kars">Kars</div><div class="kanews-weather-city" data-city="Kastamonu">Kastamonu</div><div class="kanews-weather-city" data-city="Kayseri">Kayseri</div><div class="kanews-weather-city" data-city="Kırıkkale">Kırıkkale</div><div class="kanews-weather-city" data-city="Kırklareli">Kırklareli</div><div class="kanews-weather-city" data-city="Kırşehir">Kırşehir</div><div class="kanews-weather-city" data-city="Kilis">Kilis</div><div class="kanews-weather-city" data-city="Kocaeli">Kocaeli</div><div class="kanews-weather-city" data-city="Konya">Konya</div><div class="kanews-weather-city" data-city="Kütahya">Kütahya</div><div class="kanews-weather-city" data-city="Malatya">Malatya</div><div class="kanews-weather-city" data-city="Manisa">Manisa</div><div class="kanews-weather-city" data-city="Mardin">Mardin</div><div class="kanews-weather-city" data-city="Mersin">Mersin</div><div class="kanews-weather-city" data-city="Muğla">Muğla</div><div class="kanews-weather-city" data-city="Muş">Muş</div><div class="kanews-weather-city" data-city="Nevşehir">Nevşehir</div><div class="kanews-weather-city" data-city="Niğde">Niğde</div><div class="kanews-weather-city" data-city="Ordu">Ordu</div><div class="kanews-weather-city" data-city="Osmaniye">Osmaniye</div><div class="kanews-weather-city" data-city="Rize">Rize</div><div class="kanews-weather-city" data-city="Sakarya">Sakarya</div><div class="kanews-weather-city" data-city="Samsun">Samsun</div><div class="kanews-weather-city" data-city="Siirt">Siirt</div><div class="kanews-weather-city" data-city="Sinop">Sinop</div><div class="kanews-weather-city" data-city="Sivas">Sivas</div><div class="kanews-weather-city" data-city="Şırnak">Şırnak</div><div class="kanews-weather-city" data-city="Tekirdağ">Tekirdağ</div><div class="kanews-weather-city" data-city="Tokat">Tokat</div><div class="kanews-weather-city" data-city="Trabzon">Trabzon</div><div class="kanews-weather-city" data-city="Tunceli">Tunceli</div><div class="kanews-weather-city" data-city="Şanlıurfa">Şanlıurfa</div><div class="kanews-weather-city" data-city="Uşak">Uşak</div><div class="kanews-weather-city" data-city="Van">Van</div><div class="kanews-weather-city" data-city="Yalova">Yalova</div><div class="kanews-weather-city" data-city="Yozgat">Yozgat</div><div class="kanews-weather-city" data-city="Zonguldak">Zonguldak</div>';
  $out .= '</div>';
  return $out;
}
function kanews_get_turkey_cities2($return = 'value', $city = '') {
	$sehirler = array(
		'325361' =>'Adana',
		'325329' =>'Adıyaman',
		'325302' =>'Afyonkarahisar',
		'325163' =>'Ağrı',
		'752014' =>'Amasya',
		'323786' =>'Ankara',
		'323776' =>'Antalya',
		'751816' =>'Artvin',
		'322819' =>'Aydın',
		'322164' =>'Balıkesir',
		'750598' =>'Bilecik',
		'321079' =>'Bingöl',
		'321022' =>'Bitlis',
		'745175' =>'Bolu',
		'320390' =>'Burdur',
		'750268' =>'Bursa',
		'749778' =>'Çanakkale',
		'749747' =>'Çankırı',
		'748877' =>'Çorum',
		'317109' =>'Denizli',
		'316540' =>'Diyarbakır',
		'747712' =>'Edirne',
		'315807' =>'Elazığ',
		'315372' =>'Erzincan',
		'315368' =>'Erzurum',
		'315201' =>'Eskişehir',
		'314829' =>'Gaziantep',
		'746878' =>'Giresun',
		'746423' =>'Gümüşhane',
		'312888' =>'Hakkari',
		'312394' =>'Hatay',
		'311071' =>'Isparta',
		'304531' =>'Mersin',
		'745042' =>'İstanbul',
		'311044' =>'İzmir',
		'743942' =>'Kars',
		'743881' =>'Kastamonu',
		'308464' =>'Kayseri',
		'743165' =>'Kırklareli',
		'307513' =>'Kırşehir',
		'742865' =>'Kocaeli',
		'306569' =>'Konya',
		'305267' =>'Kütahya',
		'304919' =>'Malatya',
		'304825' =>'Manisa',
		'310858' =>'Kahramanmaraş',
		'304794' =>'Mardin',
		'304183' =>'Muğla',
		'304041' =>'Muş',
		'303830' =>'Nevşehir',
		'303826' =>'Niğde',
		'741099' =>'Ordu',
		'740483' =>'Rize',
		'740352' =>'Sakarya',
		'740264' =>'Samsun',
		'300821' =>'Siirt',
		'739598' =>'Sinop',
		'300619' =>'Sivas',
		'738926' =>'Tekirdağ',
		'738742' =>'Tokat',
		'738647' =>'Trabzon',
		'298845' =>'Tunceli',
		'298332' =>'Şanlıurfa',
		'298298' =>'Uşak',
		'298113' =>'Van',
		'296560' =>'Yozgat',
		'737022' =>'Zonguldak',
		'443185' =>'Aksaray',
		'862471' =>'Bayburt',
		'309527' =>'Karaman',
		'443188' =>'Kırıkkale',
		'443186' =>'Batman',
		'443189' =>'Şırnak',
		'862467' =>'Bartın',
		'751952' =>'Ardahan',
		'443184' =>'Iğdır',
		'862469' =>'Yalova',
		'862468' =>'Karabük',
		'443213' =>'Kilis',
		'443183' =>'Osmaniye',
		'865521' =>'Düzce',
		'146268' =>'Lefkoşa',
		'146617' =>'Gazimağusa',
		'146412' =>'Girne',
		'146286' =>'Güzelyurt',
		'146027' =>'İskele',
		'786714' =>'Pristina',
	);
	$sehirler = apply_filters( 'kanews/weather_page_cities', $sehirler );

	if($return == 'value')
  return $sehirler;
	else
	return isset($sehirler[$city]) ? $sehirler[$city] : false;
}

add_filter('kanews/weather_page_cities', 'kanews_filter_cities', 10, 2);
function kanews_filter_cities($sehirler) {

	if (kanews_get_option('weather-cities2', 'turkey') == 'turkey' )
	return $sehirler;

	$cities = array(
		"524901" => "Moscow",
		"745042" => "İstanbul",
		"1796236" => "Shanghai",
		"6455259" => "Paris",
		"1816670" => "Beijing",
		"5128638" => "New York",
		"292223" => "Dubai",
		"2643743" => "London",
		"6167865" => "Toronto",
		"1735161" => "Kuala Lumpur",
		"2988507" => "Paris",
		"1850147" => "Tokyo",
		"1261481" => "Delhi",
		"1853909" => "Tokyo",
		"1819729" => "Hong Kong",
		"3448439" => "São Paulo",
		"1835848" => "Seoul",
		"1701668" => "Manila",
		"3451190" => "Rio de Janeiro",
		"1792947" => "Guangzhou",
		"2643123" => "Edinburgh",
		"3530597" => "Mexico City",
		"2950159" => "Berlin",
		"2673730" => "Stockholm",
		"2759794" => "Amsterdam",
		"6542283" => "Madrid",
		"1609350" => "Bangkok",
		"3169070" => "Rome",
		"2643741" => "Manchester",
		"5128581" => "New York",
		"1861060" => "Osaka",
		"1261481" => "New Delhi",
		"184745" => "Nairobi",
		"3441575" => "Buenos Aires",
		"160196" => "Abidjan",
		"524901" => "Moscow",
		"3470127" => "Caracas",
		"360630" => "Addis Ababa",
		"292968" => "Riyadh",
		"292223" => "Dubai",
		"2464470" => "Lagos",
		"2867714" => "Munich"
	);

	if( kanews_get_option('weather-cities2', 'turkey') == 'global' ) {	
		return $cities;
	} elseif( kanews_get_option('weather-cities2', 'turkey') == 'karma' ) {
		// unset($cities[745044]);
		return $sehirler + $cities;
	}
	return $sehirler;
}

/*-----------------------------------------------------------------------------------*/
# Link Pages
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( 'kanews_link_pages' ) ) {
	function kanews_link_pages() {
		global $page, $numpages;
		$pid = get_the_ID();
		if($numpages == 1)
		return false;

		$type = (kanews_get_option('single-pagination')) ? kanews_get_option('single-pagination') : 'classic';
		$single =  get_post_meta( $pid, 'post_pagination_type', true ) ? get_post_meta( $pid, 'post_pagination_type', true ) : 'default';

		if($single != 'default' && $single != '' ) {
			$scrollThreshold = false; 
			$button = 'no'; 
			$data = false;
			if($single == 'infinite') {
				$scrollThreshold = 100;
				$data = true;
			}
			elseif($single == 'button') {
				$button = '.kanews-entry-load-more';
				$data = true;
			}
		} else {
			$scrollThreshold = false; 
			$button = 'no'; 
			$data = false;
			if($type == 'infinite') {
				$scrollThreshold = 100;
				$data = true;
			}
			elseif($type == 'button') {
				$button = '.kanews-entry-load-more';
				$data = true;
			}
		}

		echo '<div class="page-links" data-status="'.$data.'" data-scrollThreshold="'.$scrollThreshold.'" data-button="'.$button.'">';
			echo paginate_links( array(
    'base' => trailingslashit(get_permalink()) . '%#%/',  // trailingslashit ile sonuna fazladan slash eklememeyi garanti eder.
    'format' => '%#%/',  // Bu satırda get_permalink() kullanmaya gerek yok.
				'current' => $page,
				'total' => $numpages,
				'next_text' => esc_html__( 'Sonraki Sayfa', 'kanews' ),
				'prev_text' => esc_html__( 'Önceki Sayfa', 'kanews' ),
			) );
			
		echo '</div>';
	}
	
}

function kanews_link_pages_after() { 
	$pid = get_the_ID();
	$type = (kanews_get_option('single-pagination')) ? kanews_get_option('single-pagination') : 'classic';
	$single =  get_post_meta( $pid, 'post_pagination_type', true ) ? get_post_meta( $pid, 'post_pagination_type', true ) : 'default';
	global $page, $numpages;
	if($numpages == 1)
	return false;

	if($single != 'default' && $single != '' ) : ?>
		<?php if($single == 'button') :?>
			<div class="page-load-status">
				<div class="loader-ellips infinite-scroll-request">
					<svg version="1.1" id="loader-1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="40px" height="40px" viewBox="0 0 40 40" enable-background="new 0 0 40 40" xml:space="preserve"> <path opacity="0.2" fill="#000" d="M20.201,5.169c-8.254,0-14.946,6.692-14.946,14.946c0,8.255,6.692,14.946,14.946,14.946 s14.946-6.691,14.946-14.946C35.146,11.861,28.455,5.169,20.201,5.169z M20.201,31.749c-6.425,0-11.634-5.208-11.634-11.634 c0-6.425,5.209-11.634,11.634-11.634c6.425,0,11.633,5.209,11.633,11.634C31.834,26.541,26.626,31.749,20.201,31.749z"/> <path fill="#000" d="M26.013,10.047l1.654-2.866c-2.198-1.272-4.743-2.012-7.466-2.012h0v3.312h0 C22.32,8.481,24.301,9.057,26.013,10.047z"> <animateTransform attributeType="xml" attributeName="transform" type="rotate" from="0 20 20" to="360 20 20" dur="0.5s" repeatCount="indefinite"/> </path> </svg>
				</div>
				<p class="infinite-scroll-last"><?php _e('Yazı Sona Erdi!', 'kanews'); ?></p>
				<p class="infinite-scroll-error"><?php _e('Yüklenemedi, lütfen tekrar deneyiniz.', 'kanews'); ?></p>
			</div>
			<button class="kanews-entry-load-more kanews-label"><?php esc_html_e( 'Daha Fazla Yükle', 'kanews' ); ?></button>
		<?php elseif($single == 'infinite'): ?>
			<div class="page-load-status">
				<div class="loader-ellips infinite-scroll-request">
					<svg version="1.1" id="loader-1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="40px" height="40px" viewBox="0 0 40 40" enable-background="new 0 0 40 40" xml:space="preserve"> <path opacity="0.2" fill="#000" d="M20.201,5.169c-8.254,0-14.946,6.692-14.946,14.946c0,8.255,6.692,14.946,14.946,14.946 s14.946-6.691,14.946-14.946C35.146,11.861,28.455,5.169,20.201,5.169z M20.201,31.749c-6.425,0-11.634-5.208-11.634-11.634 c0-6.425,5.209-11.634,11.634-11.634c6.425,0,11.633,5.209,11.633,11.634C31.834,26.541,26.626,31.749,20.201,31.749z"/> <path fill="#000" d="M26.013,10.047l1.654-2.866c-2.198-1.272-4.743-2.012-7.466-2.012h0v3.312h0 C22.32,8.481,24.301,9.057,26.013,10.047z"> <animateTransform attributeType="xml" attributeName="transform" type="rotate" from="0 20 20" to="360 20 20" dur="0.5s" repeatCount="indefinite"/> </path> </svg>
				</div>
				<p class="infinite-scroll-last"><?php _e('Yazı Sona Erdi!', 'kanews'); ?></p>
				<p class="infinite-scroll-error"><?php _e('Yüklenemedi, lütfen tekrar deneyiniz.', 'kanews'); ?></p>
			</div>
		<?php endif; ?>
	<?php else: ?>
		<?php if($type == 'button') :?>
			<div class="page-load-status">
				<div class="loader-ellips infinite-scroll-request">
					<svg version="1.1" id="loader-1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="40px" height="40px" viewBox="0 0 40 40" enable-background="new 0 0 40 40" xml:space="preserve"> <path opacity="0.2" fill="#000" d="M20.201,5.169c-8.254,0-14.946,6.692-14.946,14.946c0,8.255,6.692,14.946,14.946,14.946 s14.946-6.691,14.946-14.946C35.146,11.861,28.455,5.169,20.201,5.169z M20.201,31.749c-6.425,0-11.634-5.208-11.634-11.634 c0-6.425,5.209-11.634,11.634-11.634c6.425,0,11.633,5.209,11.633,11.634C31.834,26.541,26.626,31.749,20.201,31.749z"/> <path fill="#000" d="M26.013,10.047l1.654-2.866c-2.198-1.272-4.743-2.012-7.466-2.012h0v3.312h0 C22.32,8.481,24.301,9.057,26.013,10.047z"> <animateTransform attributeType="xml" attributeName="transform" type="rotate" from="0 20 20" to="360 20 20" dur="0.5s" repeatCount="indefinite"/> </path> </svg>
				</div>
				<p class="infinite-scroll-last"><?php _e('Yazı Sona Erdi!', 'kanews'); ?></p>
				<p class="infinite-scroll-error"><?php _e('Yüklenemedi, lütfen tekrar deneyiniz.', 'kanews'); ?></p>
			</div>
			<button class="kanews-entry-load-more kanews-label"><?php esc_html_e( 'Daha Fazla Yükle', 'kanews' ); ?></button>
		<?php elseif($type == 'infinite'): ?>
			<div class="page-load-status">
				<div class="loader-ellips infinite-scroll-request">
					<svg version="1.1" id="loader-1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="40px" height="40px" viewBox="0 0 40 40" enable-background="new 0 0 40 40" xml:space="preserve"> <path opacity="0.2" fill="#000" d="M20.201,5.169c-8.254,0-14.946,6.692-14.946,14.946c0,8.255,6.692,14.946,14.946,14.946 s14.946-6.691,14.946-14.946C35.146,11.861,28.455,5.169,20.201,5.169z M20.201,31.749c-6.425,0-11.634-5.208-11.634-11.634 c0-6.425,5.209-11.634,11.634-11.634c6.425,0,11.633,5.209,11.633,11.634C31.834,26.541,26.626,31.749,20.201,31.749z"/> <path fill="#000" d="M26.013,10.047l1.654-2.866c-2.198-1.272-4.743-2.012-7.466-2.012h0v3.312h0 C22.32,8.481,24.301,9.057,26.013,10.047z"> <animateTransform attributeType="xml" attributeName="transform" type="rotate" from="0 20 20" to="360 20 20" dur="0.5s" repeatCount="indefinite"/> </path> </svg>
				</div>
				<p class="infinite-scroll-last"><?php _e('Yazı Sona Erdi!', 'kanews'); ?></p>
				<p class="infinite-scroll-error"><?php _e('Yüklenemedi, lütfen tekrar deneyiniz.', 'kanews'); ?></p>
			</div>
		<?php endif; ?>
	<?php endif; ?>
<?php }

/*-----------------------------------------------------------------------------------*/
# Translate
/*-----------------------------------------------------------------------------------*/
function kanews_translate($option, $default, $sprint = NULL) {
	$text = kanews_get_option2($option) != '' ? kanews_get_option2($option) : $default;
	
	if($sprint == true)
	return sprintf($text, get_bloginfo( 'name' ));
	else
	return $text;
}

/*-----------------------------------------------------------------------------------*/
# Navbar List Sub Categories
/*-----------------------------------------------------------------------------------*/
function kanews_navbar_sub_category() {
	if(kanews_get_option('navbar-sub-category') == false)
	return;

	$category= get_category( get_query_var( 'cat' ), false );

	if($category->parent != 0)
	$category = get_category($category->category_parent, false);

	$categories = get_categories(
		array( 'parent' => $category->term_id )
	);

	// $category= get_category( get_query_var( 'cat' ), false );
	if($categories):?>

		<div id="navbar-sub" class="site-navbar-sub hidden-mobile">
			<div class="container">
				<div class="navbar-row">
					<ul class="d-flex flex-wrap flex-scroll">
						<li class="parent"><?php echo get_cat_name( $category->term_id ); ?></li>
						<?php foreach ($categories as $c) {
							$category->term_id == $c->term_id ? $current = 'class="current-menu-item"' : $current = '';
							echo '<li '. $current .'><a href="'.get_category_link($c->cat_ID).'">'.$c->cat_name.'</a></li>';
						} ?>
					</ul>
				</div>
			</div>
		</div>
	<?php endif;
}
/*-----------------------------------------------------------------------------------*/
# Get Comment Count
/*-----------------------------------------------------------------------------------*/
function kanews_get_comments_count_by_user($userID) {
    $args = array(
      'user_id' => $userID
    );
    $comments = get_comments( $args );
    return count($comments);
}

/*-----------------------------------------------------------------------------------*/
# Connect api with curl
/*-----------------------------------------------------------------------------------*/
function kanews_connect_api($site_url , $timeout = 20) {
	$ch = curl_init();

	$tarayici = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:32.0) Gecko/20100101 Firefox/32.0';

	curl_setopt($ch, CURLOPT_URL,$site_url);

	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER , 0);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER , 1);
	curl_setopt($ch, CURLOPT_HEADER         , 0);
	curl_setopt($ch, CURLOPT_TIMEOUT        , $timeout);
	curl_setopt($ch, CURLOPT_USERAGENT      , $tarayici);

	$result = curl_exec($ch);
	curl_close($ch);

	return $result;
}

/*-----------------------------------------------------------------------------------*/
# Kanews Weather Data
/*-----------------------------------------------------------------------------------*/
add_action( 'wp_ajax_nopriv_kanews_get_user_weather', 'get_user_weather' );
add_action( 'wp_ajax_kanews_get_user_weather', 'get_user_weather' );
function get_user_weather(){

	if( ! empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
		$ip = $_SERVER['HTTP_CLIENT_IP'];
	}
	elseif( ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
		$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
	}
	else{
		$ip = $_SERVER['REMOTE_ADDR'];
	}

	// $ip = '88.241.98.11';

	if( ! empty( $ip ) ){

		if ( strpos( $ip, ',' ) !== false ) {
			$ip = explode( ',', $ip );
			$ip = $ip[0];
		}
	
		$request = wp_remote_get( 'http://ip-api.com/json/'.$ip );

		if( ! is_wp_error( $request ) ){
			
			$request = wp_remote_retrieve_body( $request );
			$request = json_decode( $request, true );

			if( $request && ! empty( $request['status'] ) && $request['status'] == 'success' ){
				$city = $request['city'];
			}
		}
	} 

	if( empty( $city ) ){
		echo '<div class="p-1">'.esc_html__( 'Veri alınamadı!!', 'kanews' ).'</div>' ;
		die;
	}

	// --
	if( empty( $city ) ){
		echo '<div class="p-1">'.esc_html__( 'Veri alınamadı!!', 'kanews' ).'</div>' ;
		die;
	}else {

		$apikey = kanews_get_option('openweathermap-api');
		$api_url = 'http://api.openweathermap.org/data/2.5/weather?q='.$city.'&lang='.substr(get_locale(), 0, 2).'&units=metric&appid='.$apikey;
		$api_connect = wp_remote_get( $api_url, array( 'timeout' => 10 ) );

		if( is_wp_error( $api_connect ) ) {
			echo '<div class="p-1">'.esc_html__( 'Veri alınamadı!!', 'kanews' ).'</div>' ;
			die;
		}

		$data = json_decode( $api_connect['body'], true ); 
		
		$weather_id = ! empty( $data['weather'][0]['id'] ) ? $data['weather'][0]['id']  : 800;

		if( $weather_id < 300 ) { // Fırtına
			$bg_color =  'linear-gradient(rgb(44, 70, 108) 0%, rgb(20, 36, 60) 100%)';
			$bg_image =  get_template_directory_uri().'/assets/img/static/weather/Sunny.webp';
			}elseif( $weather_id < 502 ) { // Hafif Yağmur - Çiseleme
			$bg_color =  'linear-gradient(rgb(44, 70, 108) 0%, rgb(20, 36, 60) 100%)';
			$bg_image =  get_template_directory_uri().'/assets/img/static/weather/Rain.webp';
			}elseif( $weather_id < 600 ) { // Aşırı Yağmur
			$bg_color =  'linear-gradient(rgb(52, 92, 132) 0%, rgb(44, 76, 116) 100%)';
			$bg_image =  get_template_directory_uri().'/assets/img/static/weather/Rain-1.webp';
			}elseif( $weather_id < 700 ){ // karlı
			$bg_color =  'linear-gradient(rgb(41, 87, 147) 0%, rgb(12, 60, 124) 100%)';
			$bg_image =  get_template_directory_uri().'/assets/img/static/weather/Snow.webp';
			}elseif( $weather_id < 721 ){ // Bulutlu çok  
			$bg_color =  'linear-gradient(rgb(36, 77, 114) 0%, rgb(7, 33, 59) 100%)';
			$bg_image =  get_template_directory_uri().'/assets/img/static/weather/Cloudy.webp';
			}elseif( $weather_id == 721 ){ // Puslu 
			$bg_color =  'linear-gradient(rgb(45, 65, 86) 0%, rgb(26, 28, 36) 100%)';
			$bg_image =  get_template_directory_uri().'/assets/img/static/weather/Hazy.webp';
			}elseif( $weather_id < 800 ){ // Bulutlu 
			$bg_color =  'linear-gradient(rgb(76, 92, 122) 0%, rgb(52, 68, 100) 100%)';
			$bg_image =  get_template_directory_uri().'/assets/img/static/weather/Cloudy-2.webp';
			}else { 
			$bg_color =  'linear-gradient(rgb(36, 84, 148) 0%, rgb(28, 68, 132) 100%)';
			$bg_image =  get_template_directory_uri().'/assets/img/static/weather/Sunny.webp';
			}
		
		?>

		<div class="kanews-weather-widget-wrapper">
        <div class="kanews-weather-widget <?php echo (kanews_get_option('weather-page') != '') ? 'nbs1' : ''; ?>">
          <div class="kanews-weather-widget-bg kanews-lazy" style="background-image: url(<?php echo $bg_image; ?>);"></div>
          <div class="kanews-weather-widget-container">

            <div class="kanews-weather-widget-header">
              <div class="kanews-weather-widget-label"><?php echo sprintf(esc_html__('%s için Hava Durumu', 'kanews'), $city); ?></div>
              <div class="kanews-location-weather"><svg version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 384 384" style="enable-background:new 0 0 384 384;" xml:space="preserve"><g><g><path d="M192,136c-30.872,0-56,25.12-56,56s25.128,56,56,56s56-25.12,56-56S222.872,136,192,136z M192,216c-13.232,0-24-10.768-24-24s10.768-24,24-24s24,10.768,24,24S205.232,216,192,216z"/></g></g><g><g><path d="M368,176h-32.944C327.648,109.368,274.632,56.352,208,48.944V16c0-8.832-7.168-16-16-16c-8.832,0-16,7.168-16,16v32.944C109.368,56.352,56.352,109.368,48.944,176H16c-8.832,0-16,7.168-16,16c0,8.832,7.168,16,16,16h32.944C56.352,274.632,109.368,327.648,176,335.056V368c0,8.832,7.168,16,16,16c8.832,0,16-7.168,16-16v-32.944c66.632-7.408,119.648-60.424,127.056-127.056H368c8.832,0,16-7.168,16-16C384,183.168,376.832,176,368,176z M192,304c-61.76,0-112-50.24-112-112S130.24,80,192,80s112,50.24,112,112S253.76,304,192,304z"/></g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g></svg></div>
          
            </div>

            <div class="kanews-weather-widget-content">
              <div class="kanews-weather-widget-overall d-flex flex-wrap align-items-center">
                <?php echo kanews_get_local_image(KAN_TEMPLATE_URL.'/assets/img/weather/svg/'.$data['weather'][0]['icon'].'.svg', $attr = ['width' => 128, 'height' => 128, 'alt' => $data['weather'][0]['icon'] ] ); ?>
                <div class="kanews-weather-widget-temp"><?php echo round($data['main']['temp'], 1); ?><sup>‎°C</sup></div>
                <div class="mb-1">
                
                <div class="kanews-weather-widget-caption"><div><?php echo ucwords($data['weather'][0]['description']); ?></div><div><?php esc_html_e('Hissedilen', 'kanews'); ?> <span><?php echo round($data['main']['feels_like'], 1); ?> °</span></div></div>
              </div>
              </div>
            </div>

            <div class="kanews-weather-widget-footer">
              <div class="kanews-weather-widget-meta">
                <div class="kanews-weather-widget-meta-item">
                  <div class="kanews-weather-widget-meta-label"><svg aria-label="<?php esc_html_e( 'Rüzgar Hızı', 'kanews' ); ?>" aria-hidden="false" role="img" viewBox="0 0 24 24"><path d="M6 8.67h5.354c1.457 0 2.234-1.158 2.234-2.222S12.687 4.4 11.354 4.4c-.564 0-1.023.208-1.366.488M3 11.67h15.54c1.457 0 2.235-1.158 2.235-2.222S19.873 7.4 18.54 7.4c-.747 0-1.311.365-1.663.78M6 15.4h9.389c1.457 0 2.234 1.159 2.234 2.223 0 1.064-.901 2.048-2.234 2.048a2.153 2.153 0 0 1-1.63-.742" stroke-width="2" stroke="currentColor" stroke-linecap="round" fill="none"></path></svg> 
                  <?php esc_html_e( 'Rüzgar Hızı', 'kanews' ); ?></div>
                  <div class="kanews-weather-widget-meta-value"><?php echo round($data['wind']['speed'], 3); ?> mph/s</div>
                </div>
          
                <div class="kanews-weather-widget-meta-item">
                  <div class="kanews-weather-widget-meta-label"><svg aria-label="<?php esc_html_e( 'Nem', 'kanews' ); ?>" aria-hidden="false"  enable-background="new 0 0 510.013 510.013" height="512" viewBox="0 0 510.013 510.013" width="512" xmlns="http://www.w3.org/2000/svg"><g><path d="m179.207 446c-26.473 0-47.2-21.354-47.2-47 0-20.68 13.41-38.27 32-44.55v-52.45h-33v-30h33v-34h-33v-30h33v-34h-33v-30h33v-73h30v222.14c26.941-52.674 66.638-108.692 104-156.58v-17.56c0-65.77-53.215-119-119-119-65.62 0-119 53.38-119 119v391h170.79c-22.39-16.3-40.32-38.37-51.59-64z"/><path d="m323.007 153.29c-38.46 49.295-128.75 170.151-126.96 232.86 0 47.318 32.114 97.368 82.72 115.9 10.498 4.155 28.195 7.7 36.24 7.7 72.982 4.68 135-53.608 135-126.75 0-61.183-89.706-181.909-127-229.71zm47.5 268.71c-8 0-14.5-6.5-14.5-14.5s6.5-14.5 14.5-14.5 14.5 6.5 14.5 14.5-6.5 14.5-14.5 14.5zm-88-101c10.053 0 17.047 10.004 13.63 19.46v.01c-2.04 5.55-7.37 9.53-13.63 9.53-8 0-14.5-6.5-14.5-14.5s6.5-14.5 14.5-14.5zm28.71 109.11c-5.692-3.065-1.13-.609-26.42-14.22 21.799-40.488 10.782-20.028 56-104l26.42 14.22z"/></g></svg>
                    <?php esc_html_e( 'Nem', 'kanews' ); ?></div>
                  <div class="kanews-weather-widget-meta-value"><?php echo round($data['main']['humidity'], 0); ?> %</div>
                </div>
          
                <div class="kanews-weather-widget-meta-item">
                  <div class="kanews-weather-widget-meta-label"><?php esc_html_e( 'Basınç', 'kanews' ); ?></div>
                  <div class="kanews-weather-widget-meta-value"><?php echo $data['main']['pressure']; ?> mb</div>
                </div>
          
                <div class="kanews-weather-widget-meta-item">
                  <div class="kanews-weather-widget-meta-label"><?php esc_html_e( 'Minumum Sıcaklık', 'kanews' ); ?></div>
                  <div class="kanews-weather-widget-meta-value"><?php echo $data['main']['temp_min']; ?>°</div>
                </div>
          
                <div class="kanews-weather-widget-meta-item">
                  <div class="kanews-weather-widget-meta-label"><?php esc_html_e( 'Maksimum Sıcaklık', 'kanews' ); ?></div>
                  <div class="kanews-weather-widget-meta-value"><?php echo $data['main']['temp_max']; ?>°</div>
                </div>
              </div>
            </div>

          </div>
        </div>
      </div>


      <?php if(kanews_get_option('weather-page') != '' ): ?>

        <a class="kanews-kmg21" href="<?php echo kanews_get_page_link('sehir', replace_tr(strtolower($city)), 'weather'); ?>" ><?php esc_html_e('Tüm hava tahminini göster', 'kanews'); ?></a>
    
      <?php endif; 
		
	} 

	die;
}

/*-----------------------------------------------------------------------------------*/
# Kanews Weather Data
/*-----------------------------------------------------------------------------------*/
function kanews_weather_data($sehir){
	$apikey = kanews_get_option('openweathermap-api');
	$kaynak = kanews_connect_api('api.openweathermap.org/data/2.5/forecast?id='.$sehir.'&mode=json&lang='.substr(get_locale(), 0, 2).'&units=metric&appid='.$apikey);
	$jsoncikti = json_decode($kaynak,true);
	$bir_onceki_gun = '';

	foreach ($jsoncikti['list'] as $key => $value) {
		// print_r($value);
		if(date('d.m.Y', $value['dt'])==$bir_onceki_gun){
			$gun[$bir_onceki_gun][date('H:i', $value['dt'])] = array(
				'sicaklik'=>$value['main']['temp'],
				'hissedilen'=>$value['main']['feels_like'],
				'nem'=>$value['main']['humidity'],
				'hiz'=>$value['wind']['speed'],
				'desc'=>$value['weather'][0]['description'],
				'icon'=>$value['weather'][0]['icon']
			);
		}else{
			$gun[date('d.m.Y', $value['dt'])] = array( date('H:i', $value['dt']) => array(
				'sicaklik'=>$value['main']['temp'],
				'nem'=>$value['main']['humidity'],
				'hissedilen'=>$value['main']['feels_like'],
				'hiz'=>$value['wind']['speed'],
				'desc'=>$value['weather'][0]['description'],
				'icon'=>$value['weather'][0]['icon']
			));
		}
		$bir_onceki_gun = date('d.m.Y', $value['dt']);
	}
	return $gun;
}

/*-----------------------------------------------------------------------------------*/
# Kanews Weather Ajax
/*-----------------------------------------------------------------------------------*/
add_action( 'wp_ajax_nopriv_kanews_weather_select_city', 'kanews_weather_select_city' );
add_action( 'wp_ajax_kanews_weather_select_city', 'kanews_weather_select_city' );
function kanews_weather_select_city() {
	echo '<div id="kanews-weather-loader"></div>';
	$counter = 0; foreach (kanews_weather_data($_POST['id']) as $key => $value) { $counter++;
	?>
		<div class="col-12">
			
			<div class="kanews-weather-wrapper">
				<?php if($counter == 1): ?>
					<h2 class="kanews-weather-day"><?php _e('Bugün', 'kanews'); echo ' <span>'.$key.'</span>'; ?></h2>
				<?php else: ?>
					<?php $nameOfDay = date('D', strtotime($key)); $day = kanews_translate_days($nameOfDay); 
					echo '<h2 class="kanews-weather-day">'.$day.' <span>'.__('Günü Hava Tahminleri', 'kanews').'</span> </h2>'; ?>
				<?php endif; ?>
				
					<div>
						<?php
						foreach ($value as $key => $val) {
							?>
							<div class="kanews-weather-item d-flex flex-wrap align-items-center">
								<div class="kanews-weather-time col-auto"><span class="kanews-label kanews-label-sm"><?=$key; ?></span></div>
								<div class="kanews-weather-temp col-auto"><?=round($val['sicaklik'], 1); ?> °</div>
								<div class="kanews-weather-icon col-auto"><img width="48" height="48" src="<?php echo KAN_TEMPLATE_URL; ?>/assets/img/weather/svg/<?=$val['icon']; ?>.svg" alt=""></div>
                        <div class="kanews-weather-desc col-12 col-lg"><?=$val['desc']; ?></div>
								<div class="kanews-weather-label col-12 col-lg d-flex justify-content-end">
									<div class="kanews-weather-feels-like" title="<?php _e('Hissedilen Sıcaklık', 'kanews'); ?>"><svg aria-label="Hissedilen" aria-hidden="false" role="img" viewBox="0 0 24 24"><path d="M9.94 15.406v.323c.974.358 1.671 1.325 1.671 2.461 0 1.441-1.122 2.61-2.505 2.61-1.384 0-2.506-1.169-2.506-2.61 0-1.136.697-2.103 1.67-2.461v-.323a2.088 2.088 0 0 1-1.252-1.914V5.488a2.088 2.088 0 1 1 4.176 0v8.004c0 .856-.516 1.592-1.253 1.914zM9.15 4.9a.75.75 0 0 0-.75.75v5.33h1.5V5.65a.75.75 0 0 0-.75-.75zM15.4 8a2.8 2.8 0 1 1 0-5.6 2.8 2.8 0 0 1 0 5.6zm0-1.8a1 1 0 1 0 0-2 1 1 0 0 0 0 2z"></path></svg><span><?=round($val['hissedilen'], 1); ?> °</span></div>
									<div class="kanews-weather-wind" title="<?php _e('Rüzgar Hızı', 'kanews'); ?>"><svg aria-label="Rüzgar" aria-hidden="false" role="img" viewBox="0 0 24 24"><path d="M6 8.67h5.354c1.457 0 2.234-1.158 2.234-2.222S12.687 4.4 11.354 4.4c-.564 0-1.023.208-1.366.488M3 11.67h15.54c1.457 0 2.235-1.158 2.235-2.222S19.873 7.4 18.54 7.4c-.747 0-1.311.365-1.663.78M6 15.4h9.389c1.457 0 2.234 1.159 2.234 2.223 0 1.064-.901 2.048-2.234 2.048a2.153 2.153 0 0 1-1.63-.742" stroke-width="2" stroke="currentColor" stroke-linecap="round" fill="none"></path></svg><span><?=$val['hiz']; ?> mph</span></div>
									<div class="kanews-weather-nem" title="<?php _e('Nem', 'kanews'); ?>"><svg aria-label="Nem" aria-hidden="false" role="img" viewBox="0 -2 5 10"><path d="M4.7329.0217c-.1848-.059-.3855.0064-.4803.148L.2731 5.1191c-.0814.0922-.1501.1961-.196.3108-.2469.6009.1185 1.2697.8156 1.4943.6914.226 1.447-.0712 1.7-.6585L4.9662.4987l.0111-.0282c.073-.1807-.036-.379-.2444-.4488z"></path></svg><span><?=$val['nem']; ?>%</span></div>
								</div>
							</div>
						<?php 
						}
						?>
					</div>
				</div>
			
		</div>
	<?php 
	}
}

/*-----------------------------------------------------------------------------------*/
# Translate Days
/*-----------------------------------------------------------------------------------*/
function kanews_translate_days($gun) { 
	switch ($gun) {
		 case 'Mon':
				return esc_html__( 'Pazartesi', 'kanews' );
				break;
		 case 'Tue':
				return esc_html__( 'Salı', 'kanews' );
				break;
		 case 'Wed':
				return esc_html__( 'Çarşamba', 'kanews' );
				break;
		 case 'Thu':
				return esc_html__( 'Perşembe', 'kanews' );
				break;
		 case 'Fri':
				return esc_html__( 'Cuma', 'kanews' );
				break;
		 case 'Sat':
				return esc_html__( 'Cumartesi', 'kanews' );
				break;
		 case 'Sun':
				return esc_html__( 'Pazar', 'kanews' );
				break;
		default:
		return $gun;
	}
}

/*-----------------------------------------------------------------------------------*/
# Translate Months
/*-----------------------------------------------------------------------------------*/
function kanews_translate_months($month) { 
	switch ($month) {
		 case 'Jan':
				return esc_html__( 'Ocak', 'kanews' );
				break;
		 case 'Feb':
				return esc_html__( 'Şubat', 'kanews' );
				break;
		 case 'Mar':
				return esc_html__( 'Mart', 'kanews' );
				break;
		 case 'Apr':
				return esc_html__( 'Nisan', 'kanews' );
				break;
		 case 'May':
				return esc_html__( 'Mayıs', 'kanews' );
				break;
		 case 'Jun':
				return esc_html__( 'Haziran', 'kanews' );
				break;
		 case 'Jul':
				return esc_html__( 'Temmuz', 'kanews' );
				break;
		 case 'Aug':
				return esc_html__( 'Ağustos', 'kanews' );
				break;
		 case 'Sep':
				return esc_html__( 'Eylül', 'kanews' );
				break;
		 case 'Oct':
				return esc_html__( 'Ekim', 'kanews' );
				break;
		 case 'Nov':
				return esc_html__( 'Kasım', 'kanews' );
				break;
		 case 'Dec':
				return esc_html__( 'Aralık', 'kanews' );
				break;
		default:
		return $month;
	}
}

/*-----------------------------------------------------------------------------------*/
#  Sef Link
/*-----------------------------------------------------------------------------------*/
function kanews_seflink($text){
	$find = array("/Ğ/","/Ü/","/Ş/","/İ/","/Ö/","/Ç/","/ğ/","/ü/","/ş/","/ı/","/ö/","/ç/");
	$degis = array("G","U","S","I","O","C","g","u","s","i","o","c");
	$text = preg_replace("/[^0-9a-zA-ZÄzÜŞİÖÇğüşıöç]/"," ",$text);
	$text = preg_replace($find,$degis,$text);
	$text = preg_replace("/ +/"," ",$text);
	$text = preg_replace("/ /","-",$text);
	$text = preg_replace("/\s/","",$text);
	$text = strtolower($text);
	$text = preg_replace("/^-/","",$text);
	$text = preg_replace("/-$/","",$text);
	if($text)
	return $text;
	else
	return '#';
}

/*-----------------------------------------------------------------------------------*/
#  Placeholder Image
/*-----------------------------------------------------------------------------------*/
function kanews_lazy_link() {
	return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAABCAQAAABeK7cBAAAAC0lEQVR42mNkAAIAAAoAAv/lxKUAAAAASUVORK5CYII=';
}
function kanews_lazy_link2() {
	return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAADCAQAAAAT4xYKAAAAEElEQVR42mN89p+BgRFOAAAwVwWzWvPRBQAAAABJRU5ErkJggg==';
}

if( ! function_exists( 'kanews_lazyload_placeholder' ) ) {

	function kanews_lazyload_placeholder( $size = '' ){

		switch ( $size ) {

			case '1e2':
				return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAADCAQAAAAT4xYKAAAAEElEQVR42mN89p+BgRFOAAAwVwWzWvPRBQAAAABJRU5ErkJggg==';
				break;

			case '1e1':
				return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=';
				break;

			case '3e2':
				return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAACCAQAAAA3fa6RAAAADklEQVR42mNkAANGCAUAACMAA2w/AMgAAAAASUVORK5CYII=';
				break;

			case '3e1':
				return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAABCAQAAACx6dw/AAAAC0lEQVR42mNkAAMAAA4AAjOwv9wAAAAASUVORK5CYII=';
				break;

			case '2e3':
				return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAADCAQAAAAT4xYKAAAADklEQVR42mNkAAJGOAEAAC0ABNxMS2YAAAAASUVORK5CYII=';
				break;

			case 'wide':
				return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAKCAYAAADVTVykAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAB9JREFUeNpi/P//P8NAAiaGAQajDhh1wKgDRh0AEGAAQTcDEcKDrpMAAAAASUVORK5CYII=';
				break;

			default:
				return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAABCAQAAABeK7cBAAAAC0lEQVR42mNkAAIAAAoAAv/lxKUAAAAASUVORK5CYII=';
				break;
		}
		
	}
}

function kanews_get_local_image($src = '', $attr = [], $placeholder = '', $slick = false ) {
	if( kanews_lazyload_active() ) {
		if($slick) {
		return '<img loading="lazy" src="'.kanews_lazyload_placeholder($placeholder).'" data-lazy="'.$src.'" '. implode(' ', array_map(
			function ($k, $v) { return $k .'="'. htmlspecialchars($v) .'"'; },
			array_keys($attr), $attr
		)) .' />';
		} else {
		return '<img loading="lazy" class="kanews-lazy" src="'.kanews_lazyload_placeholder($placeholder).'" data-src="'.$src.'" '. implode(' ', array_map(
			function ($k, $v) { return $k .'="'. htmlspecialchars($v) .'"'; },
			array_keys($attr), $attr
		)) .' />';
		}
	} else {
		return '<img loading="lazy" src="'.$src.'" '. implode(' ', array_map(
			function ($k, $v) { return $k .'="'. htmlspecialchars($v) .'"'; },
			array_keys($attr), $attr
		)) .' />';
	}
}

/*-----------------------------------------------------------------------------------*/
# Mode Button
/*-----------------------------------------------------------------------------------*/
function kanews_dark_mode_button() {
	if ( ! kanews_get_option( 'mode' ) ) {
		return '';
	}

	$supports_system = 1; // Sistem modu her zaman aktif
	$default_mode    = kanews_get_option( 'default-mode', 'light' );

	$cookie_mode = '';
	if ( isset( $_COOKIE['kanews_theme_mode'] ) ) {
		$cookie_mode = sanitize_key( wp_unslash( $_COOKIE['kanews_theme_mode'] ) );
	}

	$current_mode = in_array( $cookie_mode, array( 'light', 'dark', 'system' ), true ) ? $cookie_mode : '';

	if ( ! $current_mode ) {
		if ( isset( $_COOKIE['kanews_dark_mode_override'] ) ) {
			$current_mode = ( isset( $_COOKIE['kanews_dark_mode'] ) && 'on' === $_COOKIE['kanews_dark_mode'] ) ? 'dark' : 'light';
		} else {
			$current_mode = 'system' === $default_mode ? 'system' : ( 'dark' === $default_mode ? 'dark' : 'light' );
		}
	}

	$icons = array(
		'light'  => '<i class="icon-sun"></i>',
		'dark'   => '<i class="icon-moon-fill"></i>',
		'system' => '<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" class="remixicon size-5 text-text-sub-600"><path d="M6.17071 18C6.58254 16.8348 7.69378 16 9 16C10.3062 16 11.4175 16.8348 11.8293 18H22V20H11.8293C11.4175 21.1652 10.3062 22 9 22C7.69378 22 6.58254 21.1652 6.17071 20H2V18H6.17071ZM12.1707 11C12.5825 9.83481 13.6938 9 15 9C16.3062 9 17.4175 9.83481 17.8293 11H22V13H17.8293C17.4175 14.1652 16.3062 15 15 15C13.6938 15 12.5825 14.1652 12.1707 13H2V11H12.1707ZM6.17071 4C6.58254 2.83481 7.69378 2 9 2C10.3062 2 11.4175 2.83481 11.8293 4H22V6H11.8293C11.4175 7.16519 10.3062 8 9 8C7.69378 8 6.58254 7.16519 6.17071 6H2V4H6.17071ZM9 6C9.55228 6 10 5.55228 10 5C10 4.44772 9.55228 4 9 4C8.44772 4 8 4.44772 8 5C8 5.55228 8.44772 6 9 6ZM15 13C15.5523 13 16 12.5523 16 12C16 11.4477 15.5523 11 15 11C14.4477 11 14 11.4477 14 12C14 12.5523 14.4477 13 15 13ZM9 20C9.55228 20 10 19.5523 10 19C10 18.4477 9.55228 18 9 18C8.44772 18 8 18.4477 8 19C8 19.5523 8.44772 20 9 20Z"></path></svg>',
	);

	// Sistem modunda ikonu belirle
	if ( 'system' === $current_mode ) {
		$icon_markup = $icons['system'];
	} else {
		$icon_markup = isset( $icons[ $current_mode ] ) ? $icons[ $current_mode ] : $icons['light'];
	}

	$options = array(
		'light'  => array(
			'title' => esc_html__( 'Gündüz Modu', 'kanews' ),
			'desc'  => esc_html__( 'Gündüz modunu seçin.', 'kanews' ),
			'icon'  => $icons['light'],
		),
		'dark'   => array(
			'title' => esc_html__( 'Gece Modu', 'kanews' ),
			'desc'  => esc_html__( 'Gece modunu seçin.', 'kanews' ),
			'icon'  => $icons['dark'],
		),
		'system' => array(
			'title' => esc_html__( 'Sistem Modu', 'kanews' ),
			'desc'  => esc_html__( 'Sistem modunu seçin.', 'kanews' ),
			'icon'  => $icons['system'],
		),
	);

	$list_markup = '';
	foreach ( $options as $mode => $data ) {
		$is_active = $mode === $current_mode;
		$list_markup .= sprintf(
			'<li role="none"><button type="button" class="kanews-theme-toggle__option%1$s" role="menuitemradio" data-mode="%2$s" aria-checked="%3$s"><span class="kanews-theme-toggle__option-icon">%4$s</span><span class="kanews-theme-toggle__option-content"><span class="kanews-theme-toggle__option-title">%5$s</span><span class="kanews-theme-toggle__option-desc">%6$s</span></span><span class="kanews-theme-toggle__option-indicator" aria-hidden="true"></span></button></li>',
			$is_active ? ' is-selected' : '',
			esc_attr( $mode ),
			$is_active ? 'true' : 'false',
			$data['icon'],
			$data['title'],
			$data['desc']
		);
	}

	$current_label = isset( $options[ $current_mode ] ) ? $options[ $current_mode ]['title'] : $options['light']['title'];

	return sprintf(
		'<div class="kanews-mode-change kanews-theme-toggle" data-active-mode="%1$s" data-default-mode="%2$s" data-supports-system="%10$d" data-label-template="%9$s">
		<button type="button" class="kanews-theme-toggle__button header-btn-icon" aria-haspopup="true" aria-expanded="false" aria-label="%4$s">
			<span class="kanews-theme-toggle__icon" aria-hidden="true">%3$s</span>
			<span class="screen-reader-text">%5$s</span>
		</button>
		<div class="kanews-theme-toggle__dropdown" role="menu" aria-label="%6$s">
			<div class="kanews-theme-toggle__header">
				<div class="kanews-theme-toggle__title">%6$s</div>
				<p class="kanews-theme-toggle__subtitle">%7$s</p>
			</div>
			<ul class="kanews-theme-toggle__options" role="none">
				%8$s
			</ul>
		</div>
	</div>',
		esc_attr( $current_mode ),
		esc_attr( $default_mode ),
		$icon_markup,
		esc_attr( sprintf( esc_html__( 'Mod değiştir, seçili mod %s', 'kanews' ), $current_label ) ),
		esc_html__( 'Mod değiştir', 'kanews' ),
		esc_html__( 'Mod Ayarları', 'kanews' ),
		esc_html__( 'Mod seçin, deneyimini kişiselleştirin.', 'kanews' ),
		$list_markup,
		esc_attr__( 'Mod değiştir, seçili mod %s', 'kanews' ),
		(int) $supports_system
	);
}

/*-----------------------------------------------------------------------------------*/
# Türkiye Şehir Adı ve Plaka
/*-----------------------------------------------------------------------------------*/
function kanews_get_plaka($ad) {
	$sehir = array(
		'1' =>'Adana',
		'2' =>'Adıyaman',
		'3' =>'Afyonkarahisar',
		'4' =>'Ağrı',
		'5' =>'Amasya',
		'6' =>'Ankara',
		'7' =>'Antalya',
		'8' =>'Artvin',
		'9' =>'Aydın',
		'10' =>'Balıkesir',
		'11' =>'Bilecik',
		'12' =>'Bingöl',
		'13' =>'Bitlis',
		'14' =>'Bolu',
		'15' =>'Burdur',
		'16' =>'Bursa',
		'17' =>'Çanakkale',
		'18' =>'Çankırı',
		'19' =>'Çorum',
		'20' =>'Denizli',
		'21' =>'Diyarbakır',
		'22' =>'Edirne',
		'23' =>'Elâzığ',
		'24' =>'Erzincan',
		'25' =>'Erzurum',
		'26' =>'Eskişehir',
		'27' =>'Gaziantep',
		'28' =>'Giresun',
		'29' =>'Gümüşhane',
		'30' =>'Hakkari',
		'31' =>'Hatay',
		'32' =>'Isparta',
		'33' =>'Mersin',
		'34' =>'İstanbul',
		'35' =>'İzmir',
		'36' =>'Kars',
		'37' =>'Kastamonu',
		'38' =>'Kayseri',
		'39' =>'Kırklareli',
		'40' =>'Kırşehir',
		'41' =>'Kocaeli',
		'42' =>'Konya',
		'43' =>'Kütahya',
		'44' =>'Malatya',
		'45' =>'Manisa',
		'46' =>'Kahramanmaraş',
		'47' =>'Mardin',
		'48' =>'Muğla',
		'49' =>'Muş',
		'50' =>'Nevşehir',
		'51' =>'Niğde',
		'52' =>'Ordu',
		'53' =>'Rize',
		'54' =>'Sakarya',
		'55' =>'Samsun',
		'56' =>'Siirt',
		'57' =>'Sinop',
		'58' =>'Sivas',
		'59' =>'Tekirdağ',
		'60' =>'Tokat',
		'61' =>'Trabzon',
		'62' =>'Tunceli',
		'63' =>'Şanlıurfa',
		'64' =>'Uşak',
		'65' =>'Van',
		'66' =>'Yozgat',
		'67' =>'Zonguldak',
		'68' =>'Aksaray',
		'69' =>'Bayburt',
		'70' =>'Karaman',
		'71' =>'Kırıkkale',
		'72' =>'Batman',
		'73' =>'Şırnak',
		'74' =>'Bartın',
		'75' =>'Ardahan',
		'76' =>'Iğdır',
		'77' =>'Yalova',
		'78' =>'Karabük',
		'79' =>'Kilis',
		'80' =>'Osmaniye',
		'81' =>'Düzce',
	);
	foreach($sehir as $plaka => $sehir) {
		if($ad == $sehir)
		return $plaka;
	}
}
/*-----------------------------------------------------------------------------------*/
# Türkiye Şehir Adı
/*-----------------------------------------------------------------------------------*/
function kanews_get_sehir($plaka = '') {
	$sehir = array(
		'0' =>'Yurt dışı',
		'1' =>'Adana',
		'2' =>'Adıyaman',
		'3' =>'Afyonkarahisar',
		'4' =>'Ağrı',
		'5' =>'Amasya',
		'6' =>'Ankara',
		'7' =>'Antalya',
		'8' =>'Artvin',
		'9' =>'Aydın',
		'10' =>'Balıkesir',
		'11' =>'Bilecik',
		'12' =>'Bingöl',
		'13' =>'Bitlis',
		'14' =>'Bolu',
		'15' =>'Burdur',
		'16' =>'Bursa',
		'17' =>'Çanakkale',
		'18' =>'Çankırı',
		'19' =>'Çorum',
		'20' =>'Denizli',
		'21' =>'Diyarbakır',
		'22' =>'Edirne',
		'23' =>'Elazığ',
		'24' =>'Erzincan',
		'25' =>'Erzurum',
		'26' =>'Eskişehir',
		'27' =>'Gaziantep',
		'28' =>'Giresun',
		'29' =>'Gümüşhane',
		'30' =>'Hakkari',
		'31' =>'Hatay',
		'32' =>'Isparta',
		'33' =>'Mersin',
		'34' =>'İstanbul',
		'35' =>'İzmir',
		'36' =>'Kars',
		'37' =>'Kastamonu',
		'38' =>'Kayseri',
		'39' =>'Kırklareli',
		'40' =>'Kırşehir',
		'41' =>'Kocaeli',
		'42' =>'Konya',
		'43' =>'Kütahya',
		'44' =>'Malatya',
		'45' =>'Manisa',
		'46' =>'Kahramanmaraş',
		'47' =>'Mardin',
		'48' =>'Muğla',
		'49' =>'Muş',
		'50' =>'Nevşehir',
		'51' =>'Niğde',
		'52' =>'Ordu',
		'53' =>'Rize',
		'54' =>'Sakarya',
		'55' =>'Samsun',
		'56' =>'Siirt',
		'57' =>'Sinop',
		'58' =>'Sivas',
		'59' =>'Tekirdağ',
		'60' =>'Tokat',
		'61' =>'Trabzon',
		'62' =>'Tunceli',
		'63' =>'Şanlıurfa',
		'64' =>'Uşak',
		'65' =>'Van',
		'66' =>'Yozgat',
		'67' =>'Zonguldak',
		'68' =>'Aksaray',
		'69' =>'Bayburt',
		'70' =>'Karaman',
		'71' =>'Kırıkkale',
		'72' =>'Batman',
		'73' =>'Şırnak',
		'74' =>'Bartın',
		'75' =>'Ardahan',
		'76' =>'Iğdır',
		'77' =>'Yalova',
		'78' =>'Karabük',
		'79' =>'Kilis',
		'80' =>'Osmaniye',
		'81' =>'Düzce',
	);
	if($plaka != '')
	return $sehir[$plaka];
	else
	return $sehir;
}

/*-----------------------------------------------------------------------------------*/
# Upload User File
/*-----------------------------------------------------------------------------------*/
function upload_user_file( $file = array() ) {
	require_once( ABSPATH . 'wp-admin/includes/admin.php' );

	if ( strstr( $file['name'], '.php' ) )
	return false;

	$image_info = @getimagesize($file["tmp_name"]);
	$image_width = $image_info[0];
	$image_height = $image_info[1];

	if ($image_width > 2000 || $image_height > 2000 )
	return array('error' => esc_html__('Yüklediğiniz görselin çözünürlüğü 2000x2000\'den düşük olmalıdır.', 'kanews'));
	
	if(isset($file)) {
		if($file['size'] > 1048576  ) {
			return array('error' => esc_html__('Yüklediğiniz görselin boyutu maksimum 1 MB olmalıdır.', 'kanews'));
		}
	}

	$mimes = array(
		'jpg|jpeg|jpe' => 'image/jpeg',
		'png'          => 'image/png',
		'webp'         => 'image/webp', // WebP formatı için eklenmiş giriş

	);
	$file_return = wp_handle_upload( $file, array('mimes' => $mimes, 'test_form' => false, 'unique_filename_callback' => 'kan_filename' ) );
	
	if( isset( $file_return['error'] ) || isset( $file_return['upload_error_handler'] ) ) {
		return array('error' => esc_html__('Görsel yüklenemedi.', 'kanews'));
	} else {
		$filename = $file_return['file'];
		$attachment = array(
			'post_mime_type' => $file_return['type'],
			'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
			'post_content' => '',
			'post_status' => 'inherit',
			'guid' => $file_return['url']
		);
		$attachment_id = wp_insert_attachment( $attachment, $file_return['file'] );
		require_once(ABSPATH . 'wp-admin/includes/image.php');
		$attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
		wp_update_attachment_metadata( $attachment_id, $attachment_data );
		if( 0 < intval( $attachment_id ) ) {
			return $attachment_id;
		}
	}
	return array('error' => esc_html__('Görsel yüklenemedi.', 'kanews'));
}
function kan_filename($dir, $name, $ext){
	return round(microtime(true)).mt_rand().$ext;
}


/*-----------------------------------------------------------------------------------*/
# Add Img Alt Tag
/*-----------------------------------------------------------------------------------*/
function kanews_img_alt( $attr, $attachment = null ) {
	if (empty($attr['alt'])) {
		$img_title = trim( strip_tags( $attachment->post_title ) );
		$attr['alt'] = $img_title;
	}
	return $attr;
}
add_filter( 'wp_get_attachment_image_attributes','kanews_img_alt', 10, 2 );

/*-----------------------------------------------------------------------------------*/
# Get Local File
/*-----------------------------------------------------------------------------------*/
function get_local_file_contents( $file_path ) {
	ob_start();
	include $file_path;
	$contents = ob_get_clean();

	return $contents;
}

/*-----------------------------------------------------------------------------------*/
# Wp Categories
/*-----------------------------------------------------------------------------------*/
add_filter( 'wp_list_categories', 'custom_list_categories', 999, 2 );
function custom_list_categories( $output, $args ){
    $terms = get_categories( $args );
    $result = $output;
    if( $terms ):
        ob_start(); ?>
				<div>
            <?php 
            foreach( $terms as $term ):
                $term_meta = get_term_meta( $term->term_id, '_category_color', true); ?>
                <li class="cat-item cat-<?php echo $term->term_id; ?>">
									<div class="cat-item-bg" style="background-color: #<?php echo $term_meta; ?>"></div>
                    <a href="<?php echo Kanews\Helper_Wp::get_term_link( $term, 'kategori' ); ?>"><?php echo $term->name; ?></a>
                </li>
                 <?php
            endforeach; ?>
					</div>
        <?php 
        $result = ob_get_clean();
    endif;
    return $result;
}

/**
 * Custom Quries
 */
if( ! function_exists( 'kan_query' ) ) {
	function kan_query( $widget_query = array() ){

		$args = array(
			'post_status'         => array( 'publish' ),
			'posts_per_page'      => isset($widget_query['number']) ? $widget_query['number'] : 5,
			'ignore_sticky_posts' => isset($widget_query['sticky']) ? $widget_query['sticky'] : true,
		);

		// Category
		if(is_category()) {
			if( ! empty($widget_query['id']) && $widget_query['id'] != 'all' ) 
			$args['cat'] = $widget_query['id'];
			elseif( get_query_var( 'cat' ) )
			$args['cat'] = get_query_var( 'cat' );
		} else {
			if( ! empty( $widget_query['id'] ) && $widget_query['id'] != 'all'  )
			$args['cat'] = $widget_query['id'];
		}

		// Sortby
		if( ! empty( $widget_query['sortby'] ) ){
			if( $widget_query['sortby'] == 'post-viewed' ){ 
				if( kanews_get_option( 'post-views' ) ) {
					if(kanews_get_option('post-views-source') == 'post-views-counter' && function_exists("pvc_get_post_views")) {
						$args['orderby']  = 'post_views';
						$args['suppress_filters'] = false;
					} else {
						$args['orderby']  = 'meta_value_num';
						$args['meta_key'] = 'post_views_count';
					}
				} else {
					$args['orderby']  = 'comment_count';
				}
			}elseif( $widget_query['sortby'] == 'modified' || $widget_query['sortby'] == 'post-modified'){ 
				$args['orderby']  = 'modified';
			}elseif( $widget_query['sortby'] == 'random'){ 
				$args['orderby']  = 'rand';
			}elseif($widget_query['sortby'] == 'commented') { 
				$args['orderby']  = 'comment_count';
			}elseif($widget_query['sortby'] == 'recent-s') { 
				$args['orderby']  = 'menu_order';
			}
		}

		// Post Format
		if( ! empty( $widget_query['format'] ) && $widget_query['format'] != '0' ){
			$args['tax_query'] = array(
				array(
					'taxonomy' => 'post_format',
					'field'    => 'slug',
					'terms'    => 'post-format-'.$widget_query['format'],
					'operator' => 'IN'
				)
			);
		}

		// Exclude Posts
		if( ! empty( $GLOBALS['kan_do_not_duplicate'] ) && is_array( $GLOBALS['kan_do_not_duplicate'] ) ) {
			$args['post__not_in'] = $GLOBALS['kan_do_not_duplicate'];
		} elseif( ! empty( $widget_query['exclude'] ) ) {
			$args['post__not_in'] = $widget_query['exclude'];
		}

		// ID
		if( ! empty( $widget_query['post_in'] ) ){
			$args['post__in'] = $widget_query['post_in'];
		}

		if( ! empty( $widget_query['category__not_in'] ) ){
			$args['category__not_in'] = $widget_query['category__not_in'];
		}

		// Search
		if( ! empty( $widget_query['search'] ) ){
			$args['s'] = $widget_query['search'];
		}

		// Tags with slug
		if( ! empty( $widget_query['tags'] ) ){
			$args['tag'] = $widget_query['tags'];
		}

		// Tags with id
		if( ! empty( $widget_query['tags_ids'] ) ){
			$args['tag__in'] = $widget_query['tags_ids'];
		}
		
		// Tags with id
		if( ! empty( $widget_query['cats'] ) ){
			$args['category__in'] = $widget_query['cats'];
		}

		// Offset
		if( ! empty( $widget_query['offset'] ) ){
			$args['offset'] = $widget_query['offset'];
		}

		// Post ID
		if( ! empty( $widget_query['pids'] ) ){
			$args['post__in'] = is_array($widget_query['pids']) ? $widget_query['pids'] : explode(',', $widget_query['pids']);
			unset($args['cat']);
		}

		// Author ID
		if( ! empty( $widget_query['author'] ) ){
			$args['author'] = $widget_query['author'];
		}

		// Manset
		if( ! empty( $widget_query['manset'] ) ){
			$args['tax_query'] = array(
				array(
				'taxonomy' => 'manset',
				'field' => 'term_id',
				'terms' => $widget_query['manset'],
				)
			);
		}

		// Custom Post Type
		if( ! empty( $widget_query['post_type'] ) ){
			$args['post_type'] = $widget_query['post_type'];

			if( is_array($args['post_type']) && in_array('manset', $args['post_type']) ) {
				if( $widget_query['tags'] != '' && $widget_query['id'] != '' ) {
					$args['tax_query'] = array(
						'relation' => 'OR',
						array(
							'taxonomy' => 'manset-cat',
							'field'    => 'term_id',
							'terms'    => $widget_query['manset_cat'],
							'operator' => 'IN',
						),
						array(
								'relation' => 'AND',
								array(
										'taxonomy' => 'category',
										'field'    => 'term_id',
										'terms'    => isset($args['cat'])  ? $args['cat']  : '',
										'operator' => 'IN',
								),
								array(
										'taxonomy' => 'post_tag',
										'field'    => 'slug',
										'terms'    => isset($args['tag'])  ? $args['tag']  : '',
										'operator' => 'IN',
								),
						),
					);
					unset($args['cat']);
					unset($args['tag']);
				} elseif( $widget_query['tags'] != '' ) {
					$args['tax_query'] = array(
						'relation' => 'OR',
						array(
							'taxonomy' => 'manset-cat',
							'field'    => 'term_id',
							'terms'    => $widget_query['manset_cat'],
							'operator' => 'IN',
						),
						array(
								'relation' => 'AND',
								array(
										'taxonomy' => 'post_tag',
										'field'    => 'slug',
										'terms'    => isset($args['tag'])  ? $args['tag']  : '',
										'operator' => 'IN',
								),
						),
					);
					unset($args['cat']);
					// unset($args['tag']);
				} elseif( $widget_query['id'] != '' ) {
					$args['tax_query'] = array(
						'relation' => 'OR',
						array(
							'taxonomy' => 'manset-cat',
							'field'    => 'term_id',
							'terms'    => $widget_query['manset_cat'],
							'operator' => 'IN',
						),
						array(
								'relation' => 'AND',
								array(
										'taxonomy' => 'category',
										'field'    => 'term_id',
										'terms'    => isset($args['cat'])  ? $args['cat']  : '',
										'operator' => 'IN',
								)
						),
					);
					unset($args['cat']);
					// unset($args['tag']);
				} elseif( $widget_query['manset_cat'] != '' ) {
					$args['tax_query'] = array(
						'relation' => 'OR',
						array(
							'taxonomy' => 'manset-cat',
							'field'    => 'term_id',
							'terms'    => $widget_query['manset_cat'],
							'operator' => 'IN',
						),
						array(
							'relation' => 'AND',
							array(
								'taxonomy' => 'category',
								'field'    => 'term_id',
								'terms'    => isset($args['cat'])  ? $args['cat']  : '',
								'operator' => 'EXISTS',
							)
						),
					);
				}
			}elseif( $widget_query['post_type'] == 'ilan' ) {
				$args['tax_query'] = array();
				$args['meta_query'] = array();

				if( $widget_query['icat'] > 1 ) {
					if( $widget_query['itags'] > 1 )
					$args['tax_query']['relation'] = 'AND';
					$args['tax_query'][] = array(
						'taxonomy' => 'ilan-kategori',
						'field'    => 'term_id',
						'operator' => 'AND',
						'terms'    => $widget_query['icat'],
					);
				}
				if( $widget_query['itags'] > 1 ) {
					$args['tax_query'][] = array(
						'taxonomy' => 'ilan-etiket',
						'field'    => 'term_id',
						'operator' => 'AND',
						'terms'    => $widget_query['itags'],
					);
				}

				if( $widget_query['city_query'] != '' ) {
					if( $widget_query['town_query'] != '' )
					$args['tax_query']['relation'] = 'AND';
					$args['tax_query'][] = array(
						'key'   => 'ilan_city',
						'compare' => '=',
						'value' => $widget_query['city_query'],
					);
				}
				if( $widget_query['town_query'] != '' ) {
					$args['tax_query'][] = array(
						'key'   => 'ilan-etiket',
						'compare' => '=',
						'value' => $widget_query['town_query'],
					);
				}
			}
		}

		// Date Query
		if( ! empty($widget_query['date_query']) ) {
			$args['date_query'] = $widget_query['date_query'];
		}

		// Custom Pagi
		if( ! empty($widget_query['custom_pagi']) ) {
			$args['paged'] = $widget_query['custom_pagi'];
		}

		// Range
		if( ! empty($widget_query['range']) ) {
			if($widget_query['range'] == 'year') {
				$args['date_query'] = array(
					array(
						'after' => '1 year ago',
					)
				);
			}
			elseif($widget_query['range'] == 'month') {
				$args['date_query'] = array(
					array(
						'after' => '1 month ago',
					)
				);
			}
			elseif($widget_query['range'] == 'week') {
				$args['date_query'] = array(
					array(
						'after' => '1 week ago',
					)
				);
			}
			elseif($widget_query['range'] == 'day') {
				$args['date_query'] = array(
					array(
						'after' => '1 day ago',
					)
				);
			}
		}

		// Pagination
		if ( ! empty( $widget_query['pagi'] ) ){
			if( ! empty( $widget_query['target_page'] ) ){
				$paged = intval( $widget_query['target_page'] );
			} else {
				$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
			}
			$args['paged'] = $paged;
		}
		else {
			$args['no_found_rows'] = true ;
		}

		// Offset
		if( ! empty( $widget_query['offset'] ) ){

			if( ! empty( $widget_query['pagi'] ) && ! empty( $paged ) ){
				$args['offset'] = $widget_query['offset'] + ( ($paged-1) * $args['posts_per_page'] );
			}

			else{
				$args['offset'] = $widget_query['offset'];
			}
		}
		
		$widget_query = kanews_run_the_query( $args );
		return $widget_query;
	}
}

/**
 * Run the Quries and Cache them
 */
 function kanews_run_the_query( $args = array() ){

	// Prepare the cache key
	$cache_key = http_build_query( $args );

	// Check for the custom key in the theme group
	$custom_query = wp_cache_get( $cache_key, 'kanews_theme' );

	// If nothing is found, build the object.
	if ( false === $custom_query ) {
		$custom_query = new WP_Query( $args );

		if ( ! is_wp_error( $custom_query ) && $custom_query->have_posts() ) {
			wp_cache_set( $cache_key, $custom_query, 'kanews_theme' );
		}
	}

	return $custom_query;
}

/*-----------------------------------------------------------------------------------*/
# Mobile Detect
/*-----------------------------------------------------------------------------------*/
function kan_is_mobile(){

	if ( ! wp_is_mobile() ) {
		return false;
	}

	if( isset( $GLOBALS['kan_is_mobile'] ) ){
		$is_mobile = $GLOBALS['kan_is_mobile'];
	}
	else{
		

		require_once ( KAN_TEMPLATE_PATH . '/inc/Mobile_Detect/Mobile_Detect.php');
		

		$mobile_detect = new Mobile_Detect2();

		if ( $mobile_detect->isTablet() ){
			$is_mobile = false;
		}
		else{
			$is_mobile = $mobile_detect->isMobile();
		}

		$GLOBALS['kan_is_mobile'] = $is_mobile;
	}

	return $is_mobile;
}

/*-----------------------------------------------------------------------------------*/
# Recaptcha
/*-----------------------------------------------------------------------------------*/
function kanews_get_recaptcha($what){
	$opt = get_option( 'gglcptch_options' );
	if (isset($opt[$what]) && $opt[$what] == 1 && $opt['keys_verified'] == 1 ) {
		$shortcode = do_shortcode('[bws_google_captcha]');
		if ($shortcode != '[bws_google_captcha]') {
			return '<div class="col-12">'.$shortcode.'</div>';
		}
	}

	if( function_exists('cfturnstile_field_show') && get_option('cfturnstile_login') ) {
		if(empty(get_option('cfturnstile_tested')) || get_option('cfturnstile_tested') == 'yes') {
			if(isset($_SESSION['cfturnstile_login_checked'])) { unset($_SESSION['cfturnstile_login_checked']); }

			ob_start();
					cfturnstile_field_show('#wp-submit', 'turnstileWPCallback', 'wordpress-login', '-' . wp_rand());
					$get_captcha = ob_get_clean();
					return $get_captcha;
		}
	}
}

/*-----------------------------------------------------------------------------------*/
# Kanews Icons
/*-----------------------------------------------------------------------------------*/
if( ! function_exists( 'kanews_icons' ) ) {

  function kanews_icons( $icons ) {
  
    $icons[]  = array(
      'title' => 'Kanews Icons',
      'icons' => array(
        'icon-search',
        'icon-envelope',
        'icon-user',
        'icon-home',
        'icon-add',
        'icon-gallery',
        'icon-exchange',
        'icon-edit',
        'icon-local',
        'icon-location',
        'icon-pin',
        'icon-call',
        'icon-comment',
        'icon-vpn_key',
        'icon-menu',
        'icon-menu2',
        'icon-live',
        'icon-star',
        'icon-star-o',
        'icon-star-half',
        'icon-bookmark',
        'icon-bookmark-o',
        'icon-done',
        'icon-settings',
        'icon-like',
        'icon-like-o',
        'icon-logout',
        'icon-standings',
        'icon-article',
        'icon-covid',
        'icon-caret',
        'icon-arrow-long',
        'icon-arrow',
        'icon-video',
        'icon-mic',
        'icon-notifications',
        'icon-view',
        'icon-grid',
        'icon-bolt',
        'icon-tumblr',
        'icon-close',
        // 'icon-gold',
        'icon-unlock',
        'icon-moon-fill',
        'icon-weather',
        'icon-quotes-left',
        'icon-sun',
        'icon-facebook',
        'icon-instagram',
        'icon-whatsapp',
        'icon-twitter',
        'icon-youtube',
        'icon-linkedin',
        'icon-pinterest',
        'icon-traffic',
        'icon-share',
        'icon-bitcoin',
        'icon-money',
        'icon-newspaper',
        'icon-telegram',
        'icon-local_pharmacy',
        'icon-type',
        'icon-subscriptions',
				'icon-tiktok',
      )
    );
  
    $icons = array_reverse( $icons );

    return $icons;
    
  }
  add_filter( 'csf_field_icon_add_icons', 'kanews_icons' );
}


/*-----------------------------------------------------------------------------------*/
# Email Template
/*-----------------------------------------------------------------------------------*/
function kanews_send_mail($to, $email_title, $content = array()) {
	
	// if ( ! ( $phpmailer instanceof PHPMailer\PHPMailer\PHPMailer ) )
	// return;

	$content = $content;
  
	ob_start();
	include(get_template_directory() . '/template-parts/email.php');
	$email_content = ob_get_contents();
	ob_end_clean();
	
	if(is_array($to) && !empty($to)) {
		$headers = array('Content-Type: text/html; charset=UTF-8');
		$headers[] = 'BCC: '. implode(",", $to) . "\r\n";
		wp_mail($to, $email_title, $email_content, $headers);
	}

}

function kan_send_mail($to, $email_title, $content = array(), $action = '', $user_id = '') {
	
	// if( ! class_exists('PHPMailer') )
	// 	return;

	// if ( ! ( $phpmailer instanceof PHPMailer\PHPMailer\PHPMailer ) )
	// 	return;

	$content = $content;
	
	if($action != 'activation' && ! kanews_user_status($user_id)) {
		return false;
	}
  
	ob_start();
	include(get_template_directory() . '/template-parts/email.php');
	$email_content = ob_get_contents();
	ob_end_clean();
	
	$headers = array('Content-Type: text/html; charset=UTF-8');
	wp_mail($to, $email_title, $email_content, $headers);

}

/*-----------------------------------------------------------------------------------*/
# CSS Minifier
/*-----------------------------------------------------------------------------------*/
function kan_minify_css($css){
	$css = preg_replace('/\/\*((?!\*\/).)*\*\//', '', $css); // negative look ahead
	$css = preg_replace('/\s{2,}/', ' ', $css);
	$css = preg_replace('/\s*([:;{}])\s*/', '$1', $css);
	$css = preg_replace('/;}/', '}', $css);
	return $css;
}
/*-----------------------------------------------------------------------------------*/
# Js Minifier
/*-----------------------------------------------------------------------------------*/
function kan_minify_js($js) {
if(empty($js))
return;

// Remove a tab
$js = str_replace("\t", " ", $js);

// Remove comments with "// "
$js = preg_replace('/\n(\s+)?\/\/[^\n]*/', "", $js);	

// Remove other comments
$js = preg_replace("!/\*[^*]*\*+([^/][^*]*\*+)*/!", "", $js);
$js = preg_replace("/\/\*[^\/]*\*\//", "", $js);
$js = preg_replace("/\/\*\*((\r\n|\n) \*[^\n]*)+(\r\n|\n) \*\//", "", $js);		

// Remove a carriage return
$js = str_replace("\r", "", $js);

// Remove whitespaces
$js = preg_replace("/\s+\n/", "\n", $js);	
$js = preg_replace("/\n\s+/", "\n ", $js);
$js = preg_replace("/ +/", " ", $js);

return $js;
}

/*-----------------------------------------------------------------------------------*/
# Time
/*-----------------------------------------------------------------------------------*/
function secondsToTime($seconds) {
	$dtF = new \DateTime('@0');
	$dtT = new \DateTime("@$seconds");
	return $dtF->diff($dtT)->format('%a gün, %h saat, %i dk ve %s sn');
}


/*-----------------------------------------------------------------------------------*/
# Prayer Times
/*-----------------------------------------------------------------------------------*/
function kanews_prayer_times_api($country, $region, $city, $date, $days) {

	$query = array('timezoneOffset' => 180, 'country' => $country, 'region' => $region, 'city' => $city, 'date' => $date, 'days' => $days);
	// $api_url = add_query_arg( $query, 'https://prayer-api-gamma.vercel.app/api/timesFromPlace' );
	$api_url = add_query_arg( $query, KAN_TEMPLATE_URL.'/inc/api/prayer/api.php' );

	// return print_r($api_url);
	$api = wp_remote_get( $api_url, array( 'timeout' => 10 ) );

	if( is_wp_error( $api ) )
	return array( 'error' => $api->get_error_message() );
	
	$prayer_data = json_decode( $api['body'], true );

	return $prayer_data;

}

/*-----------------------------------------------------------------------------------*/
# Nöbetçi Eczaneler
/*-----------------------------------------------------------------------------------*/
function kanews_eczane_times_api($region, $city) {

	$query = array( 'region' => $region, 'city' => $city);
	$api_url = add_query_arg( $query, KAN_TEMPLATE_URL.'/inc/api/eczane/api.php' );

	$api = wp_remote_get( $api_url, array( 'timeout' => 10, 'sslverify' => false ) );

	if( is_wp_error( $api ) )
	return array( 'error' => $api->get_error_message() );
	
	$eczane_data = json_decode( $api['body'], true );

	// Check if the API returned an error
	if (isset($eczane_data['error']) && $eczane_data['error'] === true) {
		return array('data' => array());
	}

	// If city (district) is specified and different from region, filter the results
	if (!empty($city) && $city !== $region && isset($eczane_data['data'][0]) && is_array($eczane_data['data'][0])) {
		$filtered_data = array();
		foreach ($eczane_data['data'][0] as $pharmacy) {
			if (isset($pharmacy['ilce']) && strtolower(kanews_seflink($pharmacy['ilce'])) === strtolower(kanews_seflink($city))) {
				$filtered_data[] = $pharmacy;
			}
		}
		$eczane_data['data'][0] = $filtered_data;
	}

	return $eczane_data;
}


/*-----------------------------------------------------------------------------------*/
# Live Score Data
/*-----------------------------------------------------------------------------------*//*-----------------------------------------------------------------------------------*/
# Live Score Data
/*-----------------------------------------------------------------------------------*/
function kanews_live_score_filter_by_league_name($data, $league) {
	$filterBy = $league; 
  $new = array_filter($data, function ($var) use ($filterBy) {
      return ($var['league'] == $filterBy);
  });
	return $new;
}

function kanews_correct_league_title2($samp) {

	switch($samp) {
		case 'sampiyonlar-ligi':
			return esc_html__( 'Şampiyonlar Ligi', 'kanews' );
		case 'avrupa-ligi':
			return esc_html__( 'Avrupa Ligi', 'kanews' );
		case 'super-lig':
			return esc_html__( 'Süper Lig', 'kanews' );
		case 'tff-1-lig':
			return esc_html__( 'TFF 1. Lig', 'kanews' );		
		case 'tff-2-lig':
			return esc_html__( 'TFF 2. Lig', 'kanews' );
		case 'premier-lig':
			return esc_html__( 'Premier Lig', 'kanews' );
		case 'bundesliga':
			return esc_html__( 'Bundesliga', 'kanews' );
		case 'fransa-ligi':
			return esc_html__( 'Ligue 1', 'kanews' );
		case 'serie-a':
			return esc_html__( 'Serie A', 'kanews' );
		case 'la-liga':
			return esc_html__( 'La Liga', 'kanews' );
		case 'hollanda-ligi':
			return esc_html__( 'Eredivisie', 'kanews' );
		case 'championship':
			return esc_html__( 'İngiltere Championship', 'kanews' );
		case 'dunya-kupasi':
			return esc_html__( 'Dünya Kupası', 'kanews' );
		case 'dunya-kupasi-elemeleri':
			return esc_html__( 'Dünya Kupası Elemeleri', 'kanews' );
		case 'avrupa-sampiyonasi':
			return esc_html__( 'Avrupa Şampiyonası', 'kanews' );
		case 'avrupa-sampiyonası-elemeleri':
			return esc_html__( 'Avrupa Şampiyonası Elemeleri', 'kanews' );
		case 'uluslar-ligi':
			return esc_html__( 'UEFA Uluslar Ligi', 'kanews' );
		case 'turkiye-kupasi':
			return esc_html__( 'Türkiye Kupası', 'kanews' );
		case 'super-kupa':
			return esc_html__( 'Süper Kupa', 'kanews' );
		case 'milli-takim-hazirlik':
			return esc_html__( 'Ülke Hazırlık Maçları', 'kanews' );
		case 'konferans-ligi':
			return esc_html__( 'Avrupa Konferans Ligi', 'kanews' );
		case 'hazirlik':
			return esc_html__( 'Hazırlık Maçları', 'kanews' );
		case 'all':
			return esc_html__( 'Tüm Maçlar', 'kanews' );
		default:
			return $samp;
	}
}

function kanews_correct_league_title($samp) {

	switch($samp) {
		case '4oogyu6o156iphvdvphwpck10':
			return esc_html__( 'Şampiyonlar Ligi', 'kanews' );
		case '4c1nfi2j1m731hcay25fcgndq':
			return esc_html__( 'Avrupa Ligi', 'kanews' );
		case '482ofyysbdbeoxauk19yg7tdt':
			return esc_html__( 'Süper Lig', 'kanews' );
		case '2o9svokc5s7diish3ycrzk7jm':
			return esc_html__( 'TFF 1. Lig', 'kanews' );		
		case '2nttcoriwf5co73vmz1vr8frm':
			return esc_html__( 'TFF 2. Lig', 'kanews' );
		case '2kwbbcootiqqgmrzs6o5inle5':
			return esc_html__( 'Premier Lig', 'kanews' );
		case '6by3h89i2eykc341oz7lv1ddd':
			return esc_html__( 'Bundesliga', 'kanews' );
		case 'dm5ka0os1e3dxcp3vh05kmp33':
			return esc_html__( 'Ligue 1', 'kanews' );
		case '1r097lpxe0xn03ihb7wi98kao':
			return esc_html__( 'Serie A', 'kanews' );
		case '34pl8szyvrbwcmfkuocjm3r6t':
			return esc_html__( 'La Liga', 'kanews' );
		case 'akmkihra9ruad09ljapsm84b3':
			return esc_html__( 'Eredivisie', 'kanews' );
		case '7ntvbsyq31jnzoqoa8850b9b8':
			return esc_html__( 'İngiltere Championship', 'kanews' );
		case '70excpe1synn9kadnbppahdn7':
			return esc_html__( 'Dünya Kupası', 'kanews' );
		case '39q1hq42hxjfylxb7xpe9bvf9':
			return esc_html__( 'Dünya Kupası Elemeleri', 'kanews' );
		case '8tddm56zbasf57jkkay4kbf11':
			return esc_html__( 'Avrupa Şampiyonası', 'kanews' );
		case 'gfskxsdituog2kqp9yiu7bzi':
			return esc_html__( 'Avrupa Şampiyonası Elemeleri', 'kanews' );
		case '595nsvo7ykvoe690b1e4u5n56':
			return esc_html__( 'UEFA Uluslar Ligi', 'kanews' );
		case '7af85xa75vozt2l4hzi6ryts7':
			return esc_html__( 'Türkiye Kupası', 'kanews' );
		case 'a0f4gtru0oyxmpvty4thc5qkc':
			return esc_html__( 'Süper Kupa', 'kanews' );
		case 'cesdwwnxbc5fmajgroc0hqzy2':
			return esc_html__( 'Ülke Hazırlık Maçları', 'kanews' );
		case 'c7b8o53flg36wbuevfzy3lb10':
			return esc_html__( 'Avrupa Konferans Ligi', 'kanews' );
		case '4nidzmunvpvxk1ir9b6m8mpay':
			return esc_html__( 'Hazırlık Maçları', 'kanews' );
		case 'all':
			return esc_html__( 'Tüm Maçlar', 'kanews' );
		default:
			return $samp;
	}
}
function kanews_league_logo($samp) {
	
	$array = [
		'sampiyonlar-ligi',
		'avrupa-ligi',
		'super-lig',
		'premier-lig',
		'bundesliga',
		'fransa-ligi',
		'serie-a',
		'la-liga',
		// 'hollanda-ligi',
		// 'championship',
		// 'dunya-kupasi',
		'konferans-ligi',
		'uefa-avrupa-ligi'
		
	];
	if( ! in_array(kanews_seflink($samp), $array) )
	return KAN_TEMPLATE_URL.'/assets/img/static/leagues/default-logo.webp';
	else
	return KAN_TEMPLATE_URL.'/assets/img/static/leagues/'.kanews_seflink($samp).'.png';
	
}

function kanews_live_score_data($date, $leagues) {
	
	$transient_name = 'kanews-gcx21-cache-' . md5( serialize( array( $date, $leagues ) ) );

	if ( false === ( $cons_matches = get_transient( $transient_name ) ) ){
		$data = kanews_connect_api("https://www.mackolik.com/perform/p0/ajax/components/competition/livescores/json?sports[]=Soccer&matchDate=" .$date);
		
		$matches = json_decode($data, true);
		
		if(isset($matches['data']['matches'])) {
		
			$cons_matches = array();
			foreach( $matches['data']['matches'] as $match ) {
				$timestamp =  $match['mstUtc'] / 1000; // Milisaniyeyi saniyeye çeviriyoruz

				$timezone = new DateTimeZone('GMT+3');
				$datetime = new DateTime("@$timestamp");
				$datetime->setTimezone($timezone);
				$formattedDate = $datetime->format('H:i');
				$cons_matches[] = [
					'home'       => $match['homeTeam']['name'],
					'away'       => $match['awayTeam']['name'],
					'home-score' => $match['score']['home'],
					'away-score' => $match['score']['away'],
					'home-logo'  => 'https://secure.cache.images.core.optasports.com/soccer/teams/30x30/uuid_'.$match['homeTeam']['id'].'.png?v=1.135.1&gis=mk',
					'away-logo'  => 'https://secure.cache.images.core.optasports.com/soccer/teams/30x30/uuid_'.$match['awayTeam']['id'].'.png?v=1.135.1&gis=mk',
					'min'        => $match['statusBoxContent'],
					'start'      => $formattedDate,
					'league'     => $match['competitionId'],
					'type'       => 1,
					'home-red-cards' => isset($match['redCards']['home']) ? $match['redCards']['home'] : 0,
					'away-red-cards' => isset($match['redCards']['away']) ? $match['redCards']['away'] : 0,
					'ht-home-score' => isset($match['score']['ht']['home']) ? $match['score']['ht']['home'] : '',
					'ht-away-score' => isset($match['score']['ht']['away']) ? $match['score']['ht']['away'] : '',
					'pen-home-score' => isset($match['score']['pen']['home']) ? $match['score']['pen']['home'] : '',
					'pen-away-score' => isset($match['score']['pen']['away']) ? $match['score']['pen']['away'] : '',
					'agg-home-score' => isset($match['score']['agg']['home']) ? $match['score']['agg']['home'] : '',
					'agg-away-score' => isset($match['score']['agg']['away']) ? $match['score']['agg']['away'] : '',
				
				];
			}
			
			
		} 

		// if($date == date('d/m/Y') || $date == date('d/m/Y', strtotime("+1 day")))
		// $transient_time = 15 * MINUTE_IN_SECONDS;
		// else
		// $transient_time = 24 * HOUR_IN_SECONDS;

		$transient_time = 10 * MINUTE_IN_SECONDS;

		$cons_matches = json_encode($cons_matches, true);
		set_transient( $transient_name, $cons_matches, $transient_time);
	}

	return $cons_matches;
}

/*-----------------------------------------------------------------------------------*/
# Number Format
/*-----------------------------------------------------------------------------------*/
function number_format_short( $n, $precision = 1 ) {
	if ($n < 900) {
		// 0 - 900
		$n_format = number_format($n, $precision);
		$suffix = '';
	} else if ($n < 900000) {
		// 0.9k-850k
		$n_format = number_format($n / 1000, $precision);
		$suffix = 'K';
	} else if ($n < 900000000) {
		// 0.9m-850m
		$n_format = number_format($n / 1000000, $precision);
		$suffix = 'M';
	} else if ($n < 900000000000) {
		// 0.9b-850b
		$n_format = number_format($n / 1000000000, $precision);
		$suffix = 'B';
	} else {
		// 0.9t+
		$n_format = number_format($n / 1000000000000, $precision);
		$suffix = 'T';
	}

  // Remove unecessary zeroes after decimal. "1.0" -> "1"; "1.00" -> "1"
  // Intentionally does not affect partials, eg "1.50" -> "1.50"
	if ( $precision > 0 ) {
		$dotzero = '.' . str_repeat( '0', $precision );
		$n_format = str_replace( $dotzero, '', $n_format );
	}

	return $n_format . $suffix;
}

/*-----------------------------------------------------------------------------------*/
# Currency Format
/*-----------------------------------------------------------------------------------*/
function currency_format_number($n) {
	$formatted = $n;
	if ($n <= -1) {
			$formatted = number_format($n, 2, ',', '.');
	} else if ($n < 0.50) {
			$formatted = number_format($n, 6, ',', '.');
	} else {
			$formatted = number_format($n, 2, ',', '.');
	}
	return $formatted;
}

/*-----------------------------------------------------------------------------------*/
# Category Dropdown
/*-----------------------------------------------------------------------------------*/
add_filter( 'wp_dropdown_cats', 'wp_dropdown_cats_multiple', 10, 2 );
function wp_dropdown_cats_multiple( $output, $r ) {

    if( isset( $r['multiple'] ) && $r['multiple'] ) {

        $output = preg_replace( '/^<select/i', '<select multiple', $output );

        $output = str_replace( "name='{$r['name']}'", "name='{$r['name']}[]'", $output );

        foreach ( array_map( 'trim', explode( ",", $r['selected'] ) ) as $value )
            $output = str_replace( "value=\"{$value}\"", "value=\"{$value}\" selected", $output );

    }

    return $output;
}

/*-----------------------------------------------------------------------------------*/
# Replace Class
/*-----------------------------------------------------------------------------------*/
function kan_replace_class( $html, $new_class ) {

	$pattern = '/class="([^"]*)"/';

	// Class attribute set.
	if ( preg_match( $pattern, $html, $matches ) ) {
		$predefined_classes = explode( ' ', $matches[1] );
		if ( ! in_array( $new_class, $predefined_classes, true ) ) {
			$predefined_classes[] = $new_class;
			$html                 = str_replace(
				$matches[0],
				sprintf( 'class="%s"', implode( ' ', $predefined_classes ) ),
				$html
			);
		}
	} else {
		$html = preg_replace( '/(\<.+\s)/', sprintf( '$1class="%s" ', $new_class ), $html );
	}
	
	return $html;
}

/*-----------------------------------------------------------------------------------*/
#  İlan Sistemi
/*-----------------------------------------------------------------------------------*/
add_action( 'admin_init', 'posts_order_wpse_91866' );
function posts_order_wpse_91866() 
{
  add_post_type_support( 'ilan', 'page-attributes' );
}
add_action( 'pre_get_posts', 'custom_pre_get_posts', 20, 1);
function custom_pre_get_posts($wp_query) {

	if(isset($_GET['sort']) && ( $_GET['sort'] == 'da' || $_GET['sort'] == 'dd' ) && is_archive('ilan')) {
		$wp_query->set( 'orderby', 'date' );
		if( $_GET['sort'] == 'da' )
		$wp_query->set( 'order', 'ASC' );
		else
		$wp_query->set( 'order', 'DESC' );
	}
}

/*-----------------------------------------------------------------------------------*/
#  Crypto Data // cryptocompare
/*-----------------------------------------------------------------------------------*/
function kanews_crypto_data($vs_currency, $max = 100, $page = 1) {
	$data = array();
	$transient_time = 30 * MINUTE_IN_SECONDS;
	$transient_name = 'kanews-cr2-' . md5( serialize( array( $vs_currency, $page, $max ) ) );

	if($vs_currency == 'usdt')
	$vs_currency = 'usd';

	if ( false === ( $data = get_transient( $transient_name ) ) ){

		$apiUrl = "https://min-api.cryptocompare.com/data/top/mktcapfull?limit=$max&tsym=$vs_currency";
		$response = wp_remote_get($apiUrl);
		$data = wp_remote_retrieve_body( $response );		

		if(!is_wp_error( $response ) && json_decode($data)->Message == 'Success' ) {
			$vs_currency = strtoupper($vs_currency);
			$data = json_decode($data, true);
			$counter = 0;
			$beauty_data = array();
			foreach($data['Data'] as $coin) {
				if( isset($coin['RAW'][$vs_currency]) ) {
					$counter++;
					$beauty_data[] = [
						'image' => 'https://www.cryptocompare.com'.$coin['CoinInfo']['ImageUrl'],
						'id' => strtolower($coin['CoinInfo']['FullName']),
						'symbol' => strtolower($coin['CoinInfo']['Name']),
						'name' => $coin['CoinInfo']['FullName'],
						'market_cap_rank' => $counter,
						'market_cap' => $coin['RAW'][$vs_currency]['MKTCAP'],
						'current_price' => $coin['RAW'][$vs_currency]['PRICE'],
						'total_volume' => $coin['RAW'][$vs_currency]['TOTALVOLUME24H'],
						'high_24h' => $coin['RAW'][$vs_currency]['HIGH24HOUR'],
						'low_24h' => $coin['RAW'][$vs_currency]['LOW24HOUR'],
						'price_change_percentage_24h' => $coin['RAW'][$vs_currency]['CHANGEPCT24HOUR'],
						'market_cap_change_percentage_24h' => '0',
						'circulating_supply' => $coin['RAW'][$vs_currency]['CIRCULATINGSUPPLY'],
						'max_supply' => '1',
						'ath' => '1',
						'ath_change_percentage' => '1',
						'ath_date' => '1',
						'max_supply' => '1',
						'atl' => '1',
						'atl_change_percentage' => '1',
						'atl_date' => '1',
						'last_updated' => $coin['RAW'][$vs_currency]['LASTUPDATE'],
					];
				}
			}
			$data = json_encode($beauty_data);
			set_transient( $transient_name, $data, $transient_time);
			
		} else {
			set_transient( $transient_name, $data, get_option('_transient_'.$transient_name));
			return get_option('_transient_'.$transient_name);
		}
		
	}

	return $data;
}

/*-----------------------------------------------------------------------------------*/
#  Crypto Data // coingecko
/*-----------------------------------------------------------------------------------*/
function kanews_crypto_data2($vs_currency, $max = 100, $page = 1) {
	$data = array();
	$transient_time = 30 * MINUTE_IN_SECONDS;
	$transient_name = 'kanews-cr-' . md5( serialize( array( $vs_currency, $page, $max ) ) );

	if($vs_currency == 'usdt')
	$vs_currency = 'usd';

	if ( false === ( $data = get_transient( $transient_name ) ) ){

		$apiUrl = "https://api.coingecko.com/api/v3/coins/markets?vs_currency=$vs_currency&order=market_cap_desc&per_page=$max&page=$page&sparkline=false";
		$response = wp_remote_get($apiUrl);
		$data = wp_remote_retrieve_body( $response );		

		if(!is_wp_error( $response ) && empty(json_decode($data)->status->error_message) ) {
			set_transient( $transient_name, $data, $transient_time);
		} else {
			set_transient( $transient_name, $data, get_option('_transient_'.$transient_name));
			return get_option('_transient_'.$transient_name);
		}
		
	}

	return $data;
}

/*-----------------------------------------------------------------------------------*/
#  Nex to Rgb
/*-----------------------------------------------------------------------------------*/
function hexToRgb($hex, $alpha = false) {
	$hex      = str_replace('#', '', $hex);
	$length   = strlen($hex);
	$rgb['r'] = hexdec($length == 6 ? substr($hex, 0, 2) : ($length == 3 ? str_repeat(substr($hex, 0, 1), 2) : 0));
	$rgb['g'] = hexdec($length == 6 ? substr($hex, 2, 2) : ($length == 3 ? str_repeat(substr($hex, 1, 1), 2) : 0));
	$rgb['b'] = hexdec($length == 6 ? substr($hex, 4, 2) : ($length == 3 ? str_repeat(substr($hex, 2, 1), 2) : 0));
	if ( $alpha ) {
			$rgb['a'] = $alpha;
	}
	return $rgb;
}

/*-----------------------------------------------------------------------------------*/
#  Replace Tukish
/*-----------------------------------------------------------------------------------*/
function replace_tr($text) {
	$text = trim($text);
	$search = array('Ç','ç','Ğ','ğ','ı','İ','Ö','ö','Ş','ş','Ü','ü',' ', 'â');
	$replace = array('c','c','g','g','i','i','o','o','s','s','u','u','-', 'a');
	$new_text = str_replace($search,$replace,$text);
	return $new_text;
} 

/*-----------------------------------------------------------------------------------*/
# Author Archive Base
/*-----------------------------------------------------------------------------------*/
function kanews_2610_author_base_rewrite() {
	global $wp_rewrite;
	$author_base_db = get_option( 'kanews_author_base' );
	if ( !empty( $author_base_db ) ) {
			$wp_rewrite->author_base = $author_base_db;
	}
}

add_action( 'init', 'kanews_2610_author_base_rewrite' );

/*-----------------------------------------------------------------------------------*/
# BİK
/*-----------------------------------------------------------------------------------*/
add_filter('the_content', 'kanews_bik_id');
function kanews_bik_id($content) {
	$ilan_no = get_post_meta( get_the_ID(), 'kanews_bik_id', true);
	if( !empty($ilan_no) ) {
		return $content.'<p>#ilangovtr</p><p>Basın No: '.$ilan_no.'</p>';
	} else {
		return $content;
	}
}


/*-----------------------------------------------------------------------------------*/
# Navbar Extra
/*-----------------------------------------------------------------------------------*/
add_filter('nav_menu_link_attributes', 'kan_nav_menu_link_attributes', 10, 3);
function kan_nav_menu_link_attributes($atts, $item, $args) {
  $args->link_before  = '<span>';
  if( ! in_array( 'menu-item-has-children', $item->classes ))
  $args->link_after   = '</span>';
  else
  $args->link_after   = '</span>';
  return $atts;
}

add_filter('walker_nav_menu_start_el' , 'kan_nav_menu_extra' , 10 , 4);
function kan_nav_menu_extra( $item_output, $item, $depth, $args ) {
  $options = get_post_meta($item->ID, '_kan_menu_options', true );

  // Image
  if(isset($options['image']) && !empty($options['image']['id'])){
		$item_output = str_replace('<span>', wp_get_attachment_image($options['image']['id'], 'thumbnail', '', ["class" => "kanews-nav-img" ]) .'<span>', $item_output);
  } elseif(isset($options['icon']) && !empty($options['icon'])){ 
		$item_output = str_replace('<span>', '<i class="'.esc_attr($options['icon']).'" aria-hidden="true"></i>' .'<span>', $item_output);

	}

  // Badge
  if(isset($options['badge']) && !empty($options['badge'])){
    $badge_color = isset($options['badge_color']) && !empty($options['badge_color']) ? $options['badge_color'] : 'inherit';
    preg_match('~<span>(.*?)</span>~', $item_output, $out);
    $menu_content = isset($out[1]) ? $out[1] : $item_output;
    if($depth){
      $replace = '<span>'.$menu_content.'<div class="kanews-badge" style="--kan-theme-color:'.$badge_color.'">' . $options['badge'] . '</div></span>';
    }else{
      $replace = '<span>'.$menu_content.'</span><div class="kanews-badge" style="--kan-theme-color:'.$badge_color.'">' . $options['badge'] . '</div>';
    }
    $item_output = preg_replace( '~<span>(.*?)</span>~' , $replace, $item_output );
  }


  return $item_output;
}


function get_kanews_api_data($endpoint) {
	// API URL ve key tanımlamaları
	$api_url = 'https://api-three-chi-43.vercel.app/api/' . $endpoint;
	$api_key = 'kanews-theme';

	// API isteği için argümanları hazırla
	$args = array(
			'timeout' => 15,
			'headers' => array(
					'X-API-Key' => $api_key
			)
	);

	// API isteğini yap
	$response = wp_remote_get($api_url, $args);

	// Hata kontrolü
	if (is_wp_error($response)) {
			// error_log('Kanews API Error: ' . $response->get_error_message());
			return array(
					'error' => true,
					'message' => $response->get_error_message()
			);
	}

	// HTTP durum kodunu kontrol et
	$http_code = wp_remote_retrieve_response_code($response);
	if ($http_code !== 200) {
			// error_log('Kanews API HTTP Error: ' . $http_code);
			return array(
					'error' => true,
					'message' => 'API yanıt vermedi (HTTP ' . $http_code . ')'
			);
	}

	// Yanıtı al ve JSON decode et
	$body = wp_remote_retrieve_body($response);
	$data = json_decode($body, true);

	// JSON decode hatası kontrolü
	if (json_last_error() !== JSON_ERROR_NONE) {
			// error_log('Kanews API JSON Error: ' . json_last_error_msg());
			return array(
					'error' => true,
					'message' => 'API yanıtı işlenemedi'
			);
	}

	// Veri kontrolü
	if (isset($data['error']) && $data['error'] === true) {
			// error_log('Kanews API Response Error: ' . $data['message']);
			return array(
					'error' => true,
					'message' => $data['message']
			);
	}

	return $data;
}

// Kullanım örnekleri:


/*-----------------------------------------------------------------------------------*/
# Demo Import Sırasında Mail Gönderimini Engelle
/*-----------------------------------------------------------------------------------*/

/**
 * Demo import sırasında mail gönderimini engeller
 * 
 * @return void
 */
function kanews_disable_emails_during_import() {
	// One Click Demo Import eklentisi aktifse mail gönderimini engelle
	if (defined('DOING_AJAX') && DOING_AJAX && 
			isset($_POST['action']) && 
			(strpos($_POST['action'], 'ocdi_') !== false || strpos($_POST['action'], 'pt-ocdi') !== false)) {
			
			// wp_mail fonksiyonunu geçici olarak devre dışı bırak
			if (!function_exists('wp_mail')) {
					function wp_mail($to, $subject, $message, $headers = '', $attachments = array()) {
							return true; // Mail gönderilmiş gibi göster ama aslında gönderme
					}
			} else {
					// wp_mail fonksiyonu zaten varsa filtreyi kullan
					add_filter('wp_mail', '__return_false');
			}
	}
}
add_action('init', 'kanews_disable_emails_during_import', 1);

/**
* Demo import öncesi mail gönderimini engelle
*/
function kanews_disable_import_emails() {
	// wp_mail fonksiyonunu devre dışı bırak
	add_filter('wp_mail', '__return_false');
	
	// WordPress core notification fonksiyonlarını devre dışı bırak
	add_filter('send_password_change_email', '__return_false');
	add_filter('send_email_change_email', '__return_false');
	add_filter('wp_new_user_notification_email_admin', '__return_false');
	add_filter('wp_new_user_notification_email', '__return_false');
	
	// Comment notifications
	add_filter('notify_moderator', '__return_false');
	add_filter('notify_post_author', '__return_false');
	
	// Update notifications
	add_filter('auto_core_update_send_email', '__return_false');
	add_filter('auto_plugin_update_send_email', '__return_false');
	add_filter('auto_theme_update_send_email', '__return_false');
}

/**
* Demo import sonrası mail gönderimini tekrar aktifleştir
*/
function kanews_enable_import_emails() {
	// wp_mail fonksiyonunu tekrar aktifleştir
	remove_filter('wp_mail', '__return_false');
	
	// WordPress core notification fonksiyonlarını tekrar aktifleştir
	remove_filter('send_password_change_email', '__return_false');
	remove_filter('send_email_change_email', '__return_false');
	remove_filter('wp_new_user_notification_email_admin', '__return_false');
	remove_filter('wp_new_user_notification_email', '__return_false');
	
	// Comment notifications
	remove_filter('notify_moderator', '__return_false');
	remove_filter('notify_post_author', '__return_false');
	
	// Update notifications
	remove_filter('auto_core_update_send_email', '__return_false');
	remove_filter('auto_plugin_update_send_email', '__return_false');
	remove_filter('auto_theme_update_send_email', '__return_false');
}

// Demo import öncesi mail gönderimini engelle
add_action('pt-ocdi/before_content_import', 'kanews_disable_import_emails');
add_action('ocdi/before_content_import', 'kanews_disable_import_emails');

// Demo import sonrası mail gönderimini tekrar aktifleştir
add_action('pt-ocdi/after_import', 'kanews_enable_import_emails');
add_action('ocdi/after_import', 'kanews_enable_import_emails');

/**
* AJAX işlemleri sırasında mail gönderimini engelle
*/
function kanews_maybe_disable_ajax_emails() {
	if (defined('DOING_AJAX') && DOING_AJAX) {
			$action = isset($_POST['action']) ? $_POST['action'] : '';
			$ajax_actions = array(
					'ocdi_import_demo_data',
					'pt-ocdi/import_demo_data',
					'ocdi_import_customizer_data',
					'ocdi_import_widgets',
					'ocdi_after_import_data'
			);
			
			if (in_array($action, $ajax_actions) || strpos($action, 'ocdi') !== false) {
					kanews_disable_import_emails();
			}
	}
}
add_action('wp_ajax_nopriv_ocdi_import_demo_data', 'kanews_maybe_disable_ajax_emails', 1);
add_action('wp_ajax_ocdi_import_demo_data', 'kanews_maybe_disable_ajax_emails', 1);

/**
* Admin menüde, onay bekleyen içerik sayısını tüm post typelar için rozet olarak gösterir
*/
function kanews_admin_menu_pending_counters() {
	if (!is_admin()) {
			return;
	}

	// AJAX sırasında menü etiketleriyle oynamaya gerek yok
	if (defined('DOING_AJAX') && DOING_AJAX) {
			return;
	}

	global $menu, $submenu;

	// show_ui olan tüm post typelar
	$post_type_objects = get_post_types(array('show_ui' => true), 'objects');

	foreach ($post_type_objects as $post_type => $post_type_object) {
			// Kullanıcının düzenleme yetkisi yoksa geç
			if (!isset($post_type_object->cap->edit_posts) || !current_user_can($post_type_object->cap->edit_posts)) {
					continue;
			}

			$counts = wp_count_posts($post_type);
			$pending_count = isset($counts->pending) ? (int) $counts->pending : 0;

			if ($pending_count < 1) {
					continue;
			}

			// İlgili menü slug'ı belirle
			$menu_slug = ($post_type === 'post') ? 'edit.php' : ('edit.php?post_type=' . $post_type);

			// Üst menüdeki etiketi bul ve rozet ekle
			if (is_array($menu)) {
					foreach ($menu as $index => $menu_item) {
							if (!isset($menu_item[2])) {
									continue;
							}
							if ($menu_item[2] === $menu_slug) {
									// Mevcut etiket üzerindeki olası önceki rozetleri temiz tutmak için strip_tags
									$base_label = wp_strip_all_tags($menu_item[0]);
									$menu[$index][0] = $base_label . ' <span class="awaiting-mod count-' . $pending_count . '"><span class="pending-count">' . number_format_i18n($pending_count) . '</span></span>';
									break;
							}
					}
			}

			// Alt menüde (Tüm Yazılar vb.) aynı rozeti ekle (ilgili submenu anahtarına bakar)
			if (isset($submenu[$menu_slug]) && is_array($submenu[$menu_slug])) {
					foreach ($submenu[$menu_slug] as $sindex => $sub_item) {
							// $sub_item[2] alt menü slug'ı; "Tüm" listesi genelde üst slug ile aynıdır
							if (isset($sub_item[2]) && $sub_item[2] === $menu_slug) {
									$base_sub_label = wp_strip_all_tags($sub_item[0]);
									$submenu[$menu_slug][$sindex][0] = $base_sub_label . ' <span class="awaiting-mod count-' . $pending_count . '"><span class="pending-count">' . number_format_i18n($pending_count) . '</span></span>';
									break;
							}
					}
			}
	}
}
add_action('admin_menu', 'kanews_admin_menu_pending_counters', 999);

function kanews_get_emtia_name($code) {
  $names = [
    'GRA' => 'Gram Altın',
    'GUMUS' => 'Gümüş Gram',
    'HAS' => 'Has Altın',
    'ONS' => 'Ons Altın',
    'CEYREKALTIN' => 'Çeyrek Altın',
    'YARIMALTIN' => 'Yarım Altın',
    'TAMALTIN' => 'Tam Altın',
    'CUMHURIYETALTINI' => 'Cumhuriyet Altını',
    'ATAALTIN' => 'Ata Altın',
    '14AYARALTIN' => '14 Ayar Altın',
    '18AYARALTIN' => '18 Ayar Altın',
    'YIA' => '22 Ayar Bilezik',
    'IKIBUCUKALTIN' => 'İkibuçuk Altın',
    'BESLIALTIN' => 'Beşli Altın',
    'GREMSEALTIN' => 'Gremse Altın',
    'RESATALTIN' => 'Reşat Altın',
    'HAMITALTIN' => 'Hamit Altın',
  ];
  return $names[$code] ?? $code;
}

function search_exact_word( $where, $query ) {
	global $wpdb;

	// Arama kelimesi alınır
	$search_term = $query->get('exact_search');

	if ( $search_term ) {
			// SQL injection koruması
			$search_term = esc_sql( $search_term );

			// Kelime sınırları için REGEXP
			// [[:<:]] kelime başı, [[:>:]] kelime sonu
			$where .= " AND (
					{$wpdb->posts}.post_title REGEXP '[[:<:]]{$search_term}[[:>:]]'
					OR {$wpdb->posts}.post_content REGEXP '[[:<:]]{$search_term}[[:>:]]'
			) ";
	}

	return $where;
}

function weplugins_custom_archive_title( $title ) {
	if ( is_category() ) {
			$title = single_cat_title( '', false );
	} elseif ( is_tag() ) {
			$title = single_tag_title( '', false );
	} elseif ( is_author() ) {
			$title = '<span class="vcard">' . get_the_author() . '</span>';
	} elseif ( is_post_type_archive() ) {
			$title = post_type_archive_title( '', false );
	} elseif ( is_tax() ) {
			// Custom taxonomy title logic
	}
	return $title;
}
add_filter( "get_the_archive_title", "weplugins_custom_archive_title" );