<?php 

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

/*-----------------------------------------------------------------------------------*/
# Review Notice
/*-----------------------------------------------------------------------------------*/
	add_action( 'admin_notices', 'kanews_review_admin_notice' );
function kanews_review_admin_notice() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		if ( get_option( 'kanews_review_box_dismissed', false ) ) {
			return;
		}

		$nonce = wp_create_nonce( 'kanews_review_box' );
		?>
		<div class="notice kanews-review-admin-notice" style="padding:0;margin-top:25px;background:transparent;border:none;box-shadow:none;">
			<div class="kanews-card kanews-card--review kanews-review-box" style="margin:0;">
				<button type="button" class="kanews-card__close kanews-review-notice-dismiss" data-nonce="<?php echo esc_attr( $nonce ); ?>" title="<?php esc_attr_e( 'Kapat', 'kanews' ); ?>">
					<span class="dashicons dashicons-dismiss"></span>
				</button>
				<div class="kanews-card__layout">
					<div class="kanews-card__content">
						<div class="kanews-card__intro">
							<div class="kanews-card__icon kanews-card__icon--amber">
								<span class="dashicons dashicons-star-filled"></span>
		</div>
							<div>
								<h2 class="kanews-card__title"><?php esc_html_e( 'Kanews\'i Beğendiniz mi?', 'kanews' ); ?></h2>
								<p class="kanews-card__subtitle">
									<?php esc_html_e( 'Değerlendirmeniz diğer kullanıcıların doğru temayı seçmesine yardımcı olur.', 'kanews' ); ?>
								</p>
							</div>
						</div>
						<p class="kanews-card__description">
							<?php esc_html_e( 'Memnun kaldıysanız lütfen deneyiminizi paylaşın. Geri bildirimler ürünün gelişimine katkı sağlar.', 'kanews' ); ?>
						</p>
						<div class="kanews-card__actions">
							<a href="https://www.kanthemes.com/urun/kanews-wordpress-haber-temasi/#reviews" target="_blank" class="button button-primary">
								<span class="dashicons dashicons-star-filled"></span>
								<?php esc_html_e( 'Değerlendirme Bırak', 'kanews' ); ?>
							</a>
							<a href="https://www.r10.net/wordpress-temalari/2597840-kanews-wordpress-temasi-yapay-zeka-ucretli-abonelikler-firma-ilan-ve-seoamphiz-optimizasyonu.html" target="_blank" class="button button-primary">
								<span class="dashicons dashicons-star-filled"></span>
								R10 Konumuz
							</a>
							<button type="button" class="button kanews-review-notice-dismiss" data-nonce="<?php echo esc_attr( $nonce ); ?>">
								<?php esc_html_e( 'Daha Sonra', 'kanews' ); ?>
							</button>
						</div>
					</div>
					<div class="kanews-card__aside">
						<div class="kanews-card__visual">
							<div class="kanews-card__stars">
								<?php for ( $i = 1; $i <= 5; $i++ ) : ?>
									<span class="dashicons dashicons-star-filled"></span>
								<?php endfor; ?>
							</div>
							<p class="kanews-card__hint">
								<?php esc_html_e( '5 Yıldız Değerlendirme', 'kanews' ); ?>
							</p>
						</div>
					</div>
				</div>
			</div>
		</div>
		<script type="text/javascript">
		jQuery(function($) {
			if ( typeof ajaxurl === 'undefined' ) {
				return;
			}

			$('.kanews-review-notice-dismiss').on('click', function(event) {
				event.preventDefault();
				var $button = $(this);
				if ( $button.data('loading') ) {
					return;
				}
				$button.data('loading', true).text('<?php echo esc_js( __( 'İşleniyor...', 'kanews' ) ); ?>');

				$.post(ajaxurl, {
					action: 'kanews_dismiss_review_box',
					nonce: $button.data('nonce')
				}).done(function(response) {
					if ( response && response.success ) {
						$button.closest('.kanews-review-admin-notice').fadeOut(200, function() {
							$(this).remove();
						});
						return;
					}
					alert((response && response.data && response.data.message) || '<?php echo esc_js( __( 'Bir hata oluştu.', 'kanews' ) ); ?>');
					$button.data('loading', false).text('<?php echo esc_js( __( 'Daha Sonra', 'kanews' ) ); ?>');
				}).fail(function() {
					alert('<?php echo esc_js( __( 'Bir hata oluştu.', 'kanews' ) ); ?>');
					$button.data('loading', false).text('<?php echo esc_js( __( 'Daha Sonra', 'kanews' ) ); ?>');
				});
			});
		});
		</script>
		<?php 
}

/*-----------------------------------------------------------------------------------*/
# 5. Yıl Kutlama Modal (Step by Step)
/*-----------------------------------------------------------------------------------*/
add_action( 'admin_footer', 'kanews_anniversary_modal' );
function kanews_anniversary_modal() {
	if ( ! current_user_can( 'manage_options' ) ) {
		return;
	}

	// TEST İÇİN: Tüm option'ları temizle (production'da kaldırılacak)
	if ( isset( $_GET['kanews_reset_modal'] ) && current_user_can( 'manage_options' ) ) {
		delete_option( 'kanews_anniversary_modal_completed' );
		delete_option( 'kanews_anniversary_modal_dismissed_until' );
		delete_option( 'kanews_anniversary_modal_dismissed_once' );
	}

	// Options kontrolü - tamamen tamamlandıysa gösterme
	$completed = get_option( 'kanews_anniversary_modal_completed', false );
	if ( $completed ) {
		return;
	}

	// Options kontrolü - 1 gün içinde kapatıldıysa gösterme (çarpı butonu)
	$dismissed_until = get_option( 'kanews_anniversary_modal_dismissed_until', 0 );
	if ( $dismissed_until && time() < $dismissed_until ) {
		return;
	}

	// Options kontrolü - tek seferlik gizleme (overlay tıklama) - yenilenince göster
	// PHP kontrolünü kaldırdık çünkü JS ile sadece DOM'dan kaldırıyoruz
	// $dismissed_once = get_option( 'kanews_anniversary_modal_dismissed_once', false );
	// if ( $dismissed_once ) {
	// 	return;
	// }

	$nonce = wp_create_nonce( 'kanews_anniversary_modal' );
	?>
	<div id="kanews-anniversary-modal" class="kanews-modal-overlay">
		<div class="kanews-modal kanews-modal--anniversary kanews-modal--step">
			
			<div class="kanews-modal__progress">
				<div class="kanews-modal__progress-bar">
					<div class="kanews-modal__progress-fill" style="width: 25%"></div>
				</div>
			<div class="kanews-modal__progress-steps">
				<span class="kanews-modal__progress-step active">1</span>
				<span class="kanews-modal__progress-step">2</span>
				<span class="kanews-modal__progress-step">3</span>
				<span class="kanews-modal__progress-step">4</span>
			</div>
			</div>
			
			<div class="kanews-modal__content">
				<!-- Step 1: Teşekkür -->
				<div class="kanews-modal__step kanews-modal__step--active" data-step="1">
					<div class="kanews-modal__header">
						<div class="kanews-modal__icon">🎉</div>
						<h2 class="kanews-modal__title">Kanews'in 5. Yaşını Bu Büyük Güncelleme ile Kutluyoruz!</h2>
					</div>
					
					<div class="kanews-modal__body">
						<div class="kanews-modal__message">
							<p>
							5 yıldır binlerce haber sitesine güç veriyoruz ve sizin desteğinizle büyümeye devam ediyoruz.

</p>
						</div>
					</div>
					
					<div class="kanews-modal__footer">
					<a href="https:///kanthemes.com/tema/kanews/guncellemeler/" target="_blank" class="button button-secondary" style="margin-right: 10px;">
							<span class="dashicons dashicons-arrow-right-alt"></span>
							Güncelleme Notları
						</a>
						<button type="button" class="button button-primary kanews-modal__next">
							<?php esc_html_e( 'İleri', 'kanews' ); ?>
							<span class="dashicons dashicons-arrow-right-alt"></span>
						</button>
					
					</div>
				</div>

				<!-- Step 2: KAI Geliştirmeleri -->
				<div class="kanews-modal__step" data-step="2">
					<div class="kanews-modal__header">
						<div class="kanews-modal__icon">🤖</div>
						<h2 class="kanews-modal__title">KAI v3.0 Yayında!</h2>
					</div>
					
					<div class="kanews-modal__body">
						<div class="kanews-modal__message">
							<p>
								KAI adlı yapay zeka asistanımızın 3.0 sürümü yayında!
							</p>
							<div class="kanews-modal__features">
								<div class="kanews-modal__feature">
									<span class="dashicons dashicons-admin-customizer"></span>
									<span>Gemini API Desteği</span>
								</div>
								<div class="kanews-modal__feature">
									<span class="dashicons dashicons-format-image"></span>
									<span>DALL·E 3 ve Nano Gemini API ile Görsel Üretimi</span>
								</div>
								<div class="kanews-modal__feature">
									<span class="dashicons dashicons-feedback"></span>
									<span>Yapay Zeka Destekli Haber Botu</span>
								</div>
								<div class="kanews-modal__feature">
									<span class="dashicons dashicons-microphone"></span>
									<span>Sesli Haber Bülteni Özelliği</span>
								</div>
								<div class="kanews-modal__feature">
									<span class="dashicons dashicons-format-image"></span>
									<span>Etkileyici Manşet Görseli Üretimi</span>
								</div>
							</div>
						</div>
					</div>
					
					<div class="kanews-modal__footer">
						<button type="button" class="button kanews-modal__prev">
							<span class="dashicons dashicons-arrow-left-alt"></span>
							<?php esc_html_e( 'Geri', 'kanews' ); ?>
						</button>
						
						<button type="button" class="button button-primary kanews-modal__next">
							<?php esc_html_e( 'İleri', 'kanews' ); ?>
							<span class="dashicons dashicons-arrow-right-alt"></span>
						</button>
					</div>
				</div>

				<!-- Step 3: Değerlendirme CTA -->
				<div class="kanews-modal__step" data-step="3">
					<div class="kanews-modal__header">
						<div class="kanews-modal__icon">⭐</div>
						<h2 class="kanews-modal__title">Değerlendirmeniz Bizim İçin Çok Değerli</h2>
					</div>
					
					<div class="kanews-modal__body">
						<div class="kanews-modal__message">
							<p>
								Kanews'i beğendiyseniz, deneyiminizi diğer kullanıcılarla paylaşın. Geri bildirimleriniz ürünün gelişimine katkı sağlar.
							</p>
							<div class="kanews-modal__stars" style="text-align: center; margin: 24px 0;">
								<?php for ( $i = 1; $i <= 5; $i++ ) : ?>
									<span class="dashicons dashicons-star-filled" style="color: #ffd700; font-size: 32px; width: 32px; height: 32px;"></span>
								<?php endfor; ?>
							</div>
							
							<div style="text-align: center; margin-top: 30px; padding-top: 30px; border-top: 1px solid rgba(0, 0, 0, 0.1);">
								<p style="font-size: 0.95em; color: rgba(29, 29, 31, 0.7); margin: 0 0 16px;">
									Yapacağınız bir yorum bizim için çok değerli!
								</p>
								<div style="display: flex; gap: 10px; justify-content: center; flex-wrap: wrap;">
									<a href="https://www.r10.net/wordpress-temalari/2597840-kanews-wordpress-haber-temasi-yapay-zeka-ucretli-abonelikler-firma-ilan-ve-seoamphiz-optimizasyonu.html" target="_blank" class="button button-secondary" style="margin: 5px;">
										R10 Konumuz
									</a>
									<a href="https://www.kanthemes.com/urun/kanews-wordpress-haber-temasi/" target="_blank" class="button button-secondary" style="margin: 5px;">
										Ürün Sayfasına Git
									</a>
								</div>
							</div>
						</div>
					</div>
					
					<div class="kanews-modal__footer">
						<button type="button" class="button kanews-modal__prev">
							<span class="dashicons dashicons-arrow-left-alt"></span>
							<?php esc_html_e( 'Geri', 'kanews' ); ?>
						</button>
						<button type="button" class="button button-primary kanews-modal__next">
							<?php esc_html_e( 'İleri', 'kanews' ); ?>
							<span class="dashicons dashicons-arrow-right-alt"></span>
						</button>
					</div>
				</div>

				<!-- Step 4: İndirim Kuponu -->
				<div class="kanews-modal__step" data-step="4">
					<div class="kanews-modal__header">
						<div class="kanews-modal__icon">🎁</div>
						<h2 class="kanews-modal__title">5. Yılımızı Kutluyoruz!</h2>
					</div>
					
					<div class="kanews-modal__body">
						<div class="kanews-modal__message">
							<p>
								5. yılımızı kutlarken, size özel bir indirim kuponu hazırladık!
							</p>
							
							<div class="kanews-modal__coupon" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 20px; padding: 40px 30px; margin: 30px 0; text-align: center; color: #fff; box-shadow: 0 12px 40px rgba(102, 126, 234, 0.4); border: 3px solid rgba(255, 255, 255, 0.2); position: relative; overflow: hidden;">
								<div style="position: absolute; top: -50%; right: -50%; width: 200%; height: 200%; background: radial-gradient(circle, rgba(255, 255, 255, 0.15) 0%, transparent 70%); animation: shimmer 3s infinite;"></div>
								<div style="position: relative; z-index: 1;">
									<div style="font-size: 1.1em; opacity: 0.95; margin-bottom: 16px; font-weight: 600; text-transform: uppercase; letter-spacing: 1px;">
										300 TL İndirim Kuponu
									</div>
									<div style="font-size: 2.5em; font-weight: 900; letter-spacing: 6px; margin: 20px 0; font-family: 'Courier New', monospace; text-shadow: 0 2px 10px rgba(0, 0, 0, 0.3); background: rgba(255, 255, 255, 0.1); padding: 20px; border-radius: 12px; border: 2px dashed rgba(255, 255, 255, 0.3);">
									KANEWS_5_YASINDA
									</div>
									<div style="font-size: 0.9em; opacity: 0.85; margin-top: 16px; font-weight: 500;">
										Son kullanma: 1 Ocak 2026
									</div>
									<div style="font-size: 0.85em; opacity: 0.75; margin-top: 8px;">
										İlk 100 kişiye özel
									</div>
								</div>
							</div>
						</div>
					</div>
					
					<div class="kanews-modal__footer">
						<button type="button" class="button kanews-modal__prev">
							<span class="dashicons dashicons-arrow-left-alt"></span>
							<?php esc_html_e( 'Geri', 'kanews' ); ?>
						</button>
						<button type="button" class="button button-primary kanews-anniversary-complete" data-nonce="<?php echo esc_attr( $nonce ); ?>">
							<span class="dashicons dashicons-yes-alt"></span>
							<?php esc_html_e( 'Tamamla', 'kanews' ); ?>
						</button>
					</div>
				</div>
			</div>
		</div>
	</div>
	
	<?php
}

/*-----------------------------------------------------------------------------------*/
# Review Notice
/*-----------------------------------------------------------------------------------*/

function kanews_update_check2() {
	$updates = get_option('puc_external_updates_theme-kanews') ? get_option('puc_external_updates_theme-kanews') : null;
	
	if($updates != null) {
		if (isset( $updates->update->version ) && version_compare( $updates->update->version, KAN_THEME_VER, '>' ))
		return true;
	}
	
	return false;
}

/*-----------------------------------------------------------------------------------*/
# Create Admin Menu
/*-----------------------------------------------------------------------------------*/
add_action( 'admin_menu', 'kanews_admin_menu' );
if ( ! function_exists( 'kanews_admin_menu' ) ) {
	function kanews_admin_menu() {
		
		if(kanews_update_check2()) {
			$title = 'Kanews <span class="update-plugins count-1"><span class="plugin-count">1</span></span>';
			$title2 = __('Güncellemeler', 'kanews').' <span class="update-plugins count-1"><span class="plugin-count">1</span></span>';
		}
		else {
			$title = 'Kanews';
			$title2 = __('Güncellemeler', 'kanews');
		}

		$options = '';
		// $options = '<span class="update-plugins count-1"><span class="plugin-count">2</span></span>';
		$plugins = '';
		add_menu_page( __('Tema Ayarları', 'kanews'), $title, 'manage_options', 'kanews-options', 'kanews_theme_options_page', ''.get_template_directory_uri().'/assets/img/kanthemes_favicon.png', 60  );
		add_submenu_page('kanews-options', __('Tema Ayarları', 'kanews'), __('Tema Ayarları', 'kanews').$options, 'manage_options', 'kanews-options', 'kanews_theme_options_page' );
		add_submenu_page('kanews-options', __('Kanews Temasına Hoşgeldiniz', 'kanews'), __('Başlangıç', 'kanews'), 'manage_options', 'kanews-welcome', 'kanews_welcome_page' );
		add_submenu_page('kanews-options', __('Güncellemeler', 'kanews'), $title2, 'manage_options', 'kanews-update', 'kanews_updates_page' );
		add_submenu_page('kanews-options', __('Demo Aktarıcı', 'kanews'), __('Demo Aktarıcı', 'kanews'), 'manage_options', 'kanews-import', 'kanews_demo_importer_page' );
		add_submenu_page('kanews-options', __('Uyumlu Eklentiler', 'kanews'), __('Uyumlu Eklentiler', 'kanews').$plugins, 'manage_options', 'kanews-plugins', 'kanews_compaitable_plugins' );
		add_submenu_page('kanews-options', __('KAI Araçları', 'kanews'), '<svg style="vertical-align:middle" width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="none" stroke="currentColor" stroke-width="2" d="M18.3482396,15.9535197 C18.7664592,15.0561341 19,14.0553403 19,13 C19,9.13400675 15.8659932,6 12,6 C8.13400675,6 5,9.13400675 5,13 C5,14.1167756 5.2615228,15.1724692 5.72666673,16.1091793 L5.72666673,16.1091793 M12,3 C12.5522847,3 13,2.55228475 13,2 C13,1.44771525 12.5522847,1 12,1 C11.4477153,1 11,1.44771525 11,2 C11,2.55228475 11.4477153,3 12,3 Z M12,23 C12.5522847,23 13,22.5522847 13,22 C13,21.4477153 12.5522847,21 12,21 C11.4477153,21 11,21.4477153 11,22 C11,22.5522847 11.4477153,23 12,23 Z M12,6 L12,3 M9,14 C9.55228475,14 10,13.5522847 10,13 C10,12.4477153 9.55228475,12 9,12 C8.44771525,12 8,12.4477153 8,13 C8,13.5522847 8.44771525,14 9,14 Z M15,14 C15.5522847,14 16,13.5522847 16,13 C16,12.4477153 15.5522847,12 15,12 C14.4477153,12 14,12.4477153 14,13 C14,13.5522847 14.4477153,14 15,14 Z M6,18.9876876 L5,16 C5,16 5.07242747,15.2283988 5.5,15.5 C6.43069361,16.0911921 8.57396448,17 12,17 C15.5536669,17 17.6181635,16.0844828 18.5,15.5 C18.8589052,15.262117 19,16 19,16 L18,18.9876876 C18,18.9876876 17.0049249,20.9999997 12,21 C6.99507512,21.0000003 6,18.9876876 6,18.9876876 Z"/></svg> '.__('KAI', 'kanews'), 'manage_options', 'kanews-kai', 'kanews_kai_admin_page' );
	}
}

// Add Item For Admin Bar
function kanews_admin_bar_add_item($admin_bar)  {
	$args = array(
		'id'        => 'kanews-theme-admin-bar', // Must be a unique name
		'title'     => '<img src="'.get_template_directory_uri().'/assets/img/kanthemes_favicon.png" width="12" height="12" style="width:18px!important;height:18px!important;vertical-align:-4px;margin-right:8px;"/>'.__('Kanews Ayarları', 'kanews'), // Label for this item
		'href'      => get_admin_url() . 'admin.php?page=kanews-options',
	);
	$admin_bar->add_menu( $args);
	
	if(kanews_update_check2() == true) {
		$adminURL = get_admin_url() . 'themes.php';
		$admin_bar->add_menu( array(
			'id'    => 'update_notifier',
			'title' => sprintf( __( '%s Güncellemesi Hazır', 'kanews' ), KAN_THEME_NAME ) . ' <span id="ab-updates">1</span>',
			'href'  => $adminURL
		) );
	}
}
add_action('admin_bar_menu', 'kanews_admin_bar_add_item', 900);

