<?php
/*-----------------------------------------------*/
/*  EXTHEM.ES
/*  PREMIUM WORDRESS THEMES
/*
/*  STOP DON'T TRY EDIT
/*  IF YOU DON'T KNOW PHP 
/*
/*  As Errors In Your Themes
/*  Are Not The Responsibility
/*  Of The DEVELOPERS
/*  @EXTHEM.ES
/*  
/*  Follow Social Media Exthem.es
/*  Youtube : https://www.youtube.com/channel/UCpcZNXk6ySLtwRSBN6fVyLA
/*  Facebook : https://www.facebook.com/groups/exthem.es
/*  Twitter : https://x.com/bangreyblog
/*  Instagram : https://www.instagram.com/exthem.es/
/*  Telegram : https://t.me/exthemes_helps
/*  TikTok : https://www.tiktok.com/@exthemes
/*	More Premium Themes Visit Now On https://exthem.es/
/*-----------------------------------------------*/
if ( ! defined( 'ABSPATH' ) ) exit; 
// Silence is golden.

/* --------------------------------------------------------------------
* show apk update notices
* ------------------------------------------------------------------ 
*/	   
if ( ! function_exists( 'show_apk_update_notices' ) ) 
{
	add_action( 'admin_notices', 'show_apk_update_notices' );
	function show_apk_update_notices() 
	{
		// 1. Only show to users who can edit posts
		if ( ! current_user_can( 'edit_posts' ) ) {
			return;
		}

		// 2. Only show on the Apps Updates page
		if ( ! isset( $_GET['page'] ) || $_GET['page'] !== 'app-update-list' ) {
			return;
		}

		// 3. Cek apakah fitur notice di-app-list diaktifkan
		$show_notice_on_list = get_option('app_update_show_notice_on_app_list', '1') === '1';

		// Jika notice dimatikan → langsung keluar (tidak perlu lanjut proses)
		if (!$show_notice_on_list) {
			return;
		}

		// Optional: Further restrict to exact screen (uncomment jika perlu)
		// $screen = get_current_screen();
		// if ( $screen && $screen->id !== 'toplevel_page_apps_updates' ) return;

		// 3. Count posts with pending updates
		$update_count = apk_update_count_posts(); // Asumsi fungsi ini sudah ada

		if ( $update_count <= 0 ) {
			return; // No updates → no notice
		}

		global $opt_themes;

		// 4. Trigger update checks untuk post yang outdated (>10 menit atau belum pernah dicek)
		$limit_check1 		= isset( $opt_themes['lim_post'] ) ? (int) $opt_themes['lim_post'] : 20;
		$limit_checkx 		= $opt_themes['lim_post'];
	 
		$batch_size       	= get_option( 'app_update_batch_size', 20 );
		$limit_check 		= isset( $batch_size ) ? (int) $batch_size : $limit_checkx;
		
		$args = array(
			'posts_per_page' => $batch_size,
			'post_type'      => 'post',
			'post_status'    => 'publish',
			'orderby'        => 'meta_value_num',   // Urutkan dari yang paling lama belum dicek
			'meta_key'       => '_time_scrape_app_update',
			'order'          => 'ASC',              // ASC = paling kecil dulu (lama belum update)
			'fields'         => 'ids',              // Hanya ambil ID untuk hemat memory
			'meta_query'     => array(
				'relation' => 'OR',
				array(
					'key'     => '_time_scrape_app_update',
					'value'   => time() - 600,  // Lebih dari 10 menit yang lalu
					'compare' => '<',
					'type'    => 'NUMERIC',
				),
				array(
					'key'     => '_time_scrape_app_update',
					'compare' => 'NOT EXISTS',
				),
			),
		);

		$query = new WP_Query( $args );

		$checked_count = 0;
		
		// Contoh di halaman daftar aplikasi
		//if (get_option('app_update_show_notice_on_app_list', '1') === '1') {
			// Tampilkan notice sukses/gagal update aplikasi
			// ...
		//}

		if ( $query->have_posts() ) {
			foreach ( $query->posts as $post_id ) {
				if (get_option('app_update_show_notice_on_app_list', '1') === '1') {
				app_update_available( $post_id, true );
				} else {
				app_update_available( $post_id, false );
				}
				$checked_count++;
			}
		}

		// 5. Build the message (singular/plural)
		$message = sprintf(
			_n(
				'<strong>%d app</strong> has a new version on Google Play!',
				'<strong>%d apps</strong> have a new version on Google Play!',
				$update_count,
				'mediart' // Text domain, sesuaikan jika berbeda
			),
			$update_count
		);

		// Optional info tentang checking otomatis
		$checking_info = '';
		if ( $checked_count > 0 ) {
			$checking_info = sprintf(
				'<br><em>Automatically checked updates for %d outdated apps in the background.</em>',
				$checked_count
			);
		}

		// 6. Output the notice (sudah tidak dikomentari lagi)
		?>
		<div class="notice notice-success is-dismissible">
			<p>
				<?php echo wp_kses_post( $message ); ?>
				<?php echo $checking_info; ?>
			</p>
			<p>
				If your site is <strong>HEAVY</strong> to load, please <strong>DISABLE</strong> the Apps Updates Version Notices option in the Theme Panel.
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=_options&tab=1' ) ); ?>">
					Click Here to Disable
				</a>
			</p>
		</div>
		<?php
	}
}

