<?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.

/* --------------------------------------------------------------------
* Admin Bar: Apps Update Checker + Force Check
* Add item to Admin Bar
* ------------------------------------------------------------------ 
*/	 
if ( ! function_exists( 'admin_bar_app_update' ) ) 
{
	add_action( 'admin_bar_menu', 'admin_bar_app_update', 999 );
	function admin_bar_app_update( $wp_admin_bar ) 
	{
		if ( ! current_user_can( 'edit_posts' ) ) {
			return;
		}

		// Efficient count of posts with available update
		global $wpdb;
	 
		$update_count = apk_update_count_posts();

		$badge = $update_count > 0
			? '<span style="background:#d63638;color:#fff;border-radius:9px;padding:0 6px;font-size:11px;margin-left:5px;line-height:18px;">' . $update_count . '</span>'
			: '';

		$title = 'Apps Updates' . $badge;

		// Main parent menu
		$wp_admin_bar->add_menu( array(
			'id'    => 'mediart-apk-updates',
			'title' => '<span class="ab-icon dashicons dashicons-update"></span> ' . $title,
			'href'  => admin_url( 'admin.php?page=app-update-list' ),
			'meta'  => array( 'title' => 'View Apps Updates Page' ),
		) );

		// "Check All Now" button
		$force_url = wp_nonce_url(
			add_query_arg( 'app_update_force_check', '1' ),
			'app_update_force_check_all'
		);

		$wp_admin_bar->add_menu( array(
			'parent' => 'mediart-apk-updates',
			'id'     => 'mediart-check-all',
			'title'  => '<span class="ab-icon dashicons dashicons-update" style="font-size:16px;"></span> Check All Apps Now',
			'href'   => $force_url,
			'meta'   => array( 'title' => 'Force check all apps for updates immediately' ),
		) );
		
		// Show list of apps with updates
		// Gunakan fungsi apk_get_update_posts_list() untuk ambil 10 app teratas
		$apps = apk_get_update_posts_list( 10 ); // Limit 10 untuk admin bar

		// Tampilkan daftar app di submenu
		foreach ( $apps as $app ) {
			$post_id       = intval( $app->ID );
			$display_title = esc_html( $app->display_title );
			$new_version   = esc_html( $app->available_version );
			$version_text  = $new_version ? '<span style="color:#2271b1;font-size:11px;margin-left:4px;">→ v' . $new_version . '</span>' : '';

			$wp_admin_bar->add_menu( array(
				'parent' => 'mediart-apk-updates',
				'id'     => 'mediart-update-' . $post_id,
				'title'  => $display_title . $version_text,
				'href'   => get_edit_post_link( $post_id ),
				'meta'   => array(
					'target' => '_blank',
					'title'  => sprintf( __( 'Edit: %s', TEXT_DOMAIN ), $display_title ),
				),
			) );
		}

		// Jika ada lebih dari 10 update
		if ( $update_count > 10 ) {
			$more_count = $update_count - 10;
			$wp_admin_bar->add_menu( array(
				'parent' => 'mediart-apk-updates',
				'title'  => sprintf( __( '… and %s more', TEXT_DOMAIN ), $more_count ),
				'href'   => admin_url( 'admin.php?page=app-update-list' ),
				'meta'   => array( 'title' => __( 'View all apps needing updates', TEXT_DOMAIN ) ),
			) );
		}
	}
}

/* --------------------------------------------------------------------
* AUTO-REFRESH ADMIN BAR UPDATE BADGE (Every 45 seconds)
* ------------------------------------------------------------------ 
*/	  
if ( ! function_exists( 'apk_updates_auto_refresh_badge' ) ) 
{
	add_action('admin_footer', 'apk_updates_auto_refresh_badge');
	add_action('wp_footer', 'apk_updates_auto_refresh_badge'); // Also works on frontend if admin bar shown

	function apk_updates_auto_refresh_badge() 
	{
		// Only for logged-in users who can edit posts
		if (!is_user_logged_in() || !current_user_can('edit_posts')) return;
		if (!is_admin_bar_showing()) return;
		?>
		<script type="text/javascript">
		(function($) {
			if (typeof $ === 'undefined') return;

			function updateApkBadge() {
				$.post(ajaxurl, {
					action: 'apk_get_update_count'
				}, function(res) {
					if (!res.success) return;

					var badge = $('#wp-admin-bar-mediart-apk-updates .ab-item .ab-icon').next();
					var menuItem = $('#wp-admin-bar-mediart-apk-updates > .ab-item');
					var badge2 = $('#toplevel_page_apps_updates .plugin-count');

					// Update badge #toplevel_page_apps_updates .plugin-count
					if (res.data.count > 0) {
						if (badge.length === 0) {
							menuItem.append('<span style="display:inline-block;background:#d63638;color:#fff;border-radius:10px;padding:0 7px;font-size:11px;font-weight:bold;line-height:18px;min-width:18px;text-align:center;margin-left:6px;">' + res.data.count + '</span>');
							badge2.text(res.data.count);
						} else {
							badge.text(res.data.count);
							badge2.text(res.data.count);
						}

						// Optional: tiny bounce animation
						badge.css({transform: 'scale(1.3)', opacity: 0.8})
							 .animate({transform: 'scale(1)', opacity: 1}, 300);

						// Optional: browser notification
						if (res.data.count > (window.lastApkCount || 0)) {
							if (Notification.permission === "granted") {
								new Notification("New APK Update Available!", {
									body: res.data.count + " app(s) have new versions",
									icon: "<?php echo includes_url('images/w-logo-blue.png'); ?>"
								});
							}
						}
					} else {
						badge.remove();
						badge2.remove();
					}

					window.lastApkCount = res.data.count;
				});
			}

			// Run once on load
			$(document).ready(function() {
				updateApkBadge();
			});

			// Then every 45 seconds
			setInterval(updateApkBadge, 45000);

			// Optional: Ask for notification permission on first hover
			$('#wp-admin-bar-mediart-apk-updates').one('mouseenter', function() {
				if (Notification.permission === "default") {
					Notification.requestPermission();
				}
			});

		})(jQuery);
		</script>
		<?php
	}
}

/* --------------------------------------------------------------------
* AJAX: Return current update count (super fast)
* ------------------------------------------------------------------ 
*/	   
if ( ! function_exists( 'apk_get_update_count' ) ) 
{
	add_action('wp_ajax_apk_get_update_count', 'apk_get_update_count');
	function apk_get_update_count() 
	{
		if (!current_user_can('edit_posts')) {
			wp_send_json_error();
		}

		global $wpdb;
		/* 
		$count2 = (int) $wpdb->get_var(
			"SELECT COUNT(*) FROM {$wpdb->postmeta} 
			 WHERE meta_key = 'available_updated' 
			   AND meta_value = 'yes'"
		);

		$count3 = (int) $wpdb->get_var(
			"SELECT COUNT(DISTINCT p.ID) FROM {$wpdb->posts} p
			 INNER JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id
			 WHERE p.post_type = 'post'
			   AND p.post_status = 'publish'
			   AND pm.meta_key = 'wp_GP_ID'
			   AND pm.meta_value != ''
			   AND EXISTS (
				 SELECT 1 FROM {$wpdb->postmeta} pm2 
				 WHERE pm2.post_id = p.ID 
				   AND pm2.meta_key = 'available_updated' 
				   AND pm2.meta_value = 'yes'
			   )"
		); 
		*/
		$count = apk_update_count_posts();
		wp_send_json_success(['count' => $count]);
	}
}