/*-----------------------------------------------------------------------------------*/
# Page Tabs 2
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( 'kanews_admin_tab_2' ) ) {
	function kanews_admin_tab_2($aktif1, $aktif2, $aktif3, $aktif4, $aktif5, $aktif6 = '', $aktif7 = '' ) { 
		// Değerleri normalize et ve escape et.
		$aktif1 = ( $aktif1 !== null && $aktif1 !== '' ) ? esc_attr( $aktif1 ) : '';
		$aktif2 = ( $aktif2 !== null && $aktif2 !== '' ) ? esc_attr( $aktif2 ) : '';
		$aktif3 = ( $aktif3 !== null && $aktif3 !== '' ) ? esc_attr( $aktif3 ) : '';
		$aktif4 = ( $aktif4 !== null && $aktif4 !== '' ) ? esc_attr( $aktif4 ) : '';
		$aktif5 = ( $aktif5 !== null && $aktif5 !== '' ) ? esc_attr( $aktif5 ) : '';
		$aktif6 = ( $aktif6 !== null && $aktif6 !== '' ) ? esc_attr( $aktif6 ) : '';
		$aktif7 = ( $aktif7 !== null && $aktif7 !== '' ) ? esc_attr( $aktif7 ) : '';
		?>
		<nav class="kan__header-navigation nav-tab-wrapper wp-clearfix" aria-label="İkincil menü">
			<a href="<?php echo admin_url(); ?>admin.php?page=kanews-welcome" class="nav-tab <?php echo $aktif1; ?>"><?php _e('Başlangıç', 'kanews'); ?></a>
			<a href="<?php echo admin_url(); ?>admin.php?page=kanews-options" class="nav-tab <?php echo $aktif2; ?>"><?php _e('Tema Ayarları', 'kanews'); ?></a>
			<a href="<?php echo admin_url(); ?>admin.php?page=kanews-license" class="nav-tab <?php echo $aktif3; ?>"><?php _e('Lisans', 'kanews'); ?></a>
			<a href="<?php echo admin_url(); ?>admin.php?page=kanews-update" class="nav-tab <?php echo $aktif4; ?>"><?php _e('Güncellemeler', 'kanews'); ?></a>
			<a href="<?php echo admin_url(); ?>admin.php?page=kanews-import" class="nav-tab <?php echo $aktif5; ?>"><?php _e('Demo Aktarıcı', 'kanews'); ?></a>
			<a href="<?php echo admin_url(); ?>admin.php?page=kanews-plugins" class="nav-tab <?php echo $aktif6; ?>"><?php _e('Eklentiler', 'kanews'); ?></a>
			<a href="<?php echo admin_url(); ?>admin.php?page=kanews-kai" class="nav-tab <?php echo $aktif7; ?>">
				<svg style="vertical-align:middle; width:16px; height:16px; margin-right:6px;" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
					<path fill="none" stroke="currentColor" stroke-width="2" d="M18.3482396,15.9535197 C18.7664592,15.0561341 19,14.0553403 19,13 C19,9.13400675 15.8659932,6 12,6 C8.13400675,6 5,9.13400675 5,13 C5,14.1167756 5.2615228,15.1724692 5.72666673,16.1091793 L5.72666673,16.1091793 M12,3 C12.5522847,3 13,2.55228475 13,2 C13,1.44771525 12.5522847,1 12,1 C11.4477153,1 11,1.44771525 11,2 C11,2.55228475 11.4477153,3 12,3 Z M12,23 C12.5522847,23 13,22.5522847 13,22 C13,21.4477153 12.5522847,21 12,21 C11.4477153,21 11,21.4477153 11,22 C11,22.5522847 11.4477153,23 12,23 Z M12,6 L12,3 M9,14 C9.55228475,14 10,13.5522847 10,13 C10,12.4477153 9.55228475,12 9,12 C8.44771525,12 8,12.4477153 8,13 C8,13.5522847 8.44771525,14 9,14 Z M15,14 C15.5522847,14 16,13.5522847 16,13 C16,12.4477153 15.5522847,12 15,12 C14.4477153,12 14,12.4477153 14,13 C14,13.5522847 14.4477153,14 15,14 Z M6,18.9876876 L5,16 C5,16 5.07242747,15.2283988 5.5,15.5 C6.43069361,16.0911921 8.57396448,17 12,17 C15.5536669,17 17.6181635,16.0844828 18.5,15.5 C18.8589052,15.262117 19,16 19,16 L18,18.9876876 C18,18.9876876 17.0049249,20.9999997 12,21 C6.99507512,21.0000003 6,18.9876876 6,18.9876876 Z"/>
				</svg>
				<?php _e('KAI', 'kanews'); ?>
			</a>
			<a href="https://www.codezenic.com/services/bakim-destek/" class="nav-tab nav-tab--external" target="_blank" rel="noopener noreferrer">
				<?php esc_html_e( 'WordPress Destek', 'kanews' ); ?>
			</a>
			<a href="https://www.hostinger.com.tr/cart?product=hosting%3Ahostinger_premium&period=12&referral_type=cart_link&REFERRALCODE=kanthemes&referral_id=019b043e-2ae4-72cd-ade4-8b317ba441d0" class="nav-tab nav-tab--external nav-tab--hosting" target="_blank" rel="noopener noreferrer">
				<span class="dashicons dashicons-cloud" style="vertical-align:middle; margin-right:4px;"></span>
				<?php esc_html_e( 'Hosting Edin', 'kanews' ); ?>
			</a>
		</nav>
		<?php if(kanews_update_check2() == true) : ?>
			<br>
			<div class="kan-update-alert">

				<?php
				$updates = get_option('puc_external_updates_theme-kanews') ? get_option('puc_external_updates_theme-kanews') : null;
				printf( __('<strong>%1$s</strong> temasının %2$s sürümü kurulu. <strong>%3$s</strong> sürümüne yükseltebilirsiniz. <a class="button" href="%4$s">Güncellemek için tıklayın.</a>', 'kanews'),
					KAN_THEME_NAME,
					KAN_THEME_VER,
					$updates->update->version,
					admin_url().'themes.php'
				);
				?>

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

/*-----------------------------------------------------------------------------------*/
# Admin Header Helper
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( 'kanews_render_admin_header' ) ) {
	/**
	 * Standart Kanews admin sayfa header'ını üretir.
	 *
	 * @param string $active_tab   Aktif sekme anahtarı: welcome|options|license|update|import|plugins|kai.
	 * @param string $header_text  Başlık altı açıklama metni.
	 */
	function kanews_render_admin_header( $active_tab = null, $header_text = '' ) {
		// Geçerli admin sayfasına göre otomatik aktif sekme tespiti.
		$current_page = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : '';
		$page_map = array(
			'kanews-welcome' => 'welcome',
			'kanews-options' => 'options',
			'kanews-license' => 'license',
			'kanews-update'  => 'update',
			'kanews-import'  => 'import',
			'kanews-plugins' => 'plugins',
			'kanews-kai'     => 'kai',
		);

		// Eğer $active_tab belirtilmemişse, otomatik algıla.
		if ( empty( $active_tab ) ) {
			if ( $current_page && isset( $page_map[ $current_page ] ) ) {
				$active_tab = $page_map[ $current_page ];
			} else {
				$active_tab = 'options';
			}
		}

		// Sekme sınıflarını hazırla - tüm sekmeler boş string, sadece aktif olan 'nav-tab-active' olacak.
		$tabs = array(
			'welcome' => '',
			'options' => '',
			'license' => '',
			'update'  => '',
			'import'  => '',
			'plugins' => '',
			'kai'     => '',
		);

		// Aktif sekmeye 'nav-tab-active' class'ını ekle.
		if ( isset( $tabs[ $active_tab ] ) ) {
			$tabs[ $active_tab ] = 'nav-tab-active';
		}
		?>
		<div class="kan__header kanews-anniversary-5">
			<div class="kanews-anniversary-badge">
				<span class="kanews-anniversary-icon">🎉</span>
				<span class="kanews-anniversary-text">5. Yıl</span>
			</div>

			<div class="kan__header-container">
				<div class="kan__header-title">
					<p>
					<?php 
					printf(
						'Kanews <span class="kan-theme-ver">v%1$s</span>',
						KAN_THEME_VER
					);
					?>
					</p>
				</div>

				<?php if ( ! empty( $header_text ) ) : ?>
					<div class="kan__header-text"><?php echo wp_kses_post( $header_text ); ?></div>
				<?php endif; ?>
			</div>

			<?php
			kanews_admin_tab_2(
				$tabs['welcome'],
				$tabs['options'],
				$tabs['license'],
				$tabs['update'],
				$tabs['import'],
				$tabs['plugins'],
				$tabs['kai']
			);
			?>

		</div>
		<?php
	}
}
/*-----------------------------------------------------------------------------------*/
# Page Tabs
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( 'kanews_admin_tab' ) ) {
	function kanews_admin_tab($aktif1, $aktif2, $aktif3, $aktif4, $aktif5) { ?>
		<h2 class="nav-tab-wrapper kanews-nav-tab-wrapper wp-clearfix">
			<a href="<?php echo admin_url(); ?>admin.php?page=kanews-welcome" class="nav-tab <?php echo $aktif1; ?>"><?php _e('Başlangıç', 'kanews'); ?></a>
			<a href="<?php echo admin_url(); ?>admin.php?page=kanews-options" class="nav-tab <?php echo $aktif2; ?>"><?php _e('Tema Ayarları', 'kanews'); ?></a>
			<a href="<?php echo admin_url(); ?>admin.php?page=kanews-license" class="nav-tab <?php echo $aktif3; ?>"><?php _e('Lisans Doğrulama', 'kanews'); ?></a>
			<a href="<?php echo admin_url(); ?>admin.php?page=kanews-update" class="nav-tab <?php echo $aktif4; ?>"><?php _e('Güncellemeler', 'kanews'); ?></a>
			<a href="<?php echo admin_url(); ?>admin.php?page=kanews-import" class="nav-tab <?php echo $aktif5; ?>"><?php _e('Demo Aktarıcı', 'kanews'); ?></a>
			<a target="_blank" href="https://www.kanthemes.com/tema/kanews/" class="nav-tab"><?php _e('Destek Masası', 'kanews'); ?></a>
		</h2>
		<?php if(kanews_update_check2() == true) : ?>
			<br>
			<div class="update-nag notice notice-success inline">

				<?php
				$updates = get_option('puc_external_updates_theme-kanews') ? get_option('puc_external_updates_theme-kanews') : null;
				printf( __('<strong>%1$s</strong> temasının %2$s sürümü kurulu. <strong>%3$s</strong> sürümüne yükseltebilirsiniz.<br><br> <a class="button" href="%4$s">Güncellemek için tıklayın.</a>', 'kanews'),
					KAN_THEME_NAME,
					KAN_THEME_VER,
					$updates->update->version,
					admin_url().'themes.php'
				);
				?>

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


/*-----------------------------------------------------------------------------------*/
# Admin Hero Helper
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( 'kanews_render_admin_hero' ) ) {
	/**
	 * Reusable hero section for Kanews admin pages.
	 *
	 * @param array $args Hero configuration.
	 */
	function kanews_render_admin_hero( $args = array() ) {
		$defaults = array(
			'eyebrow'        => '',
			'title'          => '',
			'title_html'     => '',
			'description'    => '',
			'description_html' => '',
			'tags'           => array(), // Each: ['label' => '', 'value' => ''].
			'meta'           => '',
			'show_patterns'  => true,
			'class'          => '',
			'actions'        => array(), // Each: ['label' => '', 'href' => '', 'class' => 'button', 'target' => '', 'attrs' => [] ].
			'stats'          => array(), // Each: ['label' => '', 'value' => '', 'hint' => ''].
		);
		$hero = wp_parse_args( $args, $defaults );

		$hero_classes = trim( 'kanews-hero kanews-anniversary-hero ' . $hero['class'] );
		?>
		<div class="<?php echo esc_attr( $hero_classes ); ?>">
			<?php if ( $hero['show_patterns'] ) : ?>
				<div class="kanews-hero__pattern kanews-hero__pattern--one"></div>
				<div class="kanews-hero__pattern kanews-hero__pattern--two"></div>
			<?php endif; ?>

			<div class="kanews-hero__body">
				<?php if ( ! empty( $hero['eyebrow'] ) ) : ?>
					<p class="kanews-hero__eyebrow"><?php echo esc_html( $hero['eyebrow'] ); ?></p>
				<?php endif; ?>

						<?php 
				if ( ! empty( $hero['title_html'] ) ) {
					echo wp_kses_post( $hero['title_html'] );
				} elseif ( ! empty( $hero['title'] ) ) {
					?>
					<h1 class="kanews-hero__title"><?php echo esc_html( $hero['title'] ); ?></h1>
					<?php
				}

				if ( ! empty( $hero['description_html'] ) ) {
					echo wp_kses_post( $hero['description_html'] );
				} elseif ( ! empty( $hero['description'] ) ) {
					?>
					<p class="kanews-hero__desc"><?php echo esc_html( $hero['description'] ); ?></p>
					<?php
				}
				?>

				<?php if ( ! empty( $hero['tags'] ) ) : ?>
					<div class="kanews-hero__tags">
						<?php foreach ( $hero['tags'] as $tag ) : ?>
							<?php if ( empty( $tag['label'] ) && empty( $tag['value'] ) ) { continue; } ?>
							<span class="kanews-hero__tag">
								<?php if ( ! empty( $tag['value'] ) ) : ?>
									<strong><?php echo esc_html( $tag['value'] ); ?></strong>
								<?php endif; ?>
								<?php if ( ! empty( $tag['label'] ) ) : ?>
									<span><?php echo esc_html( $tag['label'] ); ?></span>
								<?php endif; ?>
							</span>
						<?php endforeach; ?>
					</div>
				<?php endif; ?>

				<?php if ( ! empty( $hero['meta'] ) ) : ?>
					<div class="kanews-hero__meta">
						<span><?php echo wp_kses_post( $hero['meta'] ); ?></span>
				</div>
				<?php endif; ?>

				<?php if ( ! empty( $hero['actions'] ) ) : ?>
					<div class="kanews-hero__actions">
						<?php foreach ( $hero['actions'] as $action ) : ?>
							<?php
							if ( empty( $action['label'] ) ) {
								continue;
							}
							$action_href  = isset( $action['href'] ) ? $action['href'] : '#';
							$action_class = isset( $action['class'] ) ? $action['class'] : 'button';
							$attrs        = '';
							if ( ! empty( $action['attrs'] ) && is_array( $action['attrs'] ) ) {
								foreach ( $action['attrs'] as $attr_key => $attr_value ) {
									if ( '' === $attr_value && 'data-' !== substr( $attr_key, 0, 5 ) ) {
										continue;
									}
									$attrs .= sprintf( ' %1$s="%2$s"', esc_attr( $attr_key ), esc_attr( $attr_value ) );
								}
							}
							$target = '';
							if ( ! empty( $action['target'] ) ) {
								$target = sprintf( ' target="%s"', esc_attr( $action['target'] ) );
							}
							?>
							<a href="<?php echo esc_url( $action_href ); ?>" class="<?php echo esc_attr( $action_class ); ?>"<?php echo $target; ?><?php echo $attrs; ?>>
								<?php echo esc_html( $action['label'] ); ?>
							</a>
						<?php endforeach; ?>
			</div>
				<?php endif; ?>
			</div>

			<?php if ( ! empty( $hero['stats'] ) ) : ?>
				<div class="kanews-hero__stats">
					<?php foreach ( $hero['stats'] as $stat ) : ?>
						<?php if ( empty( $stat['label'] ) && empty( $stat['value'] ) ) { continue; } ?>
						<div class="kanews-hero__stat">
							<?php if ( ! empty( $stat['label'] ) ) : ?>
								<span class="kanews-hero__stat-label"><?php echo esc_html( $stat['label'] ); ?></span>
							<?php endif; ?>
							<?php if ( ! empty( $stat['value'] ) ) : ?>
								<span class="kanews-hero__stat-value"><?php echo esc_html( $stat['value'] ); ?></span>
							<?php endif; ?>
							<?php if ( ! empty( $stat['hint'] ) ) : ?>
								<span class="kanews-hero__stat-hint"><?php echo esc_html( $stat['hint'] ); ?></span>
							<?php endif; ?>
						</div>
					<?php endforeach; ?>
				</div>
			<?php endif; ?>
		</div>
		<?php
	}
}

/*-----------------------------------------------------------------------------------*/
# Page: Theme Options
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( 'kanews_theme_options_page' ) ) {
	function kanews_theme_options_page(){ 
		?>
		<div class="wrap kan__container kanews-wrap">

			<?php kanews_render_admin_header( 'options', __( 'Kanews temasını kendi zevkinize göre şekilendirmeye hemen başlayabilirsiniz.', 'kanews' ) ); ?>
		</div>
	<?php 
	}
}

/*-----------------------------------------------------------------------------------*/
# Page: Theme Translate
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( 'kanews_theme_translate_page' ) ) {
	function kanews_theme_translate_page(){ 
		?>
		<div class="wrap kan__container kanews-wrap">

			<?php kanews_render_admin_header( 'options', __( 'Kanews temasını kendi zevkinize göre şekilendirmeye hemen başlayabilirsiniz.', 'kanews' ) ); ?>
		</div>
						<?php 
	}
}

/*-----------------------------------------------------------------------------------*/
# Get Setup Progress
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( 'kanews_get_setup_progress' ) ) {
	function kanews_get_setup_progress() {
		$opts = get_option( 'kanews_options', array() );
		$has_api_key = ! empty( $opts['openai-api'] ) || ! empty( $opts['gemini-api'] );
		$setup_completed = get_option( 'kanews_setup_completed_steps', array() );
		
		$steps = array(
			'demo' => array(
				'name' => __( 'Demo kurulumu yap', 'kanews' ),
				'check' => ! empty( $setup_completed['demo'] ) || get_option( 'kanews_demo_imported', false ),
				'url' => admin_url( 'admin.php?page=kanews-import' ),
				'icon' => 'dashicons-download',
			),
			'menu' => array(
				'name' => __( 'Menü ayarlarını yap', 'kanews' ),
				'check' => ! empty( $setup_completed['menu'] ) || ( has_nav_menu( 'menu-1' ) || has_nav_menu( 'menu-2' ) ),
				'url' => admin_url( 'nav-menus.php' ),
				'icon' => 'dashicons-menu',
			),
			'options' => array(
				'name' => __( 'Tema ayarlarını yap', 'kanews' ),
				'check' => ! empty( $setup_completed['options'] ) || ( get_option( 'kanews_options' ) ? true : false ),
				'url' => admin_url( 'admin.php?page=kanews-options' ),
				'icon' => 'dashicons-admin-appearance',
			),
			'api' => array(
				'name' => __( 'Gemini veya OpenAI api key ekle', 'kanews' ),
				'check' => ! empty( $setup_completed['api'] ) || $has_api_key,
				'url' => admin_url( 'admin.php?page=kanews-kai#kai-settings' ),
				'icon' => 'dashicons-admin-network',
			),
			'pages' => array(
				'name' => __( 'Sayfaları Oluştur', 'kanews' ),
				'check' => ! empty( $setup_completed['pages'] ) || ( get_option( 'kanews_pages_created', false ) ),
				'url' => admin_url( 'edit.php?post_type=page' ),
				'icon' => 'dashicons-admin-page',
			),
			'widgets' => array(
				'name' => __( 'Bileşen Ayarlarını Yap', 'kanews' ),
				'check' => ! empty( $setup_completed['widgets'] ) || ( is_active_sidebar( 'sidebar-1' ) || is_active_sidebar( 'home-content' ) ),
				'url' => admin_url( 'widgets.php' ),
				'icon' => 'dashicons-screenoptions',
			),
		);

		$completed = 0;
		$total = count( $steps );

		foreach ( $steps as $step ) {
			if ( $step['check'] ) {
				$completed++;
			}
		}

		$percentage = $total > 0 ? round( ( $completed / $total ) * 100 ) : 0;

		return array(
			'steps' => $steps,
			'completed' => $completed,
			'total' => $total,
			'percentage' => $percentage,
		);
	}
}

/*-----------------------------------------------------------------------------------*/
# Setup Wizard AJAX Handlers
/*-----------------------------------------------------------------------------------*/
// Mark step as completed
add_action( 'wp_ajax_kanews_setup_complete_step', 'kanews_ajax_complete_setup_step' );
// Skip step
add_action( 'wp_ajax_kanews_setup_skip_step', 'kanews_ajax_skip_setup_step' );
// Dismiss wizard
add_action( 'wp_ajax_kanews_setup_dismiss', 'kanews_ajax_dismiss_setup_wizard' );
// Dismiss review box
add_action( 'wp_ajax_kanews_dismiss_review_box', 'kanews_ajax_dismiss_review_box' );
// Re-open wizard
add_action( 'wp_ajax_kanews_show_setup_wizard', 'kanews_ajax_show_setup_wizard' );
// Re-show review box
add_action( 'wp_ajax_kanews_show_review_box', 'kanews_ajax_show_review_box' );
// Dismiss anniversary modal (1 gün)
add_action( 'wp_ajax_kanews_dismiss_anniversary_modal', 'kanews_ajax_dismiss_anniversary_modal' );
// Complete anniversary modal (tamamlandı)
add_action( 'wp_ajax_kanews_complete_anniversary_modal', 'kanews_ajax_complete_anniversary_modal' );
// Dismiss once (tek seferlik - overlay tıklama)
add_action( 'wp_ajax_kanews_dismiss_anniversary_modal_once', 'kanews_ajax_dismiss_anniversary_modal_once' );

if ( ! function_exists( 'kanews_ajax_complete_setup_step' ) ) {
	function kanews_ajax_complete_setup_step() {
		check_ajax_referer( 'kanews_setup_wizard', 'nonce' );
		
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Yetkiniz yok.', 'kanews' ) ) );
		}

		$step = isset( $_POST['step'] ) ? sanitize_key( $_POST['step'] ) : '';
		if ( empty( $step ) ) {
			wp_send_json_error( array( 'message' => __( 'Geçersiz adım.', 'kanews' ) ) );
		}

		$completed = get_option( 'kanews_setup_completed_steps', array() );
		$completed[ $step ] = true;
		update_option( 'kanews_setup_completed_steps', $completed );

		$progress = kanews_get_setup_progress();
		wp_send_json_success( array(
			'progress' => $progress,
			'message' => __( 'Adım tamamlandı olarak işaretlendi.', 'kanews' ),
		) );
	}
}