// 2. Fungsi terpisah untuk cron hourly (hanya cek update, tanpa HTML notice)
if ( ! function_exists( 'my_hourly_app_update_check' ) ) 
{
	function my_hourly_app_update_check() 
	{
		global $opt_themes;

		// 4. Trigger update checks untuk post yang outdated (>10 menit atau belum pernah dicek)
		$limit_check1 		= isset( $opt_themes['lim_post'] ) ? (int) $opt_themes['lim_post'] : 20;
		$limit_checkx 		= $opt_themes['lim_post'];
	 
		$batch_size       	= get_option( 'app_update_batch_size', 20 );
		$limit_check 		= isset( $batch_size ) ? (int) $batch_size : $limit_checkx;
		
		$args2 = array(
			'posts_per_page' => $limit_check,
			'post_type'      => 'post',
			'post_status'    => 'publish',
			'orderby'        => 'meta_value_num',
			'meta_key'       => '_time_scrape_app_update',
			'order'          => 'ASC',
			'fields'         => 'ids',
			'meta_query'     => array(
				'relation' => 'OR',
				array(
					'key'     => '_time_scrape_app_update',
					'value'   => time() - 3600, // >1 jam (lebih longgar di cron)
					'compare' => '<',
					'type'    => 'NUMERIC',
				),
				array(
					'key'     => '_time_scrape_app_update',
					'compare' => 'NOT EXISTS',
				),
			),
		);

		$args = array(
			'posts_per_page' => $limit_check,
			'post_type'      => 'post',
			'post_status'    => 'publish',
			'orderby'        => 'meta_value_num',   // Urutkan dari yang paling lama belum dicek
			'meta_key'       => '_time_scrape_app_update',
			'order'          => 'ASC',              // ASC = paling kecil dulu (lama belum update)
			'fields'         => 'ids',              // Hanya ambil ID untuk hemat memory
			'meta_query'     => array(
				'relation' => 'OR',
				array(
					'key'     => '_time_scrape_app_update',
					'value'   => time() - 3600,  // Lebih dari 10 menit yang lalu
					'compare' => '<',
					'type'    => 'NUMERIC',
				),
				array(
					'key'     => '_time_scrape_app_update',
					'compare' => 'NOT EXISTS',
				),
			),
		);
		
		$query = new WP_Query( $args );

		if ( $query->have_posts() ) {
			foreach ( $query->posts as $post_id ) {
				app_update_available( $post_id, false ); // No debug di cron
			}
		}
	}
	// Hook cron ke fungsi yang benar
	add_action( 'my_hourly_app_update', 'my_hourly_app_update_check' );
}

// Jadwalkan cron hourly (jika belum ada)
if ( ! wp_next_scheduled( 'my_hourly_app_update' ) ) {
    wp_schedule_event( time(), 'hourly', 'my_hourly_app_update' );
}
 
/* --------------------------------------------------------------------
* show apk update notices dashboard
* ------------------------------------------------------------------ 
*/	  
if ( ! function_exists( 'show_apk_update_notices_dashboard' ) ) 
{
	add_action( 'admin_notices', 'show_apk_update_notices_dashboard' );
	function show_apk_update_notices_dashboard() 
	{
		// 1. Only show to users who can edit posts
		if ( ! current_user_can( 'edit_posts' ) ) {
			return;
		}
		
		// 2. Get current screen for reliable detection
		$screen = get_current_screen();
		
		/* 

		// 3. Only show on the main Dashboard page
		// The dashboard screen ID is always 'dashboard'
		if ( ! $screen || $screen->id !== 'dashboard' ) {
			return;
		}
		*/
	 

		// 3. DO NOT show on the apps_updates page
		// This checks if the screen ID contains 'apps_updates' (works for submenu or top-level)
		if ( $screen && strpos( $screen->id, 'app-update-list' ) !== false ) {
			return;
		}
		
		// 4. Count posts with pending updates
		$update_count = apk_update_count_posts();

		// If no updates, don't show anything
		if ( $update_count <= 0 ) {
			return;
		}

		// 5. Build singular/plural message
		$message = sprintf(
			_n(
				'<strong>%d app</strong> has a new version on Google Play!',
				'<strong>%d apps</strong> have a new version on Google Play!',
				$update_count,
				'mediart'
			),
			$update_count
		);

		// 6. Output the notice on Dashboard only
		?>
		<div class="notice notice-error is-dismissible">
			<p>
				<?php echo wp_kses_post( $message ); ?>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=app-update-list' ) ); ?>" style="margin-left:10px;">
					View all →
				</a>
			</p>
			<p>
				If your site is <strong>HEAVY</strong> to load, please <strong>DISABLE</strong> the Apps Updates Version Notices option in the Theme Panel. 
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=_options&tab=1' ) ); ?>">
					Click Here to Disable →
				</a>
			</p>
		</div>
		<?php
	}
}