if ( ! function_exists( 'kanews_ajax_skip_setup_step' ) ) {
	function kanews_ajax_skip_setup_step() {
		check_ajax_referer( 'kanews_setup_wizard', 'nonce' );
		
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Yetkiniz yok.', 'kanews' ) ) );
		}

		$step = isset( $_POST['step'] ) ? sanitize_key( $_POST['step'] ) : '';
		if ( empty( $step ) ) {
			wp_send_json_error( array( 'message' => __( 'Geçersiz adım.', 'kanews' ) ) );
		}

		$completed = get_option( 'kanews_setup_completed_steps', array() );
		$completed[ $step ] = true; // Skip also marks as completed
		update_option( 'kanews_setup_completed_steps', $completed );

		$progress = kanews_get_setup_progress();
		wp_send_json_success( array(
			'progress' => $progress,
			'message' => __( 'Adım atlandı.', 'kanews' ),
		) );
	}
}

if ( ! function_exists( 'kanews_ajax_dismiss_setup_wizard' ) ) {
	function kanews_ajax_dismiss_setup_wizard() {
		check_ajax_referer( 'kanews_setup_wizard', 'nonce' );
		
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Yetkiniz yok.', 'kanews' ) ) );
		}

		update_option( 'kanews_setup_wizard_dismissed', true );
		wp_send_json_success( array( 'message' => __( 'Kurulum sihirbazı kapatıldı.', 'kanews' ) ) );
	}
}

if ( ! function_exists( 'kanews_ajax_dismiss_review_box' ) ) {
	function kanews_ajax_dismiss_review_box() {
		check_ajax_referer( 'kanews_review_box', 'nonce' );
		
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Yetkiniz yok.', 'kanews' ) ) );
		}

		update_option( 'kanews_review_box_dismissed', true );
		wp_send_json_success( array( 'message' => __( 'Değerlendirme kutusu kapatıldı.', 'kanews' ) ) );
	}
}

if ( ! function_exists( 'kanews_ajax_show_setup_wizard' ) ) {
	function kanews_ajax_show_setup_wizard() {
		check_ajax_referer( 'kanews_setup_wizard_toggle', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Yetkiniz yok.', 'kanews' ) ) );
		}

		update_option( 'kanews_setup_wizard_dismissed', false );
		wp_send_json_success( array( 'message' => __( 'Kurulum sihirbazı yeniden etkinleştirildi.', 'kanews' ) ) );
	}
}

if ( ! function_exists( 'kanews_ajax_show_review_box' ) ) {
	function kanews_ajax_show_review_box() {
		check_ajax_referer( 'kanews_review_box_toggle', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Yetkiniz yok.', 'kanews' ) ) );
		}

		update_option( 'kanews_review_box_dismissed', false );
		wp_send_json_success( array( 'message' => __( 'Değerlendirme kutusu yeniden gösterilecek.', 'kanews' ) ) );
	}
}

if ( ! function_exists( 'kanews_ajax_dismiss_anniversary_modal' ) ) {
	function kanews_ajax_dismiss_anniversary_modal() {
		check_ajax_referer( 'kanews_anniversary_modal', 'nonce' );
		
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Yetkiniz yok.', 'kanews' ) ) );
		}

		// 1 gün boyunca gösterme (24 saat = 86400 saniye)
		$dismissed_until = time() + (24 * 60 * 60);
		update_option( 'kanews_anniversary_modal_dismissed_until', $dismissed_until );
		
		wp_send_json_success( array( 'message' => __( 'Modal 1 gün boyunca gösterilmeyecek.', 'kanews' ) ) );
	}
}

if ( ! function_exists( 'kanews_ajax_complete_anniversary_modal' ) ) {
	function kanews_ajax_complete_anniversary_modal() {
		check_ajax_referer( 'kanews_anniversary_modal', 'nonce' );
		
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Yetkiniz yok.', 'kanews' ) ) );
		}

		// Tamamen tamamlandı - bir daha gösterme
		update_option( 'kanews_anniversary_modal_completed', true );
		
		wp_send_json_success( array( 'message' => __( 'Modal tamamlandı.', 'kanews' ) ) );
	}
}

if ( ! function_exists( 'kanews_ajax_dismiss_anniversary_modal_once' ) ) {
	function kanews_ajax_dismiss_anniversary_modal_once() {
		check_ajax_referer( 'kanews_anniversary_modal', 'nonce' );
		
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Yetkiniz yok.', 'kanews' ) ) );
		}

		// Tek seferlik gizle - yenilenince göster
		update_option( 'kanews_anniversary_modal_dismissed_once', true );
		
		wp_send_json_success( array( 'message' => __( 'Modal bu seferlik gizlendi. Sayfa yenilendiğinde tekrar gösterilecek.', 'kanews' ) ) );
	}
}

// AJAX handler artık gerekli değil - cookie kullanılıyor

/*-----------------------------------------------------------------------------------*/
# Page: Welcome
/*-----------------------------------------------------------------------------------*/
	if ( ! function_exists( 'kanews_welcome_page' ) ) {
	function kanews_welcome_page(){
		$progress = kanews_get_setup_progress();
		$wizard_dismissed = get_option( 'kanews_setup_wizard_dismissed', false );
		$force_wizard = ! empty( $_GET['kanews_force_setup'] );
		
		// If progress is 100% or wizard is dismissed, show normal welcome page
		if ( ( $progress['percentage'] >= 100 || $wizard_dismissed ) && ! $force_wizard ) {
			kanews_welcome_page_complete();
			return;
		}
		
		// Show setup wizard
		?>
		<div class="wrap kan__container kanews-wrap kanews-setup-wizard">

			<?php kanews_render_admin_header( 'welcome', __( 'Kanews Wordpress temasını tercih ettiğiniz için teşekkür ederiz.', 'kanews' ) ); ?>
			
			<div class="kanews-setup-wizard-container">
				<div class="kanews-setup-wizard-header">
					<h1 class="kanews-setup-wizard-title">
						<?php esc_html_e( 'Kurulum Sihirbazı', 'kanews' ); ?>
					</h1>
					<p class="kanews-setup-wizard-description">
						<?php esc_html_e( 'Aşağıdaki adımları tamamlayarak temanızı hızlıca yapılandırabilirsiniz.', 'kanews' ); ?>
					</p>
					<div class="kanews-setup-wizard-progress">
						<div class="kanews-setup-wizard-progress-bar">
							<div class="kanews-setup-wizard-progress-fill" style="width: <?php echo esc_attr( $progress['percentage'] ); ?>%;"></div>
						</div>
						<div class="kanews-setup-wizard-progress-text">
							<?php printf( esc_html__( '%1$d / %2$d adım tamamlandı (%3$d%%)', 'kanews' ), $progress['completed'], $progress['total'], $progress['percentage'] ); ?>
						</div>
					</div>
					</div>

				<div class="kanews-setup-wizard-steps">
					<?php
					$step_order = array( 'demo', 'menu', 'options', 'api', 'pages', 'widgets' );
					foreach ( $step_order as $step_key ) {
						if ( ! isset( $progress['steps'][ $step_key ] ) ) {
							continue;
						}
						$step = $progress['steps'][ $step_key ];
						$is_completed = $step['check'];
						?>
						<div class="kanews-setup-wizard-step <?php echo $is_completed ? 'is-completed' : ''; ?>" data-step="<?php echo esc_attr( $step_key ); ?>">
							<div class="kanews-setup-wizard-step-header">
								<div class="kanews-setup-wizard-step-icon">
									<?php if ( $is_completed ) : ?>
										<span class="dashicons dashicons-yes-alt"></span>
									<?php else : ?>
										<span class="dashicons <?php echo esc_attr( $step['icon'] ); ?>"></span>
									<?php endif; ?>
				</div>
								<div class="kanews-setup-wizard-step-content">
									<h3 class="kanews-setup-wizard-step-title">
										<?php echo esc_html( $step['name'] ); ?>
									</h3>
									<?php if ( $is_completed ) : ?>
										<p class="kanews-setup-wizard-step-status">
											<?php esc_html_e( 'Tamamlandı', 'kanews' ); ?>
										</p>
									<?php endif; ?>
			</div>
								<?php if ( $is_completed ) : ?>
									<div class="kanews-setup-wizard-step-checkmark">
										<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
											<circle cx="12" cy="12" r="10" fill="#34c759"/>
											<path d="M8 12L11 15L16 9" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
										</svg>
									</div>
								<?php endif; ?>
							</div>
							<?php if ( ! $is_completed ) : ?>
								<div class="kanews-setup-wizard-step-actions">
									<a href="<?php echo esc_url( $step['url'] ); ?>" class="button button-primary kanews-setup-wizard-step-button">
										<?php esc_html_e( 'Adıma Git', 'kanews' ); ?>
									</a>
									<button type="button" class="button kanews-setup-wizard-step-complete" data-step="<?php echo esc_attr( $step_key ); ?>">
										<?php esc_html_e( 'Tamamlandı', 'kanews' ); ?>
									</button>
									<button type="button" class="button kanews-setup-wizard-step-skip" data-step="<?php echo esc_attr( $step_key ); ?>">
										<?php esc_html_e( 'Atla', 'kanews' ); ?>
									</button>
								</div>
							<?php endif; ?>
		</div>
	<?php 
	}
					?>
				</div>
				
				<div class="kanews-setup-wizard-footer">
					<button type="button" class="button kanews-setup-wizard-dismiss">
						<?php esc_html_e( 'Sihirbazı Kapat', 'kanews' ); ?>
					</button>
				</div>
			</div>
			
			<script type="text/javascript">
			jQuery(document).ready(function($) {
				var nonce = '<?php echo wp_create_nonce( 'kanews_setup_wizard' ); ?>';
				
				// Complete step
				$('.kanews-setup-wizard-step-complete').on('click', function() {
					var $button = $(this);
					var step = $button.data('step');
					var $step = $('.kanews-setup-wizard-step[data-step="' + step + '"]');
					
					$button.prop('disabled', true).text('<?php esc_html_e( 'İşleniyor...', 'kanews' ); ?>');
					
					$.ajax({
						url: ajaxurl,
						type: 'POST',
						data: {
							action: 'kanews_setup_complete_step',
							nonce: nonce,
							step: step
						},
						success: function(response) {
							if (response.success) {
								$step.addClass('is-completed');
								updateProgress(response.data.progress);
								location.reload();
							} else {
								alert(response.data.message || '<?php esc_html_e( 'Bir hata oluştu.', 'kanews' ); ?>');
								$button.prop('disabled', false).text('<?php esc_html_e( 'Tamamlandı', 'kanews' ); ?>');
							}
						},
						error: function() {
							alert('<?php esc_html_e( 'Bir hata oluştu.', 'kanews' ); ?>');
							$button.prop('disabled', false).text('<?php esc_html_e( 'Tamamlandı', 'kanews' ); ?>');
						}
					});
				});
				
				// Skip step
				$('.kanews-setup-wizard-step-skip').on('click', function() {
					var $button = $(this);
					var step = $button.data('step');
					var $step = $('.kanews-setup-wizard-step[data-step="' + step + '"]');
					
					if (!confirm('<?php esc_html_e( 'Bu adımı atlamak istediğinizden emin misiniz?', 'kanews' ); ?>')) {
						return;
					}
					
					$button.prop('disabled', true).text('<?php esc_html_e( 'İşleniyor...', 'kanews' ); ?>');
					
					$.ajax({
						url: ajaxurl,
						type: 'POST',
						data: {
							action: 'kanews_setup_skip_step',
							nonce: nonce,
							step: step
						},
						success: function(response) {
							if (response.success) {
								$step.addClass('is-completed');
								updateProgress(response.data.progress);
								location.reload();
							} else {
								alert(response.data.message || '<?php esc_html_e( 'Bir hata oluştu.', 'kanews' ); ?>');
								$button.prop('disabled', false).text('<?php esc_html_e( 'Atla', 'kanews' ); ?>');
							}
						},
						error: function() {
							alert('<?php esc_html_e( 'Bir hata oluştu.', 'kanews' ); ?>');
							$button.prop('disabled', false).text('<?php esc_html_e( 'Atla', 'kanews' ); ?>');
						}
					});
				});
				
				// Dismiss wizard
				$('.kanews-setup-wizard-dismiss').on('click', function() {
					if (!confirm('<?php esc_html_e( 'Kurulum sihirbazını kapatmak istediğinizden emin misiniz?', 'kanews' ); ?>')) {
						return;
					}
					
					var $button = $(this);
					$button.prop('disabled', true).text('<?php esc_html_e( 'İşleniyor...', 'kanews' ); ?>');
					
					$.ajax({
						url: ajaxurl,
						type: 'POST',
						data: {
							action: 'kanews_setup_dismiss',
							nonce: nonce
						},
						success: function(response) {
							if (response.success) {
								location.reload();
							} else {
								alert(response.data.message || '<?php esc_html_e( 'Bir hata oluştu.', 'kanews' ); ?>');
								$button.prop('disabled', false).text('<?php esc_html_e( 'Sihirbazı Kapat', 'kanews' ); ?>');
							}
						},
						error: function() {
							alert('<?php esc_html_e( 'Bir hata oluştu.', 'kanews' ); ?>');
							$button.prop('disabled', false).text('<?php esc_html_e( 'Sihirbazı Kapat', 'kanews' ); ?>');
						}
					});
				});
				
				function updateProgress(progress) {
					$('.kanews-setup-wizard-progress-fill').css('width', progress.percentage + '%');
					$('.kanews-setup-wizard-progress-text').text(
						progress.completed + ' / ' + progress.total + ' <?php esc_html_e( 'adım tamamlandı', 'kanews' ); ?> (' + progress.percentage + '%)'
					);
				}
			});
			</script>
		</div>
		<?php
	}
}

/*-----------------------------------------------------------------------------------*/
# Welcome Page Complete (when 100%)
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( 'kanews_welcome_page_complete' ) ) {
	function kanews_welcome_page_complete(){
		$progress               = kanews_get_setup_progress();
		$setup_toggle_nonce     = wp_create_nonce( 'kanews_setup_wizard_toggle' );
		$review_box_nonce       = wp_create_nonce( 'kanews_review_box' );
		$review_toggle_nonce    = wp_create_nonce( 'kanews_review_box_toggle' );
		$welcome_page_permalink = admin_url( 'admin.php?page=kanews-welcome' );
		$welcome_page_setup_url = add_query_arg( 'kanews_force_setup', 1, $welcome_page_permalink );
		$review_dismissed       = get_option( 'kanews_review_box_dismissed', false );
		$wp_post_counts         = wp_count_posts( 'post' );
		$wp_page_counts         = wp_count_posts( 'page' );
		$wp_comment_counts      = wp_count_comments();
		$wp_user_counts         = count_users();
		$cpt_counts             = array(
			'firma'     => wp_count_posts( 'firma' ),
			'ilan'      => wp_count_posts( 'ilan' ),
			'columnist' => wp_count_posts( 'columnist' ),
		);
		$published_posts   = isset( $wp_post_counts->publish ) ? intval( $wp_post_counts->publish ) : 0;
		$published_pages   = isset( $wp_page_counts->publish ) ? intval( $wp_page_counts->publish ) : 0;
		$approved_comments = isset( $wp_comment_counts->approved ) ? intval( $wp_comment_counts->approved ) : 0;
		$total_users       = isset( $wp_user_counts['total_users'] ) ? intval( $wp_user_counts['total_users'] ) : 0;
		$cpt_stats         = array(
			array(
				'label' => __( 'Firma Kayıtları', 'kanews' ),
				'value' => isset( $cpt_counts['firma']->publish ) ? intval( $cpt_counts['firma']->publish ) : 0,
			),
			array(
				'label' => __( 'İlanlar', 'kanews' ),
				'value' => isset( $cpt_counts['ilan']->publish ) ? intval( $cpt_counts['ilan']->publish ) : 0,
			),
			array(
				'label' => __( 'Köşe Yazarları', 'kanews' ),
				'value' => isset( $cpt_counts['columnist']->publish ) ? intval( $cpt_counts['columnist']->publish ) : 0,
			),
		);
		?>
		<div class="wrap kan__container kanews-wrap">

			<?php kanews_render_admin_header( 'welcome', __( 'Kanews Wordpress temasını tercih ettiğiniz için teşekkür ederiz.', 'kanews' ) ); ?>

					<?php 
			if ( function_exists( 'kanews_render_admin_hero' ) ) {
				$hero_stats = array(
					array(
						'label' => __( 'Tamamlanan Adım', 'kanews' ),
						'value' => sprintf( '%1$d / %2$d', intval( $progress['completed'] ), intval( $progress['total'] ) ),
						'hint'  => __( 'Kurulum adımları', 'kanews' ),
					),
					array(
						'label' => __( 'İlerleme', 'kanews' ),
						'value' => sprintf( '%s%%', intval( $progress['percentage'] ) ),
						'hint'  => __( 'Kurulum sihirbazı', 'kanews' ),
					),
					array(
						'label' => __( 'Değerlendirme', 'kanews' ),
						'value' => $review_dismissed ? __( 'Değerlendirme yapıldı', 'kanews' ) : __( 'Değerlendirme yapılmadı', 'kanews' ),
					),
				);

				$hero_actions = array(
					array(
						'label' => __( 'Dokümantasyonu Gör', 'kanews' ),
						'href'  => 'https://www.kanthemes.com/tema/kanews/dokumantasyon/',
						'target'=> '_blank',
						'class' => 'button button-primary',
					),
				);

				if ( $review_dismissed ) {
					$hero_actions[] = array(
						'label' => __( 'Değerlendirme Yap', 'kanews' ),
						'href'  => '#kanews-review',
						'class' => 'button kanews-review-show',
						'attrs' => array(
							'data-nonce'        => $review_toggle_nonce,
							'data-redirect'     => $welcome_page_permalink . '#kanews-review',
							'data-loading-text' => __( 'Hazırlanıyor...', 'kanews' ),
							'data-default-text' => __( 'Değerlendirme Yap', 'kanews' ),
						),
					);
				}

				kanews_render_admin_hero(
					array(
						'eyebrow'        => __( 'Hoş geldiniz', 'kanews' ),
						'title'          => sprintf( __( 'Kanews %s', 'kanews' ), KAN_THEME_VER ),
						'description'    => __( 'Kanews WordPress teması başarıyla kuruldu ve kullanımınıza hazır. Aşağıdaki adımları takip ederek sitenizi hızlıca yapılandırabilirsiniz.', 'kanews' ),
						'tags'           => array(
							array(
								'value' => null,
								'label' => __( 'AI Haber Botu', 'kanews' ),
							),
							array(
								'value' => null,
								'label' => __( 'AI Araçları', 'kanews' ),
							),
							array(
								'value' => null,
								'label' => __( 'BIK Uyumluluğu', 'kanews' ),
							),
						),
						'actions'        => $hero_actions,
						'stats'          => $hero_stats,
					)
				);
			} else {
				?>
				<div class="kan__section is-feature">
					<div style="text-align: center; padding: 20px 0;">
						<h1 style="font-size: 3.5em; margin: 0 0 16px; font-weight: 700; letter-spacing: -0.02em;">
							<?php printf( __('Kanews %1$s', 'kanews'), KAN_THEME_VER ); ?>
						</h1>
						<p style="font-size: 1.4em; margin: 0; color: rgba(29, 29, 31, 0.7); font-weight: 400;">
							<?php esc_html_e('Modern ve güçlü WordPress haber teması', 'kanews'); ?>
						</p>
						<p style="font-size: 1.1em; margin: 24px auto 0; font-weight: 400; color: rgba(29, 29, 31, 0.6); line-height: 1.6;">
							<?php esc_html_e('Kanews WordPress teması başarıyla kuruldu ve kullanımınıza hazır. Aşağıdaki adımları takip ederek sitenizi hızlıca yapılandırabilirsiniz.', 'kanews'); ?>
					</p>
				</div>
				</div>
				<?php
			}
			?>

			<!-- Review Box -->
			<?php
			if ( ! $review_dismissed ) :
			?>
			<div id="kanews-review" class="kanews-card kanews-card--review kanews-review-box">
				<button type="button" class="kanews-card__close kanews-review-close" title="<?php esc_attr_e( 'Kapat', 'kanews' ); ?>">
					<span class="dashicons dashicons-dismiss"></span>
				</button>
				<div class="kanews-card__layout">
					<div class="kanews-card__content">
						<div class="kanews-card__intro">
							<div class="kanews-card__icon kanews-card__icon--amber">
								<span class="dashicons dashicons-star-filled"></span>
			</div>
							<div>
								<h2 class="kanews-card__title">
									<?php esc_html_e( 'Kanews\'i Beğendiniz mi?', 'kanews' ); ?>
								</h2>
								<p class="kanews-card__subtitle">
									<?php esc_html_e( 'Deneyiminizi bizimle paylaşın ve diğer kullanıcılara yardımcı olun!', 'kanews' ); ?>
								</p>
							</div>
						</div>
						<p class="kanews-card__description">
							<?php esc_html_e( 'Kanews temasını kullanmaktan memnunsanız, lütfen web sitemizde bir değerlendirme bırakın. Bu, temanın gelişimine katkıda bulunur ve diğer kullanıcıların doğru kararı vermesine yardımcı olur.', 'kanews' ); ?>
						</p>
						<div class="kanews-card__actions">
							<a href="https://www.kanthemes.com/urun/kanews-wordpress-haber-temasi/#reviews" target="_blank" class="button button-primary">
								<span class="dashicons dashicons-star-filled"></span>
								<?php esc_html_e( 'Değerlendirme Bırak', 'kanews' ); ?>
							</a>

							<a href="https://www.r10.net/wordpress-temalari/2597840-kanews-wordpress-temasi-yapay-zeka-ucretli-abonelikler-firma-ilan-ve-seoamphiz-optimizasyonu.html" target="_blank" class="button button-primary">
								<span class="dashicons dashicons-star-filled"></span>
								R10 Konumuz
							</a>
							<button type="button" class="button kanews-review-dismiss">
								<?php esc_html_e( 'Daha Sonra', 'kanews' ); ?>
							</button>
		</div>
					</div>
					<div class="kanews-card__aside">
						<div class="kanews-card__visual">
							<div class="kanews-card__stars">
								<?php for ( $i = 1; $i <= 5; $i++ ) : ?>
									<span class="dashicons dashicons-star-filled"></span>
								<?php endfor; ?>
							</div>
							<p class="kanews-card__hint">
								<?php esc_html_e( '5 Yıldız Değerlendirme', 'kanews' ); ?>
							</p>
						</div>
					</div>
				</div>
			</div>
			<?php endif; ?>

			<!-- Hosting Card -->
			<div class="kanews-card kanews-card--panel kanews-card--hosting" style="margin: 24px 0; background: linear-gradient(135deg, #00d4ff 0%, #090979 100%); border: none; box-shadow: 0 8px 24px rgba(0, 212, 255, 0.3); position: relative; overflow: hidden;">
				<div style="position: absolute; top: -50%; right: -50%; width: 200%; height: 200%; background: radial-gradient(circle, rgba(255, 255, 255, 0.1) 0%, transparent 70%); animation: hosting-shimmer 4s infinite;"></div>
				<div class="kanews-card__content" style="display: flex; flex-direction: column; gap: 16px; color: #fff; position: relative; z-index: 1;">
					<div style="display: flex; align-items: center; gap: 12px;">
						<div style="width: 48px; height: 48px; background: rgba(255, 255, 255, 0.25); border-radius: 12px; display: flex; align-items: center; justify-content: center; backdrop-filter: blur(10px); box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);">
							<span class="dashicons dashicons-cloud" style="font-size: 24px; width: 24px; height: 24px; color: #fff; animation: float 3s ease-in-out infinite;"></span>
						</div>
						<div>
							<p class="kanews-card__eyebrow" style="margin: 0 0 4px; font-size: 0.75em; text-transform: uppercase; letter-spacing: 0.05em; opacity: 0.95; font-weight: 700;">Hostinger</p>
							<h2 class="kanews-card__title" style="margin: 0; font-size: 1.5rem; font-weight: 700; letter-spacing: -0.5px; color: #fff; text-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);">
								<?php esc_html_e( 'Hosting Edin', 'kanews' ); ?>
							</h2>
						</div>
					</div>
					<p class="kanews-card__subtitle" style="margin: 0; font-size: 0.95em; opacity: 0.95; line-height: 1.6; color: #fff;">
						<?php esc_html_e( 'Hızlı ve güvenilir hosting çözümü ile sitenizi yüksek performansta çalıştırın. WordPress için optimize edilmiş hosting paketlerimizle tanışın.', 'kanews' ); ?>
					</p>
					<div class="kanews-card__actions" style="margin-top: 8px; display: flex; gap: 10px; flex-wrap: wrap;">
						<a class="button button-primary" target="_blank" rel="noopener noreferrer" href="https://www.hostinger.com.tr/cart?product=hosting%3Ahostinger_premium&period=12&referral_type=cart_link&REFERRALCODE=kanthemes&referral_id=019b043e-2ae4-72cd-ade4-8b317ba441d0" style="background: #fff; color: #090979; border-color: #fff; font-weight: 700; padding: 12px 28px; border-radius: 10px; box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2); transition: all 0.3s ease; text-transform: uppercase; letter-spacing: 0.5px; font-size: 0.9em;">
							<span class="dashicons dashicons-cloud" style="vertical-align: middle; margin-right: 8px; font-size: 18px;"></span>
							<?php esc_html_e( 'Hosting Satın Al', 'kanews' ); ?>
						</a>
						<a class="button" target="_blank" rel="noopener noreferrer" href="https://hostinger.com.tr?REFERRALCODE=kanthemes" style="background: rgba(255, 255, 255, 0.15); color: #fff; border-color: rgba(255, 255, 255, 0.3); font-weight: 600; padding: 12px 24px; border-radius: 10px; backdrop-filter: blur(10px); transition: all 0.3s ease;">
							<?php esc_html_e( 'Paketleri İncele', 'kanews' ); ?>
						</a>
					</div>
				</div>
			</div>

			<!-- Quick Start Cards -->
			<div class="kanews_admin_content">
				<div class="kan__section has-3-columns has-gutters kanews-grid">
					<!-- Setup Card -->
					<div class="column">
						<div class="kanews-card">
						<div class="kanews-progress-circle" style="position: absolute;right: 1em;top:1em">
									<svg class="kanews-progress-svg">
										<circle class="kanews-progress-bg" cx="45" cy="45" r="40" fill="none" stroke="rgba(0, 113, 227, 0.1)" stroke-width="5" stroke-linecap="round"></circle>
										<circle class="kanews-progress-bar" cx="45" cy="45" r="40" fill="none" stroke="url(#kanews-progress-gradient)" stroke-width="5" stroke-linecap="round" stroke-dasharray="<?php echo 2 * M_PI * 40; ?>" stroke-dashoffset="<?php echo 2 * M_PI * 40 * (1 - $progress['percentage'] / 100); ?>"></circle>
									</svg>
									<svg class="kanews-progress-gradient">
										<defs>
											<linearGradient id="kanews-progress-gradient" x1="0%" y1="0%" x2="100%" y2="100%">
												<stop offset="0%" style="stop-color:#0071e3;stop-opacity:1" />
												<stop offset="100%" style="stop-color:#007aff;stop-opacity:1" />
											</linearGradient>
										</defs>
									</svg>
									<div class="kanews-progress-indicator">
										<span class="kanews-progress-percent">
											<?php echo esc_html( $progress['percentage'] ); ?>%
										</span>
										<span class="kanews-progress-count">
											<?php echo esc_html( $progress['completed'] ); ?>/<?php echo esc_html( $progress['total'] ); ?>
										</span>
									</div>
								</div>
							<div class="kanews-card__header">
								<div class="kanews-card__header-text" style="padding-right: 100px">
									<div class="kanews-card__icon kanews-card__icon--blue">
										<span class="dashicons dashicons-admin-settings"></span>
									</div>
									<div>
										<h3 class="kanews-card__title">
											<?php esc_html_e( 'Kurulum & Yapılandırma', 'kanews' ); ?>
										</h3>
										<p class="kanews-card__subtitle">
											<?php esc_html_e( 'Temanızı yapılandırma adımları.', 'kanews' ); ?>
										</p>
									</div>
								</div>
							

							</div>
							<div class="kanews-card__actions kanews-card__actions--inline">
									<button type="button"
										class="button kanews-open-setup"
										data-nonce="<?php echo esc_attr( $setup_toggle_nonce ); ?>"
										data-redirect="<?php echo esc_url( $welcome_page_setup_url ); ?>"
										data-loading-text="<?php echo esc_attr__( 'Açılıyor...', 'kanews' ); ?>"
										data-default-text="<?php echo esc_attr__( 'Kurulum Sihirbazını Aç', 'kanews' ); ?>">
										<?php esc_html_e( 'Kurulum Sihirbazını Aç', 'kanews' ); ?>
									</button>
								</div>
								<br>
							<ul class="kanews-card__list">
				<?php 
							$step_keys = array( 'demo', 'menu', 'options', 'api', 'pages', 'widgets' );
							$step_links = array(
								'demo' => admin_url('admin.php?page=kanews-import'),
								'menu' => admin_url('nav-menus.php'),
								'options' => admin_url('admin.php?page=kanews-options'),
								'api' => admin_url('admin.php?page=kanews-kai#kai-settings'),
								'pages' => admin_url('edit.php?post_type=page'),
								'widgets' => admin_url('widgets.php'),
							);
							$step_icons = array(
								'demo' => 'dashicons-download',
								'menu' => 'dashicons-menu',
								'options' => 'dashicons-admin-appearance',
								'api' => 'dashicons-admin-network',
								'pages' => 'dashicons-admin-page',
								'widgets' => 'dashicons-screenoptions',
							);
							foreach ( $step_keys as $key ) {
								if ( ! isset( $progress['steps'][ $key ] ) ) {
									continue;
								}
								$step = $progress['steps'][ $key ];
								$is_completed = isset( $step['check'] ) ? $step['check'] : false;
								$step_name = isset( $step['name'] ) ? $step['name'] : '';
								$completed_class = $is_completed ? 'kanews-step-completed' : '';
				?>
							<li>
								<a href="<?php echo esc_url( isset( $step_links[ $key ] ) ? $step_links[ $key ] : '#' ); ?>" class="kanews-card__list-link <?php echo esc_attr( $completed_class ); ?>">
									<span class="kanews-card__list-body">
										<?php if ( $is_completed ) : ?>
											<span class="dashicons dashicons-yes-alt"></span>
										<?php else : ?>
											<span class="dashicons <?php echo esc_attr( isset( $step_icons[ $key ] ) ? $step_icons[ $key ] : 'dashicons-admin-settings' ); ?>"></span>
										<?php endif; ?>
										<span class="kanews-card__list-label"><?php echo esc_html( $step_name ); ?></span>
									</span>
									<?php if ( $is_completed ) : ?>
										<span class="kanews-card__status">
											<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
												<circle cx="8" cy="8" r="7" fill="#34c759"/>
												<path d="M5 8L7 10L11 6" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
											</svg>
										</span>
									<?php endif; ?>
								</a>
							</li>
							<?php } ?>
							</ul>
						</div>
		</div>

					<!-- Quick Links Card -->
					<div class="column">
						<div class="kanews-card">
							<div class="kanews-card__header">
								<div class="kanews-card__header-text">
									<div class="kanews-card__icon kanews-card__icon--green">
										<span class="dashicons dashicons-admin-links"></span>
				</div>
									<div>
										<h3 class="kanews-card__title">
											<?php esc_html_e( 'Hızlı Erişim', 'kanews' ); ?>
										</h3>
										<p class="kanews-card__subtitle">
											<?php esc_html_e( 'Yardımcı kaynaklar ve dokümantasyon', 'kanews' ); ?>
										</p>
									</div>
								</div>
							</div>
							<ul class="kanews-card__list">
								<li>
									<a target="_blank" href="https://www.kanthemes.com/tema/kanews/guncellemeler/" class="kanews-card__list-link">
										<span class="kanews-card__list-body">
											<span class="dashicons dashicons-update"></span>
											<?php _e('Güncelleme Notları', 'kanews'); ?>
										</span>
									</a>
								</li>
								<li>
									<a target="_blank" href="https://www.kanthemes.com.tr/files/kanews/kanews-child.zip" class="kanews-card__list-link">
										<span class="kanews-card__list-body">
											<span class="dashicons dashicons-download"></span>
											<?php _e('Child Temayı İndir', 'kanews'); ?>
										</span>
									</a>
								</li>
								<li>
									<a target="_blank" href="https://www.kanthemes.com/urun/kanews-wordpress-haber-temasi/" class="kanews-card__list-link">
										<span class="kanews-card__list-body">
											<span class="dashicons dashicons-download"></span>
											<?php esc_html_e( 'Ürün Linkimiz', 'kanews' ); ?>
										</span>
									</a>
								</li>
								<li>
									<a target="_blank" href="https://www.r10.net/wordpress-temalari/2597840-kanews-wordpress-temasi-yapay-zeka-ucretli-abonelikler-firma-ilan-ve-seoamphiz-optimizasyonu.html" class="kanews-card__list-link">
										<span class="kanews-card__list-body">
											<span class="dashicons dashicons-download"></span>
											R10 Konumuz
										</span>
									</a>
								</li>
					</ul>
				</div>
					</div>

					<!-- Support Card -->
					<div class="column">
						<div class="kanews-card">
							<div class="kanews-card__header">
								<div class="kanews-card__header-text">
									<div class="kanews-card__icon kanews-card__icon--amber">
										<span class="dashicons dashicons-sos"></span>
				</div>
									<div>
										<h3 class="kanews-card__title">
											<?php esc_html_e( 'Destek & Yardım', 'kanews' ); ?>
										</h3>
										<p class="kanews-card__subtitle">
											<?php esc_html_e( 'Yardıma mı ihtiyacınız var? Bizimle iletişime geçin', 'kanews' ); ?>
										</p>
			</div>
		</div>
							</div>
							<div class="kanews-card__stacked-actions">
								<a class="button button-primary" href="https://www.kanthemes.com/destek/" target="_blank">
									<?php _e('Destek Talebi Oluştur', 'kanews'); ?>
								</a>
								<a class="button button-secondary" href="https://www.kanthemes.com/tema/kanews/dokumantasyon/" target="_blank">
									<?php _e('Çevrimiçi Dökümantasyon', 'kanews'); ?>
								</a>
							</div>
						</div>

						<div class="kanews-card kanews-card--panel kanews-card--codezen">
							<div class="kanews-card__content" style="display: flex;flex-direction: column;gap: 10px;">
								<p class="kanews-card__eyebrow">Codezenic</p>
								<h2 class="kanews-card__title" style="    font-size: 1.5rem;
    font-weight: 600;
    letter-spacing: -0.5px;">
									<?php esc_html_e( 'WordPress Danışmanlık & Destek', 'kanews' ); ?>
								</h2>
								<p class="kanews-card__subtitle" style="    opacity: .75;">
									<?php esc_html_e( 'Performans optimizasyonu, özel tema geliştirme ve KAI entegrasyonlarında tek tıkla destek alın.', 'kanews' ); ?>
								</p>
								<div class="kanews-card__actions">
									<a class="button button-primary" target="_blank" rel="noopener noreferrer" href="https://www.codezenic.com/services/bakim-destek/">
										<?php esc_html_e( 'Hemen Teklif Al', 'kanews' ); ?>
									</a>
				</div>
		</div>
						</div>
					</div>
				</div>
			</div>

	



			<div class="kanews_admin_stats">
				<div class="kan__section has-2-columns has-gutters kanews-grid">
					<div class="column">
						<div class="kanews-card kanews-card--panel">
							<h3 class="kanews-card__title"><?php esc_html_e( 'WordPress İstatistikleri', 'kanews' ); ?></h3>
							<ul class="kanews-card__list">
								<li>
									<div class="kanews-card__list-body">
										<span class="kanews-card__list-label"><?php esc_html_e( 'Yayınlanan Yazılar', 'kanews' ); ?></span>
									</div>
									<span class="kanews-card__status"><?php echo esc_html( number_format_i18n( $published_posts ) ); ?></span>
								</li>
								<li>
									<div class="kanews-card__list-body">
										<span class="kanews-card__list-label"><?php esc_html_e( 'Yayınlanan Sayfalar', 'kanews' ); ?></span>
									</div>
									<span class="kanews-card__status"><?php echo esc_html( number_format_i18n( $published_pages ) ); ?></span>
								</li>
								<li>
									<div class="kanews-card__list-body">
										<span class="kanews-card__list-label"><?php esc_html_e( 'Onaylı Yorumlar', 'kanews' ); ?></span>
									</div>
									<span class="kanews-card__status"><?php echo esc_html( number_format_i18n( $approved_comments ) ); ?></span>
								</li>
								<li>
									<div class="kanews-card__list-body">
										<span class="kanews-card__list-label"><?php esc_html_e( 'Toplam Kullanıcı', 'kanews' ); ?></span>
									</div>
									<span class="kanews-card__status"><?php echo esc_html( number_format_i18n( $total_users ) ); ?></span>
								</li>
							</ul>
						</div>
					</div>
					<div class="column">
						<div class="kanews-card kanews-card--panel">
							<h3 class="kanews-card__title"><?php esc_html_e( 'Özel İçerik Tipleri', 'kanews' ); ?></h3>
							<ul class="kanews-card__list">
							<?php foreach ( $cpt_stats as $cpt_stat ) : ?>
								<li>
									<div class="kanews-card__list-body">
										<span class="kanews-card__list-label"><?php echo esc_html( $cpt_stat['label'] ); ?></span>
									</div>
									<span class="kanews-card__status"><?php echo esc_html( number_format_i18n( $cpt_stat['value'] ) ); ?></span>
								</li>
							<?php endforeach; ?>
							</ul>
						</div>
					</div>
				</div>
	</div>

			<div class="kanews-card__panel-footer">
					<a href="https://bit.ly/34PKAWt" target="_blank" class="button">
						<?php esc_html_e('Faydalı İçerikler', 'kanews'); ?>
					</a>
					<a href="https://twitter.com/share?ref_src=twsrc%5Etfw" class="twitter-share-button" data-size="large" data-text="Kanews Wordpress temasını siteme kurdum, sizede tavsiye ederim." data-url="https://www.kanthemes.com/tanitim/kanews/" data-via="kanthemes" data-hashtags="kanewswptheme" data-show-count="false" target="_blank">
						<?php esc_html_e('Tweet', 'kanews'); ?>
					</a>
					<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
				</div>

			<script type="text/javascript">
			jQuery(function($) {
				if ( typeof ajaxurl === 'undefined' ) {
					return;
				}

				var reviewDismissNonce = '<?php echo esc_js( $review_box_nonce ); ?>';
				var reviewReloadUrl    = '<?php echo esc_js( $welcome_page_permalink . '#kanews-review' ); ?>';
				var setupRedirectUrl   = '<?php echo esc_js( $welcome_page_setup_url ); ?>';

				function navigateWithRefresh(url) {
					var target = url || window.location.href;
					var parts  = target.split('#');
					var base   = parts[0];
					var hash   = parts[1] ? '#' + parts[1] : '';

					var separator = base.indexOf('?') === -1 ? '?' : '&';
					base += separator + 'kanews_refresh=' + Date.now();

					window.location.href = base + hash;
				}

				function setLoadingState($el, isLoading) {
					if ( ! $el || ! $el.length ) {
						return;
					}

					if ( isLoading ) {
						if ( $el.data('loading-text') ) {
							if ( ! $el.data('original-html') ) {
								$el.data('original-html', $el.html());
							}
							$el.html( $el.data('loading-text') );
						}
						$el.attr('aria-disabled', 'true').addClass('is-loading');
					} else {
						if ( $el.data('loading-text') && $el.data('original-html') ) {
							$el.html( $el.data('original-html') );
						}
						$el.removeAttr('aria-disabled').removeClass('is-loading');
					}
				}

				$('.kanews-review-dismiss, .kanews-review-close').on('click', function(event) {
					event.preventDefault();
					var $trigger = $(this);
					setLoadingState($trigger, true);

					$.post(ajaxurl, {
						action: 'kanews_dismiss_review_box',
						nonce: reviewDismissNonce
					}).done(function(response) {
						if ( response && response.success ) {
							navigateWithRefresh(reviewReloadUrl);
							return;
						}
						alert((response && response.data && response.data.message) || '<?php echo esc_js( __( 'Bir hata oluştu.', 'kanews' ) ); ?>');
						setLoadingState($trigger, false);
					}).fail(function() {
						alert('<?php echo esc_js( __( 'Bir hata oluştu.', 'kanews' ) ); ?>');
						setLoadingState($trigger, false);
					});
				});

				$('.kanews-review-show').on('click', function(event) {
					event.preventDefault();
					var $button  = $(this);
					var nonce    = $button.data('nonce');
					var redirect = $button.data('redirect') || reviewReloadUrl;

					setLoadingState($button, true);

					$.post(ajaxurl, {
						action: 'kanews_show_review_box',
						nonce: nonce
					}).done(function(response) {
						if ( response && response.success ) {
							navigateWithRefresh(redirect);
							return;
						}
						alert((response && response.data && response.data.message) || '<?php echo esc_js( __( 'Bir hata oluştu.', 'kanews' ) ); ?>');
						setLoadingState($button, false);
					}).fail(function() {
						alert('<?php echo esc_js( __( 'Bir hata oluştu.', 'kanews' ) ); ?>');
						setLoadingState($button, false);
					});
				});

				$('.kanews-open-setup').on('click', function(event) {
					event.preventDefault();
					var $button  = $(this);
					var nonce    = $button.data('nonce');
					var redirect = $button.data('redirect') || setupRedirectUrl;

					setLoadingState($button, true);

					$.post(ajaxurl, {
						action: 'kanews_show_setup_wizard',
						nonce: nonce
					}).done(function(response) {
						if ( response && response.success ) {
							navigateWithRefresh(redirect);
							return;
						}
						alert((response && response.data && response.data.message) || '<?php echo esc_js( __( 'Bir hata oluştu.', 'kanews' ) ); ?>');
						setLoadingState($button, false);
					}).fail(function() {
						alert('<?php echo esc_js( __( 'Bir hata oluştu.', 'kanews' ) ); ?>');
						setLoadingState($button, false);
					});
				});
			});
			</script>

		</div>
		<?php
	}
}

/*-----------------------------------------------------------------------------------*/
# Page: Updates
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( 'kanews_updates_page' ) ) {
	function kanews_updates_page(){
		if ( isset( $_POST['theme_update_auth'] ) && isset( $_POST['kanews_update_auth_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['kanews_update_auth_nonce'] ) ), 'kanews_save_update_auth' ) ) {
			$order_auth = isset( $_POST['order_auth'] ) ? sanitize_text_field( wp_unslash( $_POST['order_auth'] ) ) : '';
			update_option( 'kanews_order_auth', $order_auth );
		}

		$auth          = get_option( 'kanews_order_auth', '' );
		$release_notes = array(
			array(
				'version' => '8.0',
				'url'     => 'https://www.kanthemes.com/tema/kanews/guncellemeler/#v_80',
			),
			array(
				'version' => '7.5',
				'url'     => 'https://www.kanthemes.com/tema/kanews/guncellemeler/#v_75',
			),
			array(
				'version' => '7.3',
				'url'     => 'https://www.kanthemes.com/tema/kanews/guncellemeler/#v_73',
			),
			array(
				'version' => '7.2',
				'url'     => 'https://www.kanthemes.com/tema/kanews/guncellemeler/#v_72',
			),
			array(
				'version' => '7.1.1',
				'url'     => 'https://www.kanthemes.com/tema/kanews/guncellemeler/#v_711',
			),
			array(
				'version' => '7.1',
				'url'     => 'https://www.kanthemes.com/tema/kanews/guncellemeler/#v_71',
			),
			array(
				'version' => '7.0',
				'url'     => 'https://www.kanthemes.com/tema/kanews/guncellemeler/#v_70',
			),
			array(
				'version' => '6.8',
				'url'     => 'https://www.kanthemes.com/tema/kanews/guncellemeler/#v_68',
			),
			array(
				'version' => '6.7.2',
				'url'     => 'https://www.kanthemes.com/tema/kanews/guncellemeler/#v_672',
			),
		);
		$auto_steps = array(
			__( 'update-core ekranında kontrolü tetikleyin ve Kanews için güncelleme uyarısını görün.', 'kanews' ),
			__( 'Görünüm → Temalar ekranında Kanews kartındaki “Hemen Güncelle” bağlantısına tıklayın.', 'kanews' ),
			__( 'İşlem tamamlandıktan sonra ön belleği temizleyin ve ana sayfayı doğrulayın.', 'kanews' ),
		);
		$manual_steps = array(
			__( 'Kanthemes hesabınızdan son sürüm kanews.zip dosyasını indirin.', 'kanews' ),
			__( 'WordPress üzerinde “Görünüm → Temalar → Yeni Ekle → Tema Yükle” yolunu izleyin.', 'kanews' ),
			__( 'İndirilen dosyayı seçerek yükleyin ve “Mevcut olanı yüklenen ile değiştir” seçeneğini onaylayın.', 'kanews' ),
			__( 'FTP üzerinde child tema veya özelleştirmeleriniz varsa güncel dosyayla eşleştirin.', 'kanews' ),
			__( 'WP Rocket / LiteSpeed Cache benzeri çözümler kullanıyorsanız tüm cache’leri temizleyin.', 'kanews' ),
		);
		$auto_steps = array(
			__( 'update-core ekranında kontrolü tetikleyin ve Kanews için güncelleme uyarısını görün.', 'kanews' ),
			__( 'Görünüm → Temalar ekranında Kanews kartındaki “Hemen Güncelle” bağlantısına tıklayın.', 'kanews' ),
			__( 'İşlem tamamlandıktan sonra ön belleği temizleyin ve ana sayfayı doğrulayın.', 'kanews' ),
		);
		$manual_steps = array(
			__( 'Kanthemes hesabınızdan son sürüm kanews.zip dosyasını indirin.', 'kanews' ),
			__( 'WordPress üzerinde “Görünüm → Temalar → Yeni Ekle → Tema Yükle” yolunu izleyin.', 'kanews' ),
			__( 'İndirilen dosyayı seçerek yükleyin ve “Mevcut olanı yüklenen ile değiştir” seçeneğini onaylayın.', 'kanews' ),
			__( 'FTP üzerinde child tema veya özelleştirmeleriniz varsa güncel dosyayla eşleştirin.', 'kanews' ),
			__( 'WP Rocket / LiteSpeed Cache benzeri çözümler kullanıyorsanız tüm cache’leri temizleyin.', 'kanews' ),
		);

		?>
		<div class="wrap kan__container kanews-wrap">

			<?php kanews_render_admin_header( 'update', __( 'Kanews\'in en son yayınlanan güncellemesini buradan indirip yükleyebilirsiniz.', 'kanews' ) ); ?>

						<?php 
			if ( function_exists( 'kanews_render_admin_hero' ) ) {
				$hero_stats = array(
					array(
						'label' => __( 'Yüklü Sürüm', 'kanews' ),
						'value' => KAN_THEME_VER,
						'hint'  => __( 'Güncel tema sürümünüz', 'kanews' ),
					),
					array(
						'label' => __( 'Son Kontrol', 'kanews' ),
						'value' => esc_html( date_i18n( get_option( 'date_format' ) ) ),
						'hint'  => __( 'update-core üzerinden', 'kanews' ),
					),
				);
				kanews_render_admin_hero(
					array(
						'eyebrow'     => __( 'Kanews Güncellemeleri', 'kanews' ),
						'title'       => __( 'Sitenizi güncel ve güvenli tutun', 'kanews' ),
						'description' => __( 'Otomatik anahtar doğrulama ve manuel yükleme yönergeleri ile Kanews güncellemelerini birkaç adımda tamamlayın.', 'kanews' ),
						'actions'     => array(
							array(
								'label' => __( 'Güncellemeleri Denetle', 'kanews' ),
								'href'  => admin_url( 'update-core.php?force-check=1' ),
								'class' => 'button button-primary',
							),
							array(
								'label'  => __( 'Güncelleme Notları', 'kanews' ),
								'href'   => 'https://www.kanthemes.com/tema/kanews/guncellemeler/',
								'target' => '_blank',
								'class'  => 'button',
							),
						),
						'stats'       => $hero_stats,
					)
				);
			}
			?>

			<div class="kanews_admin_content">
				<div class="kan__section has-2-columns has-gutters kanews-grid">
					<div class="column">
						<div class="kanews-card">
							<div class="kanews-card__header">
								<div class="kanews-card__header-text">
									<div class="kanews-card__icon kanews-card__icon--blue">
										<span class="dashicons dashicons-admin-network"></span>
									</div>
									<div>
										<h3 class="kanews-card__title"><?php esc_html_e( 'Güncelleme Anahtarını Kaydet', 'kanews' ); ?></h3>
										<p class="kanews-card__subtitle">
											<?php esc_html_e( 'Aşağıdaki adımları tamamlayarak otomatik güncelleme servisini etkinleştirin.', 'kanews' ); ?>
						</p>
					</div>
				</div>
			</div>
							<ul class="kanews-progress-list">
								<li>
									<span class="kanews-progress-list__badge">1</span>
									<div class="kanews-progress-list__content">
										<p><?php esc_html_e( 'Kanthemes hesabınıza giriş yapın ve Hesabım / Siparişler sayfasını açın.', 'kanews' ); ?></p>
									</div>
								</li>
								<li>
									<span class="kanews-progress-list__badge">2</span>
									<div class="kanews-progress-list__content">
										<p><?php esc_html_e( 'Kanews siparişinizde yer alan lisans anahtarını kopyalayın.', 'kanews' ); ?></p>
									</div>
								</li>
								<li>
									<span class="kanews-progress-list__badge">3</span>
									<div class="kanews-progress-list__content">
										<p><?php esc_html_e( 'Anahtarı aşağıdaki alana yapıştırıp Kaydet butonuna tıklayın.', 'kanews' ); ?></p>
									</div>
								</li>
							</ul>
							<form method="post" action="<?php echo esc_url( admin_url( 'admin.php?page=kanews-update' ) ); ?>" class="kanews-form">
								<?php wp_nonce_field( 'kanews_save_update_auth', 'kanews_update_auth_nonce' ); ?>
								<input class="widefat" type="text" name="order_auth" value="<?php echo esc_attr( $auth ); ?>" placeholder="<?php esc_attr_e( 'Güncelleme anahtarınız', 'kanews' ); ?>" required />
							<input type="hidden" name="theme_update_auth" value="update" />
								<div class="kanews-card__actions">
									<button type="submit" class="button button-primary">
										<?php esc_html_e( 'Anahtarı Kaydet', 'kanews' ); ?>
									</button>
									<a class="button" target="_blank" rel="noopener noreferrer" href="https://www.kanthemes.com/hesabim/siparisler/">
										<?php esc_html_e( 'Anahtar Yardımı', 'kanews' ); ?>
									</a>
								</div>
						</form>
					</div>

					<div class="kanews-card kanews-card--panel">
							<div class="kanews-card__header">
								<div class="kanews-card__header-text">
									<div class="kanews-card__icon kanews-card__icon--amber">
										<span class="dashicons dashicons-cloud-upload"></span>
					</div>
									<div>
										<h3 class="kanews-card__title"><?php esc_html_e( 'Manuel Yükleme Adımları', 'kanews' ); ?></h3>
										<p class="kanews-card__subtitle">
											<?php esc_html_e( 'FTP veya WP arayüzü üzerinden paket yükleyerek güncellemeyi tamamlayın.', 'kanews' ); ?>
										</p>
					</div>
				</div>
							</div>
							<ul class="kanews-progress-list">
								<?php
								$manual_index = 1;
								foreach ( $manual_steps as $step_text ) :
									?>
									<li>
										<span class="kanews-progress-list__badge"><?php echo esc_html( $manual_index ); ?></span>
										<div class="kanews-progress-list__content">
											<p><?php echo esc_html( $step_text ); ?></p>
										</div>
									</li>
									<?php
									$manual_index++;
								endforeach;
								?>
							</ul>
				</div>

		
				</div>

					<div class="column">
			

						<div class="kanews-card kanews-card--panel">
							<div class="kanews-card__header">
								<div class="kanews-card__header-text">

									<div>
										<h3 class="kanews-card__title"><?php esc_html_e( 'Kaynaklar & Notlar', 'kanews' ); ?></h3>
										<p class="kanews-card__subtitle">
											<?php esc_html_e( 'Son sürüm notları, video rehber ve destek bağlantılarını buradan takip edin.', 'kanews' ); ?>
					</p>
					</div>
					</div>
							</div>
							<ul class="kanews-card__list kanews-card__list--link">
								<?php foreach ( $release_notes as $note ) : ?>
									<li>
										<a class="kanews-card__list-link" target="_blank" rel="noopener noreferrer" href="<?php echo esc_url( $note['url'] ); ?>">
											<span class="kanews-card__list-body">
												<span class="dashicons dashicons-media-document"></span>
												<span><?php printf( esc_html__( 'Sürüm %s notları', 'kanews' ), esc_html( $note['version'] ) ); ?></span>
											</span>
											<span class="kanews-card__status"><?php esc_html_e( 'Oku', 'kanews' ); ?></span>
										</a>
									</li>
								<?php endforeach; ?>
							</ul>
						</div>

						<div class="kanews-card">
							<div class="kanews-card__header">
								<div class="kanews-card__header-text">
									<div class="kanews-card__icon kanews-card__icon--green">
										<span class="dashicons dashicons-update"></span>
									</div>
									<div>
										<h3 class="kanews-card__title"><?php esc_html_e( 'Otomatik Güncelleme Akışı', 'kanews' ); ?></h3>
										<p class="kanews-card__subtitle">
											<?php esc_html_e( 'update-core üzerinden tek tıkla kontrol edip Kanews’i WP panelinden güncelleyin.', 'kanews' ); ?>
						</p>
					</div>
					</div>
				</div>
							<ul class="kanews-progress-list">
								<?php
								$step_index = 1;
								foreach ( $auto_steps as $step_text ) :
									?>
									<li>
										<span class="kanews-progress-list__badge"><?php echo esc_html( $step_index ); ?></span>
										<div class="kanews-progress-list__content">
											<p><?php echo esc_html( $step_text ); ?></p>
					</div>
									</li>
									<?php
									$step_index++;
								endforeach;
								?>
							</ul>
							<div class="kanews-card__actions">
								<a class="button button-primary" href="<?php echo esc_url( admin_url( 'themes.php' ) ); ?>" target="_blank">
									<?php esc_html_e( 'Temalar Sayfasını Aç', 'kanews' ); ?>
								</a>
				</div>
					</div>
				</div>

			</div>
		</div>
		</div>
		<?php
	}
}

/*-----------------------------------------------------------------------------------*/
# Page: Demo Importer
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( 'kanews_compaitable_plugins' ) ) {
	function kanews_compaitable_plugins(){ ?>
	<div class="wrap s-wrap">
		<h2><?php _e('Uyumlu Eklentiler', 'kanews'); ?></h2>
	<p><?php esc_html_e( 'Bu eklentilerin kurulması zorunlu değildir, ihtiyacınıza göre tam uyumluluk gösteren bu eklentileri kullanabilirsiniz.', 'kanews' ); ?></p><br>
				<table class="wp-list-table widefat fixed">
					<thead>
						<tr>
							<th scope="col" id="plugin" class="manage-column column-plugin column-primary"><?php _e('Plugin'); ?></th>
							<th scope="col" id="tur" class="manage-column column-tur"><?php _e('Type'); ?></th>
							<th scope="col" id="status" class="manage-column column-status"><?php _e('Status'); ?></th>
						</tr>
					</thead>
					<tbody id="one-list">
						<tr>
							<td class="plugin column-plugin has-row-actions column-primary" data-colname="Plugin">
								<strong><a target="_blank" href="<?php echo admin_url('themes.php?page=tgmpa-install-plugins'); ?>" class="thickbox">
								Kanews Hikayeler</a></strong>
							</td>
							<td class="source column-tur" data-colname="Tur"><?php _e('Özelleştirme', 'kanews'); ?></td>
							<td class="source column-status" data-colname="status">
								<a target="_blank" class="install-now button" href="<?php echo admin_url('themes.php?page=tgmpa-install-plugins'); ?>"><?php _e('Hemen yükle', 'kanews'); ?></a>
							</td>
						</tr>
						<tr>
							<td class="plugin column-plugin has-row-actions column-primary" data-colname="Plugin">
								<strong><a target="_blank" href="<?php $plugin = 'amp'; echo admin_url('plugin-install.php?tab=plugin-information&amp;plugin='.$plugin.'&amp;TB_iframe=true&amp;width=640&amp;height=500'); ?>" class="thickbox">
								AMP</a></strong>
							</td>
							<td class="source column-tur" data-colname="Tur"><?php _e('Seo', 'kanews'); ?></td>
							<td class="source column-status" data-colname="status">
								<a target="_blank" class="install-now button" href="<?php $plugin = 'amp'; echo admin_url('plugin-install.php?tab=plugin-information&amp;plugin='.$plugin.'&amp;TB_iframe=true&amp;width=640&amp;height=500'); ?>"><?php _e('Hemen yükle', 'kanews'); ?></a>
							</td>
						</tr>
						<tr>
							<td class="plugin column-plugin has-row-actions column-primary" data-colname="Plugin">
								<strong><a target="_blank" href="<?php $plugin = 'litespeed-cache'; echo admin_url('plugin-install.php?tab=plugin-information&amp;plugin='.$plugin.'&amp;TB_iframe=true&amp;width=640&amp;height=500'); ?>" class="thickbox">
								Litespeed Cache</a></strong>
							</td>
							<td class="source column-tur" data-colname="Tur"><?php _e('Hız', 'kanews'); ?></td>
							<td class="source column-status" data-colname="status">
								<a target="_blank" class="install-now button" href="<?php $plugin = 'litespeed-cache'; echo admin_url('plugin-install.php?tab=plugin-information&amp;plugin='.$plugin.'&amp;TB_iframe=true&amp;width=640&amp;height=500'); ?>"><?php _e('Hemen yükle', 'kanews'); ?></a>
							</td>
						</tr>
						<tr>
							<td class="plugin column-plugin has-row-actions column-primary" data-colname="Plugin">
								<strong><a target="_blank" href="<?php $plugin = 'seo-by-rank-math'; echo admin_url('plugin-install.php?tab=plugin-information&amp;plugin='.$plugin.'&amp;TB_iframe=true&amp;width=640&amp;height=500'); ?>" class="thickbox">
								Rank Math – SEO Plugin for WordPress</a></strong>
							</td>
							<td class="source column-tur" data-colname="Tur"><?php _e('Seo', 'kanews'); ?></td>
							<td class="source column-status" data-colname="status">
								<a target="_blank" class="install-now button" href="<?php $plugin = 'seo-by-rank-math'; echo admin_url('plugin-install.php?tab=plugin-information&amp;plugin='.$plugin.'&amp;TB_iframe=true&amp;width=640&amp;height=500'); ?>"><?php _e('Hemen yükle', 'kanews'); ?></a>
							</td>
						</tr>
						<tr>
							<td class="plugin column-plugin has-row-actions column-primary" data-colname="Plugin">
								<strong><a target="_blank" href="<?php $plugin = 'wordpress-seo'; echo admin_url('plugin-install.php?tab=plugin-information&amp;plugin='.$plugin.'&amp;TB_iframe=true&amp;width=640&amp;height=500'); ?>" class="thickbox">
								Wordpress Seo by Yoast</a></strong>
							</td>
							<td class="source column-tur" data-colname="Tur"><?php _e('Seo', 'kanews'); ?></td>
							<td class="source column-status" data-colname="status">
								<a target="_blank" class="install-now button" href="<?php $plugin = 'wordpress-seo'; echo admin_url('plugin-install.php?tab=plugin-information&amp;plugin='.$plugin.'&amp;TB_iframe=true&amp;width=640&amp;height=500'); ?>"><?php _e('Hemen yükle', 'kanews'); ?></a>
							</td>
						</tr>
						<tr>
							<td class="plugin column-plugin has-row-actions column-primary" data-colname="Plugin">
								<strong><a target="_blank" href="<?php $plugin = 'contact-form-7'; echo admin_url('plugin-install.php?tab=plugin-information&amp;plugin='.$plugin.'&amp;TB_iframe=true&amp;width=640&amp;height=500'); ?>" class="thickbox">
								Contact Form 7</a></strong>
							</td>
							<td class="source column-tur" data-colname="Tur"><?php _e('İletişim', 'kanews'); ?></td>
							<td class="source column-status" data-colname="status">
								<a target="_blank" class="install-now button" href="<?php $plugin = 'contact-form-7'; echo admin_url('plugin-install.php?tab=plugin-information&amp;plugin='.$plugin.'&amp;TB_iframe=true&amp;width=640&amp;height=500'); ?>"><?php _e('Hemen yükle', 'kanews'); ?></a>
							</td>
						</tr>
						<tr>
							<td class="plugin column-plugin has-row-actions column-primary" data-colname="Plugin">
								<strong><a target="_blank" href="<?php $plugin = 'wp-smushit'; echo admin_url('plugin-install.php?tab=plugin-information&amp;plugin='.$plugin.'&amp;TB_iframe=true&amp;width=640&amp;height=500'); ?>" class="thickbox">
								Smush</a></strong>
							</td>
							<td class="source column-tur" data-colname="Tur"><?php _e('Optimizasyon', 'kanews'); ?></td>
							<td class="source column-status" data-colname="status">
								<a target="_blank" class="install-now button" href="<?php $plugin = 'wp-smushit'; echo admin_url('plugin-install.php?tab=plugin-information&amp;plugin='.$plugin.'&amp;TB_iframe=true&amp;width=640&amp;height=500'); ?>"><?php _e('Hemen yükle', 'kanews'); ?></a>
							</td>
						</tr>
						<tr>
							<td class="plugin column-plugin has-row-actions column-primary" data-colname="Plugin">
								<strong><a target="_blank" href="<?php $plugin = 'table-of-contents-plus'; echo admin_url('plugin-install.php?tab=plugin-information&amp;plugin='.$plugin.'&TB_iframe=true&width=600&height=550'); ?>" class="thickbox">
								Table of Contents Plus</a></strong>
							</td>
							<td class="source column-tur" data-colname="Tur"><?php _e('Özelleştirme', 'kanews'); ?></td>
							<td class="source column-status" data-colname="status">
								<a target="_blank" class="install-now button" href="<?php $plugin = 'table-of-contents-plus'; echo admin_url('plugin-install.php?tab=plugin-information&amp;plugin='.$plugin.'&amp;TB_iframe=true&amp;width=640&amp;height=500'); ?>"><?php _e('Hemen yükle', 'kanews'); ?></a>
							</td>
						</tr>
						<tr>
							<td class="plugin column-plugin has-row-actions column-primary" data-colname="Plugin">
								<strong><a target="_blank" href="<?php $plugin = 'nextend-facebook-connect'; echo admin_url('plugin-install.php?tab=plugin-information&amp;plugin='.$plugin.'&TB_iframe=true&width=600&height=550'); ?>" class="thickbox">
								Nextend Social Login</a></strong>
							</td>
							<td class="source column-tur" data-colname="Tur"><?php _e('Özelleştirme', 'kanews'); ?></td>
							<td class="source column-status" data-colname="status">
								<a target="_blank" class="install-now button" href="<?php $plugin = 'nextend-facebook-connect'; echo admin_url('plugin-install.php?tab=plugin-information&amp;plugin='.$plugin.'&amp;TB_iframe=true&amp;width=640&amp;height=500'); ?>"><?php _e('Hemen yükle', 'kanews'); ?></a>
							</td>
						</tr>
						<tr>
							<td class="plugin column-plugin has-row-actions column-primary" data-colname="Plugin">
								<strong><a target="_blank" href="<?php $plugin = 'google-captcha'; echo admin_url('plugin-install.php?tab=plugin-information&amp;plugin='.$plugin.'&TB_iframe=true&width=600&height=550'); ?>" class="thickbox">
								Google Captcha (reCAPTCHA)</a></strong>
							</td>
							<td class="source column-tur" data-colname="Tur"><?php _e('Güvenlik', 'kanews'); ?></td>
							<td class="source column-status" data-colname="status">
								<a target="_blank" class="install-now button" href="<?php $plugin = 'google-captcha'; echo admin_url('plugin-install.php?tab=plugin-information&amp;plugin='.$plugin.'&amp;TB_iframe=true&amp;width=640&amp;height=500'); ?>"><?php _e('Hemen yükle', 'kanews'); ?></a>
							</td>
						</tr>
						<tr>
							<td class="plugin column-plugin has-row-actions column-primary" data-colname="Plugin">
								<strong><a target="_blank" href="<?php $plugin = 'simple-cloudflare-turnstile'; echo admin_url('plugin-install.php?tab=plugin-information&amp;plugin='.$plugin.'&TB_iframe=true&width=600&height=550'); ?>" class="thickbox">
								Simple Cloudflare Turnstile</a></strong>
							</td>
							<td class="source column-tur" data-colname="Tur"><?php _e('Güvenlik', 'kanews'); ?></td>
							<td class="source column-status" data-colname="status">
								<a target="_blank" class="install-now button" href="<?php $plugin = 'simple-cloudflare-turnstile'; echo admin_url('plugin-install.php?tab=plugin-information&amp;plugin='.$plugin.'&amp;TB_iframe=true&amp;width=640&amp;height=500'); ?>"><?php _e('Hemen yükle', 'kanews'); ?></a>
							</td>
						</tr>
						<tr>
							<td class="plugin column-plugin has-row-actions column-primary" data-colname="Plugin">
								<strong><a target="_blank" href="<?php $plugin = 'post-views-counter'; echo admin_url('plugin-install.php?tab=plugin-information&amp;plugin='.$plugin.'&TB_iframe=true&width=600&height=550'); ?>" class="thickbox">
								Post Views Counter</a></strong>
							</td>
							<td class="source column-tur" data-colname="Tur"><?php _e('Özelleştirme', 'kanews'); ?></td>
							<td class="source column-status" data-colname="status">
								<a target="_blank" class="install-now button" href="<?php $plugin = 'post-views-counter'; echo admin_url('plugin-install.php?tab=plugin-information&amp;plugin='.$plugin.'&amp;TB_iframe=true&amp;width=640&amp;height=500'); ?>"><?php _e('Hemen yükle', 'kanews'); ?></a>
							</td>
						</tr>
						<tr>
							<td class="plugin column-plugin has-row-actions column-primary" data-colname="Plugin">
								<strong><a target="_blank" href="<?php $plugin = 'co-authors-plus'; echo admin_url('plugin-install.php?tab=plugin-information&amp;plugin='.$plugin.'&TB_iframe=true&width=600&height=550'); ?>" class="thickbox">
								Co-Authors Plus</a></strong>
							</td>
							<td class="source column-tur" data-colname="Tur"><?php _e('Özelleştirme', 'kanews'); ?></td>
							<td class="source column-status" data-colname="status">
								<a target="_blank" class="install-now button" href="<?php $plugin = 'co-authors-plus'; echo admin_url('plugin-install.php?tab=plugin-information&amp;plugin='.$plugin.'&amp;TB_iframe=true&amp;width=640&amp;height=500'); ?>"><?php _e('Hemen yükle', 'kanews'); ?></a>
							</td>
						</tr>
						<tr>
							<td class="plugin column-plugin has-row-actions column-primary" data-colname="Plugin">
								<strong><a target="_blank" href="<?php $plugin = 'simple-custom-post-order'; echo admin_url('plugin-install.php?tab=plugin-information&amp;plugin='.$plugin.'&TB_iframe=true&width=600&height=550'); ?>" class="thickbox">
								Simple Custom Post Order</a></strong>
							</td>
							<td class="source column-tur" data-colname="Tur"><?php _e('Özelleştirme', 'kanews'); ?></td>
							<td class="source column-status" data-colname="status">
								<a target="_blank" class="install-now button" href="<?php $plugin = 'simple-custom-post-order'; echo admin_url('plugin-install.php?tab=plugin-information&amp;plugin='.$plugin.'&amp;TB_iframe=true&amp;width=640&amp;height=500'); ?>"><?php _e('Hemen yükle', 'kanews'); ?></a>
							</td>
						</tr>
					</tbody>
				</table>
				</div>
	<?php }
}

/*-----------------------------------------------------------------------------------*/
# Page: Demo Importer
/*-----------------------------------------------------------------------------------*/
if ( ! function_exists( 'kanews_demo_importer_page' ) ) {
	function kanews_demo_importer_page(){
		$demo_packages    = function_exists( 'kanews_import_files' ) ? kanews_import_files() : array();
		$demo_showcase    = array_slice( $demo_packages, 0, 4 );
		$plugin_steps     = array(
			__( 'WooCommerce eklentisini kurarak ücretli abonelik akışını hazır hale getirin (isteğe bağlı).', 'kanews' ),
			__( 'One Click Demo Import eklentisini kurup etkinleştirin.', 'kanews' ),
			__( 'Import ekranında kurmak istediğiniz demoyu seçin ve işlemi başlatın.', 'kanews' ),
		);
		$import_tips      = array(
			__( 'Import süresince sayfayı kapatmayın, tamamlandığında başarı mesajını bekleyin.', 'kanews' ),
			__( 'Menüler, widget alanları ve medya içerikleri otomatik eşleştirilecektir.', 'kanews' ),
			__( 'Kurulumdan sonra Özelleştir ekranından logonuzu ve temel ayarları güncelleyin.', 'kanews' ),
		);
		
		?>
		<div class="wrap kan__container kanews-wrap">

			<?php kanews_render_admin_header( 'import', __( 'Önceden hazırlanmış demo ayarlarından birini sitenize hızlıca uygulayın.', 'kanews' ) ); ?>

						<?php 
			if ( function_exists( 'kanews_render_admin_hero' ) ) {
				$hero_stats = array(
					array(
						'label' => __( 'Hazır Demo', 'kanews' ),
						'value' => number_format_i18n( count( $demo_packages ) ),
						'hint'  => __( 'Tek tıkla kurulabilir', 'kanews' ),
					),
					array(
						'label' => __( 'Önerilen Eklentiler', 'kanews' ),
						'value' => 'WooCommerce · OCDI',
						'hint'  => __( 'Opsiyonel / zorunlu', 'kanews' ),
					),
				);
				kanews_render_admin_hero(
					array(
						'eyebrow'     => __( 'Demo Aktarıcı', 'kanews' ),
						'title'       => __( 'Dakikalar içinde Kanews demosu kurun', 'kanews' ),
						'description' => __( 'WooCommerce ve One Click Demo Import ile tam kapsamlı demo kurulumu yapabilir, tüm içerik ve ayarları otomatik içe aktarabilirsiniz.', 'kanews' ),
						'actions'     => array(
							array(
								'label' => __( 'Demo Kurulum Sayfasını Aç', 'kanews' ),
								'href'  => (class_exists( 'OCDI_Plugin' ) ? admin_url( 'themes.php?page=pt-one-click-demo-import' ) : admin_url( 'plugin-install.php?tab=plugin-information&plugin=one-click-demo-import&TB_iframe=true&width=640&height=500' )),
								'class' => 'button button-primary',
							),
							array(
								'label'  => __( 'Kurulum Dökümantasyonu', 'kanews' ),
								'href'   => 'https://docs.kanthemes.com/kanews/#/kurulum?id=demo-kurulumu-nas%c4%b1l-yap%c4%b1l%c4%b1r',
								'target' => '_blank',
								'class'  => 'button',
							),
						),
						'stats'       => $hero_stats,
					)
				);
			}
			?>

			<div class="kanews_admin_content">
				<div class="kan__section has-2-columns has-gutters kanews-grid">
					<div class="column">
						<div class="kanews-card">
							<div class="kanews-card__header">
								<div class="kanews-card__header-text">
									<div class="kanews-card__icon kanews-card__icon--amber">
										<span class="dashicons dashicons-admin-plugins"></span>
									</div>
									<div>
										<h3 class="kanews-card__title"><?php esc_html_e( 'Hazırlık Adımları', 'kanews' ); ?></h3>
										<p class="kanews-card__subtitle">
											<?php esc_html_e( 'Demo importu öncesi gerekli eklentileri yükleyin.', 'kanews' ); ?>
						</p>
					</div>
				</div>
			</div>
							<ul class="kanews-progress-list">
								<?php
								$badge = 1;
								foreach ( $plugin_steps as $step_text ) :
									?>
								<li>
									<span class="kanews-progress-list__badge"><?php echo esc_html( $badge ); ?></span>
									<div class="kanews-progress-list__content">
										<p><?php echo esc_html( $step_text ); ?></p>
			</div>
								</li>
								<?php
								$badge ++;
								endforeach;
								?>
							</ul>
							<br>
							<div class="kanews-card__actions">
								<a target="_blank" rel="noopener noreferrer" href="<?php echo esc_url( admin_url( 'plugin-install.php?tab=plugin-information&plugin=one-click-demo-import&TB_iframe=true&width=640&height=500' ) ); ?>" class="button button-primary">
									<?php esc_html_e( 'OCDI Kur ve Etkinleştir', 'kanews' ); ?>
								</a>
				</div>
				</div>
			</div>

					<div class="column">
						<div class="kanews-card">
							<div class="kanews-card__header">
								<div class="kanews-card__header-text">
									<div class="kanews-card__icon kanews-card__icon--green">
										<span class="dashicons dashicons-media-interactive"></span>
				</div>
									<div>
										<h3 class="kanews-card__title"><?php esc_html_e( 'Import Akışı', 'kanews' ); ?></h3>
										<p class="kanews-card__subtitle">
											<?php esc_html_e( 'İşlem sırasında dikkat edilmesi gereken kilit noktalar.', 'kanews' ); ?>
										</p>
									</div>
								</div>
							</div>
							<ul class="kanews-progress-list">
								<?php
								$tip_index = 1;
								foreach ( $import_tips as $tip_text ) :
									?>
								<li>
									<span class="kanews-progress-list__badge"><?php echo esc_html( $tip_index ); ?></span>
									<div class="kanews-progress-list__content">
										<p><?php echo esc_html( $tip_text ); ?></p>
									</div>
								</li>
								<?php
								$tip_index ++;
								endforeach;
								?>
							</ul>
						</div>
					</div>
				</div>
		</div>
		
			<?php if ( ! empty( $demo_showcase ) ) : ?>
				<div class="kanews-card kanews-card--panel">
					<h3 class="kanews-card__title"><?php esc_html_e( 'Öne Çıkan Demolar', 'kanews' ); ?></h3>
					<div class="kanews-demo-grid">
						<?php foreach ( $demo_showcase as $package ) : ?>
							<article class="kanews-demo-card">
								<?php if ( ! empty( $package['import_preview_image_url'] ) ) : ?>
									<img src="<?php echo esc_url( $package['import_preview_image_url'] ); ?>" alt="<?php echo esc_attr( $package['import_file_name'] ); ?>" loading="lazy">
								<?php endif; ?>
								<div class="kanews-demo-card__body">
									<h4><?php echo esc_html( $package['import_file_name'] ); ?></h4>
									<p><?php echo esc_html( wp_parse_url( $package['preview_url'], PHP_URL_HOST ) ); ?></p>
					</div>
								<div class="kanews-demo-card__actions">
									<a class="button" target="_blank" rel="noopener noreferrer" href="<?php echo esc_url( $package['preview_url'] ); ?>">
										<?php esc_html_e( 'Önizle', 'kanews' ); ?>
									</a>
				</div>
							</article>
						<?php endforeach; ?>
		</div>
				</div>
			<?php endif; ?>

			<div class="kanews-card kanews-card--panel">
				<h3 class="kanews-card__title"><?php esc_html_e( 'Destek & Kaynaklar', 'kanews' ); ?></h3>
				<ul class="kanews-card__list kanews-card__list--link">
					<li>
						<a class="kanews-card__list-link" target="_blank" rel="noopener noreferrer" href="https://docs.kanthemes.com/kanews/#/kurulum?id=demo-kurulumu-nas%c4%b1l-yap%c4%b1l%c4%b1r">
							<span class="kanews-card__list-body">
								<span class="dashicons dashicons-book-alt"></span>
								<span><?php esc_html_e( 'Dokümantasyon: Demo Kurulumu', 'kanews' ); ?></span>
							</span>
							<span class="kanews-card__status"><?php esc_html_e( 'Oku', 'kanews' ); ?></span>
						</a>
					</li>
					<li>
						<a class="kanews-card__list-link" target="_blank" rel="noopener noreferrer" href="https://docs.kanthemes.com/kanews/#/kurulum?id=sss">
							<span class="kanews-card__list-body">
								<span class="dashicons dashicons-sos"></span>
								<span><?php esc_html_e( 'SSS: Import sırasında dikkat edilmesi gerekenler', 'kanews' ); ?></span>
							</span>
							<span class="kanews-card__status"><?php esc_html_e( 'İncele', 'kanews' ); ?></span>
						</a>
					</li>
					<li>
						<a class="kanews-card__list-link" target="_blank" rel="noopener noreferrer" href="https://www.kanthemes.com/destek/">
							<span class="kanews-card__list-body">
								<span class="dashicons dashicons-email-alt"></span>
								<span><?php esc_html_e( 'Destek Talebi Oluştur', 'kanews' ); ?></span>
							</span>
							<span class="kanews-card__status"><?php esc_html_e( 'Gönder', 'kanews' ); ?></span>
						</a>
					</li>
				</ul>
			</div>

		</div>
		<?php
	}
}

/*-----------------------------------------------------------------------------------*/
# Redirect after theme active
/*-----------------------------------------------------------------------------------*/
function kanews_theme_active_redirect_page() {
	global $pagenow;
	if ( 'themes.php' == $pagenow && isset( $_GET['activated'] ) ) {
		if ( function_exists('kanews__get__status') && kanews__get__status() ) {
			wp_redirect(admin_url("admin.php?page=kanews-welcome"));
		} else {
			wp_redirect(admin_url("admin.php?page=kanews-license"));
		}
	}
}
add_action('admin_init', 'kanews_theme_active_redirect_page');

/*-----------------------------------------------------------------------------------*/
# One Click Demo Import
/*-----------------------------------------------------------------------------------*/
add_filter( 'ocdi/import_files', 'kanews_import_files' );
add_action( 'ocdi/after_import', 'kdi_after_import_setup' );
add_action( 'ocdi/before_widgets_import', 'kdi_reset_widgets' );
// Legacy hook names for backward compatibility.
add_filter( 'pt-ocdi/import_files', 'kanews_import_files' );
add_action( 'pt-ocdi/after_import', 'kdi_after_import_setup' );
add_action( 'pt-ocdi/before_widgets_import', 'kdi_reset_widgets' );

if ( ! function_exists( 'kanews_import_files' ) ) :
	function kanews_import_files() {
		
		if ( ! class_exists( 'wp_Knskea36' ) )
		return array();

		return array(
			array(
				'import_file_name'           => __('Haber', 'kanews'),
				'import_file_url'            => 'https://www.kanthemes.com.tr/files/kanews/demo/genel/wordpress.xml',
				'import_widget_file_url'     => 'https://www.kanthemes.com.tr/files/kanews/demo/genel/widgets.wie',
				'import_preview_image_url'   => 'https://www.kanthemes.com/wp-content/themes/kanthemes/dist/img/land/kanews/demo1.jpg',
				'preview_url'                => 'https://demo.kanthemes.com.tr/kanews/',
				'import_json'      => array(
					array(
						'file_url'     => 'https://www.kanthemes.com.tr/files/kanews/demo/genel/options.txt',
						'option_name'  => 'kanews_options',
					),
				)
			),
			array(
				'import_file_name'           => __('Yerel', 'kanews'),
				'import_file_url'            => 'https://www.kanthemes.com.tr/files/kanews/demo/yerel/wordpress.xml',
				'import_widget_file_url'     => 'https://www.kanthemes.com.tr/files/kanews/demo/yerel/widgets.wie',
				'import_preview_image_url'   => 'https://www.kanthemes.com/wp-content/themes/kanthemes/dist/img/land/kanews/demo2.jpg',
				'preview_url'                => 'https://demo.kanthemes.com.tr/kanews/yerel/',
				'import_json'      => array(
					array(
						'file_url'     => 'https://www.kanthemes.com.tr/files/kanews/demo/yerel/options.txt',
						'option_name'  => 'kanews_options',
					),
				)
			),

			array(
				'import_file_name'           => __('Startup', 'kanews'),
				'import_file_url'            => 'https://www.kanthemes.com.tr/files/kanews/demo/startups/wordpress.xml',
				'import_widget_file_url'     => 'https://www.kanthemes.com.tr/files/kanews/demo/startups/widgets.wie',
				'import_preview_image_url'   => 'https://www.kanthemes.com/wp-content/themes/kanthemes/dist/img/land/kanews/demo3.jpg',
				'preview_url'                => 'https://demo.kanthemes.com.tr/kanews/startups/',
				'import_json'      => array(
					array(
						'file_url'     => 'https://www.kanthemes.com.tr/files/kanews/demo/startups/options.txt',
						'option_name'  => 'kanews_options',
					),
				)
			),

			array(
				'import_file_name'           => __('Global News', 'kanews'),
				'import_file_url'            => 'https://www.kanthemes.com.tr/files/kanews/demo/world/wordpress.xml',
				'import_widget_file_url'     => 'https://www.kanthemes.com.tr/files/kanews/demo/world/widgets.wie',
				'import_preview_image_url'   => 'https://www.kanthemes.com/wp-content/themes/kanthemes/dist/img/land/kanews/demo4.jpg',
				'preview_url'                => 'https://demo.kanthemes.com.tr/kanews/world/',
				'import_json'      => array(
					array(
						'file_url'     => 'https://www.kanthemes.com.tr/files/kanews/demo/world/options.txt',
						'option_name'  => 'kanews_options',
					),
				)
			),

			array(
				'import_file_name'           => __('Firma Rehberi', 'kanews'),
				'import_file_url'            => 'https://www.kanthemes.com.tr/files/kanews/demo/firma/wordpress.xml',
				'import_widget_file_url'     => 'https://www.kanthemes.com.tr/files/kanews/demo/firma/widgets.wie',
				'import_preview_image_url'   => 'https://www.kanthemes.com/wp-content/themes/kanthemes/dist/img/land/kanews/demo9.jpg',
				'preview_url'                => 'https://demo.kanthemes.com.tr/kanews/firma-rehberi/',
				'import_json'      => array(
					array(
						'file_url'     => 'https://www.kanthemes.com.tr/files/kanews/demo/firma/options.txt',
						'option_name'  => 'kanews_options',
					),
				)
			),	

			array(
				'import_file_name'           => __('İlan', 'kanews'),
				'import_file_url'            => 'https://www.kanthemes.com.tr/files/kanews/demo/ilan/wordpress.xml',
				'import_widget_file_url'     => 'https://www.kanthemes.com.tr/files/kanews/demo/ilan/widgets.wie',
				'import_preview_image_url'   => 'https://www.kanthemes.com/wp-content/themes/kanthemes/dist/img/land/kanews/demo10.jpg',
				'preview_url'                => 'https://demo.kanthemes.com.tr/kanews/ilan/',
				'import_json'      => array(
					array(
						'file_url'     => 'https://www.kanthemes.com.tr/files/kanews/demo/ilan/options.txt',
						'option_name'  => 'kanews_options',
					),
				)
			),	


			array(
				'import_file_name'           => __('Kripto', 'kanews'),
				'import_file_url'            => 'https://www.kanthemes.com.tr/files/kanews/demo/kripto/wordpress.xml',
				'import_widget_file_url'     => 'https://www.kanthemes.com.tr/files/kanews/demo/kripto/widgets.wie',
				'import_preview_image_url'   => 'https://www.kanthemes.com/wp-content/themes/kanthemes/dist/img/land/kanews/demo7.jpg',
				'preview_url'                => 'https://demo.kanthemes.com.tr/kanews/kripto/',
				'import_json'      => array(
					array(
						'file_url'     => 'https://www.kanthemes.com.tr/files/kanews/demo/kripto/options.txt',
						'option_name'  => 'kanews_options',
					),
				)
			),
			
					
			array(
				'import_file_name'           => __('Finans', 'kanews'),
				'import_file_url'            => 'https://www.kanthemes.com.tr/files/kanews/demo/finans/wordpress.xml',
				'import_widget_file_url'     => 'https://www.kanthemes.com.tr/files/kanews/demo/finans/widgets.wie',
				'import_preview_image_url'   => 'https://www.kanthemes.com/wp-content/themes/kanthemes/dist/img/land/kanews/demo8.jpg',
				'preview_url'                => 'https://demo.kanthemes.com.tr/kanews/finans/',
				'import_json'      => array(
					array(
						'file_url'     => 'https://www.kanthemes.com.tr/files/kanews/demo/finans/options.txt',
						'option_name'  => 'kanews_options',
					),
				)
			),

			array(
				'import_file_name'           => __('Spor', 'kanews'),
				'import_file_url'            => 'https://www.kanthemes.com.tr/files/kanews/demo/spor/wordpress.xml',
				'import_widget_file_url'     => 'https://www.kanthemes.com.tr/files/kanews/demo/spor/widgets.wie',
				'import_preview_image_url'   => 'https://www.kanthemes.com/wp-content/themes/kanthemes/dist/img/land/kanews/demo5.jpg',
				'preview_url'                => 'https://demo.kanthemes.com.tr/kanews/spor/',
				'import_json'      => array(
					array(
						'file_url'     => 'https://www.kanthemes.com.tr/files/kanews/demo/spor/options.txt',
						'option_name'  => 'kanews_options',
					),
				)
			),

			array(
				'import_file_name'           => __('Blog', 'kanews'),
				'import_file_url'            => 'https://www.kanthemes.com.tr/files/kanews/demo/blog/wordpress.xml',
				'import_widget_file_url'     => 'https://www.kanthemes.com.tr/files/kanews/demo/blog/widgets.wie',
				'import_preview_image_url'   => 'https://www.kanthemes.com/wp-content/themes/kanthemes/dist/img/land/kanews/demo6.jpg',
				'preview_url'                => 'https://demo.kanthemes.com.tr/kanews/blog/',
				'import_json'      => array(
					array(
						'file_url'     => 'https://www.kanthemes.com.tr/files/kanews/demo/blog/options.txt',
						'option_name'  => 'kanews_options',
					),
				)
			),

			
			
			
		);
	}
endif;

// Set Navigation Menus
function kdi_after_import_setup($selected_import) {
	$navbar   = get_term_by( 'name', 'Navbar', 'nav_menu' );
	$footer   = get_term_by( 'name', 'Footer', 'nav_menu' );
	$big_menu = get_term_by( 'name', 'Büyük Menü', 'nav_menu' );

	set_theme_mod( 'nav_menu_locations', array(
			'menu-1'   => $navbar->term_id,
			'menu-2'   => $navbar->term_id,
			'menu-3'   => $footer->term_id,
			'big-menu' => $big_menu->term_id,
		)
	);

	update_option( 'show_on_front', 'posts' );
}

// Reset Widgets
function kdi_reset_widgets(){
	update_option( 'sidebars_widgets', '' );
}

function ocdi_register_plugins( $plugins ) {
	
  $theme_plugins = [
    [ // A WordPress.org plugin repository example.
      'name'     => 'Woocommerce', // Name of the plugin.
      'slug'     => 'woocommerce', // Plugin slug - the same as on WordPress.org plugin repository.
      'required' => false,                     // If the plugin is required or not.
    ],
    [ // A WordPress.org plugin repository example.
      'name'     => 'Litespeed Cache', // Name of the plugin.
      'slug'     => 'litespeed-cache', // Plugin slug - the same as on WordPress.org plugin repository.
      'required' => false,  // If the plugin is required or not.
		],
		[
			'name'     => esc_html__( 'Kanews Hikayeler', 'kanews' ),
			'slug'     => 'kanews-stories',
			'source'   => get_template_directory_uri() . '/inc/plugins/kanews-stories.zip',
      'required' => false,
    ]
  ];

	
  return array_merge( $plugins, $theme_plugins );
}
add_filter( 'ocdi/register_plugins', 'ocdi_register_plugins' );

/*-----------------------------------------------------------------------------------*/
# Admin Notices
/*-----------------------------------------------------------------------------------*/
function kanews_check_plugin_state(){
	global $pagenow;
	if($pagenow == 'plugins.php')
	return false;
	
	if (is_plugin_active('easy-theme-and-plugin-upgrades/init.php')){
		wp_die('<p>Easy Theme and Plugin Updates eklentisini kaldırın veya etkisiz hale getirin!</p> <a class="button" href="'.admin_url('plugins.php').'">Eklentileri Görüntüle</a>');
	} else
	return false;
}
add_action('admin_init', 'kanews_check_plugin_state');

// Update Key
function kanews_update_key_notice(){
	if ( get_option('kanews_order_auth') != '' )
	return false;

	$message = sprintf( esc_html__( 'Güncellemeleri paneliniz üzerinden yapmak için lütfen %s ekleyin.', 'kanews' ), '<a href="'.admin_url('admin.php?page=kanews-update').'">güncelleme anahtarınızı</a>' );
	printf( '<div class="error"><p>%s</p></div>', $message );
}
add_action('admin_notices', 'kanews_update_key_notice');

// Disable wp cron
function kanews_update_key_notice2(){
	if ( defined( 'DISABLE_WP_CRON' ) && DISABLE_WP_CRON ) {
		$message =  esc_html__( 'Kanews\'i tam verimlilik ile kullanmak için WP Cron sistemini etkinleştirin.', 'kanews' );
		printf( '<div class="notice notice-info"><p>%s</p></div>', $message );
	} else {
		return false;
	}
}
add_action('admin_notices', 'kanews_update_key_notice2');

// Curl Extension
function kanews_curl_requires_notice() {
	if( in_array('curl', get_loaded_extensions()) ) 
	return false;

	$message = sprintf( esc_html__( '%s çalışması için cURL kütüphanenizin aktif olması gerekiyor.', 'kanews' ), KAN_THEME_NAME );
	printf( '<div class="error"><p>%s</p></div>', $message );
}
add_action( 'admin_notices', 'kanews_curl_requires_notice' );

/*-----------------------------------------------------------------------------------*/
# Post Format Base
/*-----------------------------------------------------------------------------------*/
add_filter( 'post_format_rewrite_base', 'kanews_post_format_rewrite_base' );
function kanews_post_format_rewrite_base( $slug ) {
	if(get_option('kanews_post_format_base') != '')
	return trim( strip_tags(get_option('kanews_post_format_base')));
	else
	return $slug;
}

add_action( 'load-options-permalink.php', 'kanews_post_format_load_permalinks' );
function kanews_post_format_load_permalinks() {
	if( isset( $_POST['kanews_post_format_base'] ) ) {
		update_option( 'kanews_post_format_base', sanitize_title_with_dashes( $_POST['kanews_post_format_base'] ) );
	}
	add_settings_field( 'kanews_post_format_base', __( 'Yazı türü temeli' ), 'kanews_post_format_field_callback', 'permalink', 'optional' );
}

function kanews_post_format_field_callback(){
	$value = get_option( 'kanews_post_format_base' );	
	echo '<input type="text" value="' . esc_attr( $value ) . '" name="kanews_post_format_base" id="kanews_post_format_base" class="regular-text" />';
}


/**
* Render textinput for Author base
* Callback for the add_settings_function()
*
* @return void
*/
function kanews_2610_author_base_render_field() {
	global $wp_rewrite;
	printf(
			'<code>'.home_url('/').'</code><input name="kanews_author_base" id="kanews_author_base" type="text" value="%s" class="regular-text code">',
			esc_attr( $wp_rewrite->author_base )
	);
}

/**
* Add a setting field for Author Base to the "Optional" Section
* of the Permalinks Page
*
* @return void
*/
function kanews_2610_author_base_add_settings_field() {
	add_settings_field(
			'kanews_author_base',
			esc_html__( 'Yazar temeli' ),
			'kanews_2610_author_base_render_field',
			'permalink',
			'optional',
			array( 'label_for' => 'kanews_author_base' )
	);
}

add_action( 'admin_init', 'kanews_2610_author_base_add_settings_field' );

/**
* Sanitize and save the given Author Base value to the database
*
* @return void
*/
function kanews_2610_author_base_update() {
	$author_base_db = get_option( 'kanews_author_base' );

	if ( isset( $_POST['kanews_author_base'] ) &&
			isset( $_POST['permalink_structure'] ) &&
			check_admin_referer( 'update-permalink' )
	) {
		$author_base = sanitize_title( $_POST['kanews_author_base'] );

		if ( empty( $author_base ) ) {
			add_settings_error(
				'kanews_author_base',
				'kanews_author_base',
				esc_html__( 'Invalid Author Base.' ),
				'error'
			);
		} elseif ( $author_base_db != $author_base ) {
				update_option( 'kanews_author_base', $author_base );
		}
	}
}

add_action( 'admin_init', 'kanews_2610_author_base_update' );

/*-----------------------------------------------------------------------------------*/
# Author Archive Slug
/*-----------------------------------------------------------------------------------*/

/**
* Render textinput for Author slug
* Callback for the add_settings_function()
*
* @return void
*/
function kanews_2610_author_slug_render_field() {
	global $wp_rewrite;
	printf(
			'<code>'.home_url('/'.esc_attr( $wp_rewrite->author_base )).'/</code><input name="kanews_author_slug" id="kanews_author_slug" type="text" value="%s" class="regular-text code">',
			esc_attr( get_option( 'kanews_author_slug', 'kose-yazisi' ) )
	);
}

/**
* Add a setting field for Author Base to the "Optional" Section
* of the Permalinks Page
*
* @return void
*/
function kanews_2610_author_slug_add_settings_field() {
	add_settings_field(
			'kanews_author_slug',
			esc_html__( 'Köşe yazısı temeli' ),
			'kanews_2610_author_slug_render_field',
			'permalink',
			'optional',
			array( 'label_for' => 'kanews_author_slug' )
	);
}

add_action( 'admin_init', 'kanews_2610_author_slug_add_settings_field' );

/**
* Sanitize and save the given Author slug value to the dataslug
*
* @return void
*/
function kanews_2610_author_slug_update() {
	$author_slug_db = get_option( 'kanews_author_slug' );

	if ( isset( $_POST['kanews_author_slug'] ) &&
			isset( $_POST['permalink_structure'] ) &&
			check_admin_referer( 'update-permalink' )
	) {
		$author_slug = sanitize_title( $_POST['kanews_author_slug'] );

		if ( empty( $author_slug ) ) {
			add_settings_error(
				'kanews_author_slug',
				'kanews_author_slug',
				esc_html__( 'Invalid Author slug.' ),
				'error'
			);
		} elseif ( $author_slug_db != $author_slug ) {
				update_option( 'kanews_author_slug', $author_slug );
		}
	}
}

add_action( 'admin_init', 'kanews_2610_author_slug_update' );

/*-----------------------------------------------------------------------------------*/
# İlan Slug
/*-----------------------------------------------------------------------------------*/

/**
* Render textinput for Author slug
* Callback for the add_settings_function()
*
* @return void
*/
function kanews_2610_ilan_slug_render_field() {
	global $wp_rewrite;
	printf(
			'<code>'.home_url().'/</code><input name="kanews_ilan_slug" id="kanews_ilan_slug" type="text" value="%s" class="regular-text code">',
			esc_attr( get_option( 'kanews_ilan_slug', 'ilan' ) )
	);
}

/**
* Add a setting field for ilan Base to the "Optional" Section
* of the Permalinks Page
*
* @return void
*/
function kanews_2610_ilan_slug_add_settings_field() {
	add_settings_field(
			'kanews_ilan_slug',
			esc_html__( 'İlanlar temeli' ),
			'kanews_2610_ilan_slug_render_field',
			'permalink',
			'optional',
			array( 'label_for' => 'kanews_ilan_slug' )
	);
}

add_action( 'admin_init', 'kanews_2610_ilan_slug_add_settings_field' );

/**
* Sanitize and save the given ilan slug value to the dataslug
*
* @return void
*/
function kanews_2610_ilan_slug_update() {
	$ilan_slug_db = get_option( 'kanews_ilan_slug' );

	if ( isset( $_POST['kanews_ilan_slug'] ) &&
			isset( $_POST['permalink_structure'] ) &&
			check_admin_referer( 'update-permalink' )
	) {
		$ilan_slug = sanitize_title( $_POST['kanews_ilan_slug'] );

		if ( empty( $ilan_slug ) ) {
			add_settings_error(
				'kanews_ilan_slug',
				'kanews_ilan_slug',
				esc_html__( 'Invalid ilan slug.' ),
				'error'
			);
		} elseif ( $ilan_slug_db != $ilan_slug ) {
				update_option( 'kanews_ilan_slug', $ilan_slug );
		}
	}
}

add_action( 'admin_init', 'kanews_2610_ilan_slug_update' );

/*-----------------------------------------------------------------------------------*/
# Firma Slug
/*-----------------------------------------------------------------------------------*/

/**
* Render textinput for Author slug
* Callback for the add_settings_function()
*
* @return void
*/
function kanews_2610_firma_slug_render_field() {
	global $wp_rewrite;
	printf(
			'<code>'.home_url().'/</code><input name="kanews_firma_slug" id="kanews_firma_slug" type="text" value="%s" class="regular-text code">',
			esc_attr( get_option( 'kanews_firma_slug', 'firma-rehberi' ) )
	);
}

/**
* Add a setting field for firma Base to the "Optional" Section
* of the Permalinks Page
*
* @return void
*/
function kanews_2610_firma_slug_add_settings_field() {
	add_settings_field(
			'kanews_firma_slug',
			esc_html__( 'Firma temeli' ),
			'kanews_2610_firma_slug_render_field',
			'permalink',
			'optional',
			array( 'label_for' => 'kanews_firma_slug' )
	);
}

add_action( 'admin_init', 'kanews_2610_firma_slug_add_settings_field' );

/**
* Sanitize and save the given firma slug value to the dataslug
*
* @return void
*/
function kanews_2610_firma_slug_update() {
	$firma_slug_db = get_option( 'kanews_firma_slug' );

	if ( isset( $_POST['kanews_firma_slug'] ) &&
			isset( $_POST['permalink_structure'] ) &&
			check_admin_referer( 'update-permalink' )
	) {
		$firma_slug = sanitize_title( $_POST['kanews_firma_slug'] );

		if ( empty( $firma_slug ) ) {
			add_settings_error(
				'kanews_firma_slug',
				'kanews_firma_slug',
				esc_html__( 'Invalid firma slug.' ),
				'error'
			);
		} elseif ( $firma_slug_db != $firma_slug ) {
				update_option( 'kanews_firma_slug', $firma_slug );
		}
	}
}

add_action( 'admin_init', 'kanews_2610_firma_slug_update' );


/*-----------------------------------------------------------------------------------*/
# Google Fonts
/*-----------------------------------------------------------------------------------*/
function kanews_google_fonts() {
  // Check if cached fonts exist and are less than 30 days old
  $cached_fonts = get_transient('kanews_google_fonts_cache');
  if ($cached_fonts !== false) {
    return $cached_fonts;
  }

  // Try to fetch latest fonts from Google Fonts API
  $response = wp_remote_get('https://www.googleapis.com/webfonts/v1/webfonts?key=AIzaSyBNWzU2R3gbTv_d_nBKbbg1cP5yynMbETk');
  
  if (!is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200) {
    $fonts = json_decode(wp_remote_retrieve_body($response), true);
    $list = array("system" => "Sistem Fontu"); // Add system font as first option
    
    if (!empty($fonts['items'])) {
      foreach ($fonts['items'] as $font) {
        $key = strtolower(str_replace(' ', '_', $font['family']));
        $list[$key] = $font['family'];
      }
      
      // Cache the fonts list for 30 days
      set_transient('kanews_google_fonts_cache', $list, 30 * DAY_IN_SECONDS);
      
      return $list;
    }
  }
  
  // Fallback to existing static list if API call fails
  $list = array( "system" => "Sistem Fontu", /* ... existing fonts ... */ );
  
  return $list;
}

/**
 * Adding local_import_json and import_json param supports.
 */
if ( ! function_exists( 'kan_after_content_import_execution' ) ) {
  function kan_after_content_import_execution( $selected_import_files, $import_files, $selected_index ) {

    $downloader = new OCDI\Downloader();

    if( ! empty( $import_files[$selected_index]['import_json'] ) ) {

      foreach( $import_files[$selected_index]['import_json'] as $index => $import ) {
        $file_path = $downloader->download_file( $import['file_url'], 'demo-import-file-'. $index .'-'. date( 'Y-m-d__H-i-s' ) .'.json' );
        $file_raw  = OCDI\Helpers::data_from_file( $file_path );
        update_option( $import['option_name'], json_decode( $file_raw, true ) );
      }

    } else if( ! empty( $import_files[$selected_index]['local_import_json'] ) ) {

      foreach( $import_files[$selected_index]['local_import_json'] as $index => $import ) {
        $file_path = $import['file_path'];
        $file_raw  = OCDI\Helpers::data_from_file( $file_path );
        update_option( $import['option_name'], json_decode( $file_raw, true ) );
      }

    }

  }
  add_action('ocdi/before_content_import_execution', 'kan_after_content_import_execution', 3, 10 );
}


function kanews_get_turkey_cities3() {
	$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' =>'Elâzığ',
		'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',
	);
  return apply_filters('kanews/weather_page_cities', $sehirler);
}

/*-----------------------------------------------------------------------------------*/
# Get Categories
/*-----------------------------------------------------------------------------------*/
function kanews_get_categories() {
  $output_categories = array();
  $categories = get_categories();
	
  foreach($categories as $category) {
    $output_categories[$category->slug] = $category->name;
  }

  return $output_categories;
}

/*-----------------------------------------------------------------------------------*/
# Get Pages
/*-----------------------------------------------------------------------------------*/
function kanews_get_pages() {
  $output_pages = array();
  $pages = get_pages('hide_empty=0&depth=1&type=post');
	
  foreach($pages as $page) {
    $output_pages[$page->ID] = $page->post_title;
  }

  return $output_pages;
}


/*-----------------------------------------------------------------------------------*/
# Contact Forms
/*-----------------------------------------------------------------------------------*/
function kanews_get_contact_forms() {
  $posts = get_posts(array(
    'post_type'     => 'wpcf7_contact_form',
    'numberposts'   => -1
  ));

	$output = array();

  foreach ( $posts as $p ) {
    $output[$p->ID] = $p->post_title;
  }
  
  return $output;
}

/*-----------------------------------------------------------------------------------*/
# Database Optimizer Functions
/*-----------------------------------------------------------------------------------*/

/**
 * Clean empty values from array (recursive)
 */
function kanews_clean_empty_values( $data ) {
  if ( ! is_array( $data ) ) {
    return $data;
  }

  // If array is empty, return empty array
  if ( empty( $data ) ) {
    return array();
  }

  // First check: if ALL values in the array are empty strings, null, empty arrays, or only default values, return empty array
  $default_only_values = array( 'px', 'em', 'rem', 'pt', '%' );
  $all_values_empty = true;
  $has_only_default_keys = true;
  $has_any_non_default_key = false;
  
  foreach ( $data as $key => $value ) {
    // Check if this is a default key (unit, type)
    if ( $key === 'unit' || $key === 'type' ) {
      // If it's a default key with default value, it's still considered "empty" for our purposes
      if ( is_string( $value ) && in_array( $value, $default_only_values ) ) {
        // This is a default key with default value, continue checking
        continue;
      } else if ( $value !== '' && $value !== null ) {
        // Default key but non-default value, this is meaningful
        $all_values_empty = false;
        $has_only_default_keys = false;
        break;
      }
    } else {
      // This is a non-default key
      $has_any_non_default_key = true;
      $has_only_default_keys = false;
      
      if ( is_array( $value ) ) {
        // Recursively check nested arrays
        $cleaned_nested = kanews_clean_empty_values( $value );
        if ( ! empty( $cleaned_nested ) ) {
          $all_values_empty = false;
          break;
        }
      } else if ( $value !== '' && $value !== null && $value !== 'default' ) {
        $all_values_empty = false;
        break;
      }
    }
  }
  
  // If array only has default keys (unit/type) with default values and no other meaningful values, it's empty
  if ( $has_only_default_keys && ! $has_any_non_default_key ) {
    return array();
  }
  
  // If all values are empty, return empty array
  if ( $all_values_empty ) {
    return array();
  }

  $cleaned = array();

  foreach ( $data as $key => $value ) {
    // Check if value is an array
    if ( is_array( $value ) ) {
      // Recursively clean the array first
      $cleaned_sub = kanews_clean_empty_values( $value );
      
      // If cleaned array is empty, skip it
      if ( empty( $cleaned_sub ) ) {
        continue;
      }
      
      // Check if array has any meaningful values (not just default unit/type)
      $has_meaningful_value = false;
      $has_non_default_keys = false;
      
      foreach ( $cleaned_sub as $sub_key => $sub_value ) {
        // Skip default keys (unit, type) if they only have default values
        if ( $sub_key === 'unit' || $sub_key === 'type' ) {
          // If unit/type has a non-default value, it's meaningful
          if ( $sub_value !== '' && $sub_value !== null && ! in_array( $sub_value, $default_only_values ) ) {
            $has_meaningful_value = true;
            break;
          }
          // If unit is "px" or other default, it's not meaningful by itself
          continue;
        }
        
        $has_non_default_keys = true;
        
        // Check if this is a meaningful value (not empty, not null, not empty array)
        if ( $sub_value !== '' && $sub_value !== null && ! ( is_array( $sub_value ) && empty( $sub_value ) ) ) {
          $has_meaningful_value = true;
          break;
        }
      }
      
      // If array only has default keys (unit/type) and no meaningful non-default values, it's empty
      if ( ! $has_non_default_keys && ! $has_meaningful_value ) {
        continue;
      }
      
      // If array has non-default keys but no meaningful values, it's still empty
      if ( $has_non_default_keys && ! $has_meaningful_value ) {
        continue;
      }
      
      // Only add arrays with meaningful values
      if ( $has_meaningful_value ) {
        $cleaned[$key] = $cleaned_sub;
      }
    } 
    // Check if value is a string
    else if ( is_string( $value ) ) {
      // Only add non-empty strings
      if ( trim( $value ) !== '' && $value !== 'default' ) {
        $cleaned[$key] = $value;
      }
    }
    // For other types (int, bool, etc.), keep them
    else {
      if ( $value !== null && $value !== '' && $value !== 'default' ) {
        $cleaned[$key] = $value;
      }
    }
  }

  return $cleaned;
}

/**
 * Get duplicate meta statistics
 */
function kanews_get_duplicate_meta_stats() {
  global $wpdb;
  
  $duplicates = $wpdb->get_results( "
    SELECT post_id, meta_key, COUNT(*) as count
    FROM {$wpdb->postmeta}
    WHERE (
      meta_key LIKE 'kanews_%' 
      OR meta_key LIKE '%_kanews_%' 
      OR meta_key = 'kanews_post_options' 
      OR meta_key = 'kanews_page_options' 
      OR meta_key = 'kanews_columnist_options'
      OR meta_key = 'kanews_companies_options'
      OR meta_key = 'kanews_ilan_options'
      OR meta_key LIKE 'kanews_%_options'
    )
    GROUP BY post_id, meta_key
    HAVING count > 1
  ", ARRAY_A );

  $total_duplicates = 0;
  $duplicate_groups = array();
  
  foreach ( $duplicates as $dup ) {
    $total_duplicates += ( $dup['count'] - 1 ); // -1 because we keep one
    $duplicate_groups[] = array(
      'post_id' => $dup['post_id'],
      'meta_key' => $dup['meta_key'],
      'count' => $dup['count']
    );
  }

  return array(
    'total_duplicate_groups' => count( $duplicates ),
    'total_duplicate_records' => $total_duplicates,
    'duplicate_groups' => $duplicate_groups
  );
}

/**
 * Remove duplicate post meta values
 */
function kanews_remove_duplicate_meta() {
  global $wpdb;
  
  $removed = 0;
  $log = array();
  
  // Get all post meta with duplicate keys for same post (kanews related)
  $duplicates = $wpdb->get_results( "
    SELECT post_id, meta_key, COUNT(*) as count
    FROM {$wpdb->postmeta}
    WHERE (
      meta_key LIKE 'kanews_%' 
      OR meta_key LIKE '%_kanews_%' 
      OR meta_key = 'kanews_post_options' 
      OR meta_key = 'kanews_page_options' 
      OR meta_key = 'kanews_columnist_options'
      OR meta_key = 'kanews_companies_options'
      OR meta_key = 'kanews_ilan_options'
      OR meta_key LIKE 'kanews_%_options'
    )
    GROUP BY post_id, meta_key
    HAVING count > 1
  ", ARRAY_A );

  $before_stats = kanews_get_duplicate_meta_stats();

  foreach ( $duplicates as $duplicate ) {
    $post_id = $duplicate['post_id'];
    $meta_key = $duplicate['meta_key'];
    $count = $duplicate['count'];
    
    // Get all meta values for this post and key
    $meta_values = $wpdb->get_results( $wpdb->prepare( "
      SELECT meta_id, meta_value
      FROM {$wpdb->postmeta}
      WHERE post_id = %d AND meta_key = %s
      ORDER BY meta_id ASC
    ", $post_id, $meta_key ), ARRAY_A );
    
    // Keep the first one, delete the rest
    if ( count( $meta_values ) > 1 ) {
      $first_meta_id = $meta_values[0]['meta_id'];
      $removed_count = 0;
      
      foreach ( $meta_values as $meta ) {
        if ( $meta['meta_id'] != $first_meta_id ) {
          $wpdb->delete( $wpdb->postmeta, array( 'meta_id' => $meta['meta_id'] ), array( '%d' ) );
          $removed++;
          $removed_count++;
        }
      }
      
      if ( $removed_count > 0 ) {
        $post_title = get_the_title( $post_id );
        $log[] = sprintf( 
          esc_html__( 'Yazı #%d (%s) - %s: %d tekrarlayan kayıt silindi', 'kanews' ), 
          $post_id, 
          $post_title ? $post_title : esc_html__( 'Başlıksız', 'kanews' ),
          $meta_key,
          $removed_count
        );
      }
    }
  }

  $after_stats = kanews_get_duplicate_meta_stats();

  return array(
    'success' => true,
    'message' => sprintf( esc_html__( '%d tekrarlayan meta değeri silindi.', 'kanews' ), $removed ),
    'removed' => $removed,
    'before' => $before_stats,
    'after' => $after_stats,
    'log' => $log
  );
}

/**
 * Get empty post meta statistics
 */
function kanews_get_empty_post_meta_stats() {
  global $wpdb;
  
  // Get all post meta that might contain empty arrays
  // Include kanews-related keys and common theme meta keys
  $metas = $wpdb->get_results( "
    SELECT meta_id, post_id, meta_key, meta_value
    FROM {$wpdb->postmeta}
    WHERE (
      meta_key LIKE 'kanews_%' 
      OR meta_key LIKE '%_kanews_%' 
      OR meta_key = 'kanews_post_options' 
      OR meta_key = 'kanews_page_options' 
      OR meta_key = 'kanews_columnist_options'
      OR meta_key = 'kanews_companies_options'
      OR meta_key = 'kanews_ilan_options'
      OR meta_key LIKE 'kanews_%_options'
      OR meta_key LIKE 'post_%'
      OR meta_key LIKE 'manset_%'
      OR meta_key LIKE '%_typography'
      OR meta_key LIKE '%_desktop'
      OR meta_key LIKE '%_mobile'
      OR meta_key = 'post_text_to_speech'
    )
    AND meta_value != ''
    AND meta_value IS NOT NULL
  ", ARRAY_A );

  $empty_arrays = 0;
  $empty_strings = 0;
  $needs_cleaning = 0;
  $total_metas = count( $metas );

  foreach ( $metas as $meta ) {
    $meta_value = maybe_unserialize( $meta['meta_value'] );
    
    if ( is_array( $meta_value ) ) {
      // Clean the array and check if it's empty
      $cleaned = kanews_clean_empty_values( $meta_value );
      
      if ( empty( $cleaned ) || count( $cleaned ) === 0 ) {
        $empty_arrays++;
      } else {
        // Check if cleaning changed anything
        $cleaned_serialized = maybe_serialize( $cleaned );
        $original_serialized = maybe_serialize( $meta_value );
        
        if ( $cleaned_serialized !== $original_serialized ) {
          $needs_cleaning++;
        }
      }
    } else if ( empty( $meta_value ) || $meta_value === '' || $meta_value === 'default' ) {
      $empty_strings++;
    }
  }

  return array(
    'total_metas' => $total_metas,
    'empty_arrays' => $empty_arrays,
    'empty_strings' => $empty_strings,
    'needs_cleaning' => $needs_cleaning,
    'total_empty' => $empty_arrays + $empty_strings
  );
}

/**
 * Clean empty post meta values
 */
function kanews_clean_empty_post_meta() {
  global $wpdb;
  
  $removed = 0;
  $updated = 0;
  $log = array();
  
  $before_stats = kanews_get_empty_post_meta_stats();
  
  // Get all post meta that might be empty (kanews related and common theme meta keys)
  $metas = $wpdb->get_results( "
    SELECT meta_id, post_id, meta_key, meta_value
    FROM {$wpdb->postmeta}
    WHERE (
      meta_key LIKE 'kanews_%' 
      OR meta_key LIKE '%_kanews_%' 
      OR meta_key = 'kanews_post_options' 
      OR meta_key = 'kanews_page_options' 
      OR meta_key = 'kanews_columnist_options'
      OR meta_key = 'kanews_companies_options'
      OR meta_key = 'kanews_ilan_options'
      OR meta_key LIKE 'kanews_%_options'
      OR meta_key LIKE 'post_%'
      OR meta_key LIKE 'manset_%'
      OR meta_key LIKE '%_typography'
      OR meta_key LIKE '%_desktop'
      OR meta_key LIKE '%_mobile'
      OR meta_key = 'post_text_to_speech'
    )
    AND meta_value != ''
    AND meta_value IS NOT NULL
  ", ARRAY_A );

  foreach ( $metas as $meta ) {
    $meta_value = maybe_unserialize( $meta['meta_value'] );
    $post_title = get_the_title( $meta['post_id'] );
    $post_title = $post_title ? $post_title : esc_html__( 'Başlıksız', 'kanews' );
    
    // Check if it's an empty array or has only empty/default values
    if ( is_array( $meta_value ) ) {
      // Clean the array using our function
      $cleaned = kanews_clean_empty_values( $meta_value );
      
      // Check if cleaned array is empty
      if ( empty( $cleaned ) || count( $cleaned ) === 0 ) {
        // Delete if completely empty after cleaning
        $wpdb->delete( $wpdb->postmeta, array( 'meta_id' => $meta['meta_id'] ), array( '%d' ) );
        $removed++;
        $log[] = sprintf( 
          esc_html__( 'Yazı #%d (%s) - %s: Boş array silindi', 'kanews' ), 
          $meta['post_id'], 
          $post_title,
          $meta['meta_key']
        );
      } else {
        // Update with cleaned value if changed
        $cleaned_serialized = maybe_serialize( $cleaned );
        $original_serialized = maybe_serialize( $meta_value );
        
        // Compare serialized versions to see if anything changed
        if ( $cleaned_serialized !== $original_serialized ) {
          $wpdb->update( 
            $wpdb->postmeta, 
            array( 'meta_value' => $cleaned_serialized ), 
            array( 'meta_id' => $meta['meta_id'] ), 
            array( '%s' ), 
            array( '%d' ) 
          );
          $updated++;
          $log[] = sprintf( 
            esc_html__( 'Yazı #%d (%s) - %s: Boş değerler temizlendi', 'kanews' ), 
            $meta['post_id'], 
            $post_title,
            $meta['meta_key']
          );
        }
      }
    } else if ( empty( $meta_value ) || $meta_value === '' || $meta_value === 'default' ) {
      $wpdb->delete( $wpdb->postmeta, array( 'meta_id' => $meta['meta_id'] ), array( '%d' ) );
      $removed++;
      $log[] = sprintf( 
        esc_html__( 'Yazı #%d (%s) - %s: Boş string silindi', 'kanews' ), 
        $meta['post_id'], 
        $post_title,
        $meta['meta_key']
      );
    }
  }

  $after_stats = kanews_get_empty_post_meta_stats();
  $total = $removed + $updated;
  
  $message = '';
  if ( $removed > 0 && $updated > 0 ) {
    $message = sprintf( esc_html__( '%d boş meta değeri silindi, %d meta değeri temizlendi.', 'kanews' ), $removed, $updated );
  } else if ( $removed > 0 ) {
    $message = sprintf( esc_html__( '%d boş post meta değeri temizlendi.', 'kanews' ), $removed );
  } else if ( $updated > 0 ) {
    $message = sprintf( esc_html__( '%d post meta değeri temizlendi.', 'kanews' ), $updated );
  } else {
    $message = esc_html__( 'Temizlenecek boş meta değeri bulunamadı.', 'kanews' );
  }

  return array(
    'success' => true,
    'message' => $message,
    'removed' => $total,
    'removed_count' => $removed,
    'updated_count' => $updated,
    'before' => $before_stats,
    'after' => $after_stats,
    'log' => $log
  );
}

/**
 * Get database size information
 */
function kanews_get_database_size() {
  global $wpdb;
  
  $database_name = DB_NAME;
  $database_name_escaped = esc_sql( $database_name );
  $size_data = $wpdb->get_results( "
    SELECT 
      table_schema AS 'database_name',
      ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) AS 'size_mb',
      ROUND(SUM(data_length) / 1024 / 1024, 2) AS 'data_size_mb',
      ROUND(SUM(index_length) / 1024 / 1024, 2) AS 'index_size_mb',
      COUNT(*) AS 'table_count'
    FROM information_schema.TABLES 
    WHERE table_schema = '{$database_name_escaped}'
    GROUP BY table_schema
  ", ARRAY_A );
  
  if ( empty( $size_data ) ) {
    // Fallback: calculate from individual tables
    $tables = $wpdb->get_results( "SHOW TABLE STATUS", ARRAY_A );
    $total_size = 0;
    $total_data = 0;
    $total_index = 0;
    $table_count = 0;
    
    foreach ( $tables as $table ) {
      $total_size += $table['Data_length'] + $table['Index_length'];
      $total_data += $table['Data_length'];
      $total_index += $table['Index_length'];
      $table_count++;
    }
    
    return array(
      'size_mb' => round( $total_size / 1024 / 1024, 2 ),
      'data_size_mb' => round( $total_data / 1024 / 1024, 2 ),
      'index_size_mb' => round( $total_index / 1024 / 1024, 2 ),
      'table_count' => $table_count,
      'size_gb' => round( $total_size / 1024 / 1024 / 1024, 2 ),
      'formatted_size' => kanews_format_bytes( $total_size )
    );
  }
  
  $data = $size_data[0];
  
  return array(
    'size_mb' => floatval( $data['size_mb'] ),
    'data_size_mb' => floatval( $data['data_size_mb'] ),
    'index_size_mb' => floatval( $data['index_size_mb'] ),
    'table_count' => intval( $data['table_count'] ),
    'size_gb' => round( floatval( $data['size_mb'] ) / 1024, 2 ),
    'formatted_size' => kanews_format_bytes( floatval( $data['size_mb'] ) * 1024 * 1024 )
  );
}

/**
 * Format bytes to human readable format
 */
function kanews_format_bytes( $bytes, $precision = 2 ) {
  $units = array( 'B', 'KB', 'MB', 'GB', 'TB' );
  
  for ( $i = 0; $bytes > 1024 && $i < count( $units ) - 1; $i++ ) {
    $bytes /= 1024;
  }
  
  return round( $bytes, $precision ) . ' ' . $units[$i];
}

/**
 * Check for unused database tables
 */
function kanews_check_unused_tables() {
  global $wpdb;
  
  // Get all tables in the database
  $all_tables = $wpdb->get_results( "SHOW TABLES", ARRAY_N );
  $table_prefix = $wpdb->prefix;
  
  // WordPress core tables (should never be deleted)
  $core_tables = array(
    $table_prefix . 'posts',
    $table_prefix . 'postmeta',
    $table_prefix . 'comments',
    $table_prefix . 'commentmeta',
    $table_prefix . 'terms',
    $table_prefix . 'term_taxonomy',
    $table_prefix . 'term_relationships',
    $table_prefix . 'termmeta',
    $table_prefix . 'users',
    $table_prefix . 'usermeta',
    $table_prefix . 'options',
    $table_prefix . 'links',
  );
  
  // Get active plugins
  $active_plugins = get_option( 'active_plugins', array() );
  $active_plugin_tables = array();
  
  // Common plugin table patterns (we'll check if plugins are active)
  $plugin_table_patterns = array(
    'woocommerce' => array( $table_prefix . 'woocommerce_', $table_prefix . 'wc_' ),
    'yoast' => array( $table_prefix . 'yoast_' ),
    'rank_math' => array( $table_prefix . 'rank_math_' ),
    'elementor' => array( $table_prefix . 'elementor_' ),
    'wpml' => array( $table_prefix . 'icl_', $table_prefix . 'wpml_' ),
    'polylang' => array( $table_prefix . 'term_relationships_' ),
    'bbpress' => array( $table_prefix . 'bbp_' ),
    'buddypress' => array( $table_prefix . 'bp_' ),
    'contact_form_7' => array( $table_prefix . 'cf7_' ),
    'wp_super_cache' => array( $table_prefix . 'super_cache_' ),
    'wp_rocket' => array( $table_prefix . 'wp_rocket_' ),
  );
  
  // Check which plugins are active and add their tables
  foreach ( $active_plugins as $plugin ) {
    $plugin_slug = dirname( $plugin );
    foreach ( $plugin_table_patterns as $pattern_key => $patterns ) {
      if ( strpos( $plugin_slug, $pattern_key ) !== false || strpos( $plugin, $pattern_key ) !== false ) {
        $active_plugin_tables = array_merge( $active_plugin_tables, $patterns );
      }
    }
  }
  
  $unused_tables = array();
  $log = array();
  
  foreach ( $all_tables as $table ) {
    $table_name = $table[0];
    
    // Skip WordPress core tables
    if ( in_array( $table_name, $core_tables ) ) {
      continue;
    }
    
    // Skip active plugin tables
    $is_plugin_table = false;
    foreach ( $active_plugin_tables as $pattern ) {
      if ( strpos( $table_name, $pattern ) === 0 ) {
        $is_plugin_table = true;
        break;
      }
    }
    if ( $is_plugin_table ) {
      continue;
    }
    
    // Check if table is empty or has very old data
    $table_name_escaped = esc_sql( $table_name );
    $row_count = $wpdb->get_var( "SELECT COUNT(*) FROM `{$table_name_escaped}`" );
    
    // Get table size
    $table_info = $wpdb->get_row( $wpdb->prepare( "
      SELECT 
        ROUND(((data_length + index_length) / 1024 / 1024), 2) AS size_mb,
        table_rows
      FROM information_schema.TABLES 
      WHERE table_schema = DATABASE()
      AND table_name = %s
    ", $table_name ), ARRAY_A );
    
    $size_mb = isset( $table_info['size_mb'] ) ? floatval( $table_info['size_mb'] ) : 0;
    
    // Check if table is referenced in options or elsewhere
    $is_referenced = false;
    
    // Check in options table
    $option_check = $wpdb->get_var( $wpdb->prepare( "
      SELECT COUNT(*) FROM {$wpdb->options} 
      WHERE option_value LIKE %s
    ", '%' . $wpdb->esc_like( $table_name ) . '%' ) );
    
    if ( $option_check > 0 ) {
      $is_referenced = true;
    }
    
    // Consider table unused if:
    // 1. It's not a core table
    // 2. It's not from an active plugin
    // 3. It's empty or has very few rows
    // 4. It's not referenced in options
    if ( ! $is_referenced && ( $row_count == 0 || $row_count < 10 ) ) {
      $unused_tables[] = array(
        'name' => $table_name,
        'rows' => intval( $row_count ),
        'size_mb' => $size_mb,
        'formatted_size' => kanews_format_bytes( $size_mb * 1024 * 1024 )
      );
      
      $log[] = sprintf( 
        esc_html__( 'Tablo: %s - %d satır, %s', 'kanews' ), 
        $table_name, 
        $row_count,
        $size_mb > 0 ? $size_mb . ' MB' : esc_html__( 'Boş', 'kanews' )
      );
    }
  }
  
  $total_size = 0;
  foreach ( $unused_tables as $table ) {
    $total_size += $table['size_mb'];
  }
  
  $message = '';
  if ( count( $unused_tables ) > 0 ) {
    $message = sprintf( 
      esc_html__( '%d kullanılmayan tablo bulundu. Toplam boyut: %s', 'kanews' ), 
      count( $unused_tables ),
      kanews_format_bytes( $total_size * 1024 * 1024 )
    );
  } else {
    $message = esc_html__( 'Kullanılmayan tablo bulunamadı.', 'kanews' );
  }
  
  return array(
    'success' => true,
    'message' => $message,
    'unused_tables' => $unused_tables,
    'total_unused_tables' => count( $unused_tables ),
    'total_size_mb' => $total_size,
    'log' => $log
  );
}

/**
 * Get database statistics for optimizer
 */
add_action( 'wp_ajax_kanews_get_optimizer_stats', 'kanews_ajax_get_optimizer_stats' );
function kanews_ajax_get_optimizer_stats() {
  check_ajax_referer( 'kanews_optimize_nonce', 'nonce' );
  
  if ( ! current_user_can( 'manage_options' ) ) {
    wp_send_json_error( array( 'message' => esc_html__( 'Yetkiniz yok.', 'kanews' ) ) );
  }

  $meta_stats = kanews_get_empty_post_meta_stats();
  $duplicate_stats = kanews_get_duplicate_meta_stats();
  $db_size = kanews_get_database_size();

  wp_send_json_success( array(
    'post_meta' => $meta_stats,
    'duplicates' => $duplicate_stats,
    'database_size' => $db_size
  ) );
}

/**
 * AJAX handler for optimizer
 */
add_action( 'wp_ajax_kanews_optimize_database', 'kanews_ajax_optimize_database' );
function kanews_ajax_optimize_database() {
  check_ajax_referer( 'kanews_optimize_nonce', 'nonce' );
  
  if ( ! current_user_can( 'manage_options' ) ) {
    wp_send_json_error( array( 'message' => esc_html__( 'Yetkiniz yok.', 'kanews' ) ) );
  }

  $action = isset( $_POST['action_type'] ) ? sanitize_text_field( $_POST['action_type'] ) : '';
  $result = array();

  switch ( $action ) {
    case 'clean_post_meta':
      $result = kanews_clean_empty_post_meta();
      break;
    
    case 'remove_duplicates':
      $result = kanews_remove_duplicate_meta();
      break;
    
    case 'check_unused_tables':
      $result = kanews_check_unused_tables();
      break;
    
    case 'clean_all':
      $result2 = kanews_clean_empty_post_meta();
      $result3 = kanews_remove_duplicate_meta();
      
      $total_cleaned = ( isset( $result2['removed'] ) ? $result2['removed'] : 0 ) + 
                       ( isset( $result3['removed'] ) ? $result3['removed'] : 0 );
      
      $all_logs = array();
      if ( isset( $result2['log'] ) ) $all_logs = array_merge( $all_logs, $result2['log'] );
      if ( isset( $result3['log'] ) ) $all_logs = array_merge( $all_logs, $result3['log'] );
      
      $result = array(
        'success' => true,
        'message' => sprintf( esc_html__( 'Toplam %d kayıt temizlendi.', 'kanews' ), $total_cleaned ),
        'cleaned' => $total_cleaned,
        'log' => $all_logs,
        'results' => array(
          'post_meta' => $result2,
          'duplicates' => $result3
        )
      );
      break;
    
    default:
      wp_send_json_error( array( 'message' => esc_html__( 'Geçersiz işlem.', 'kanews' ) ) );
  }

  if ( $result['success'] ) {
    wp_send_json_success( $result );
  } else {
    wp_send_json_error( $result );
  }
}