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

/* --------------------------------------------------------------------
* CHECK BUTTON on edit post (No external files)
* ------------------------------------------------------------------ 
*/	  
if ( ! function_exists( 'apk_update_add_force_check_single_post' ) ) 
{
	add_action('add_meta_boxes', 'apk_update_add_force_check_single_post');
	function apk_update_add_force_check_single_post() 
	{
		add_meta_box(
			'app_update_force_check',
			'APK Update Checker',
			'apk_update_render_force_check_single_post',
			'post',		   // Change to your post type if needed
			'side',
			'high'
		);
	}
}

if ( ! function_exists( 'apk_update_render_force_check_single_post' ) ) 
{
	//add_action( 'post_submitbox_misc_actions', 'apk_update_render_force_check_single_post' );
	function apk_update_render_force_check_single_post($post) 
	{
		$appid			= get_post_meta($post->ID, 'wp_GP_ID', true);
		$current_ver	= get_post_meta($post->ID, 'wp_version_GP', true);
		$available		= get_post_meta($post->ID, 'available_updated', true);
		$available_ver 	= get_post_meta($post->ID, 'available_version', true);
		$last_checked  	= get_post_meta($post->ID, '_time_scrape_app_update', true);
		$last_checked  	= $last_checked ? human_time_diff($last_checked) . ' ago' : 'Never';

		if (empty($appid)) {
			echo '<p><strong>No Google Play ID set.</strong></p>';
			return;
		}

		wp_nonce_field('app_update_force_check_nonce', 'app_update_force_check_nonce');
		?>

		<div id="mediart-check-result" style="font-size:13px;line-height:1.4;">
			<?php if ($available === 'yes'): ?>
				<p style="color:#d63638;font-weight:bold;margin:0 0 8px;">Update Available!</p>
				<p style="margin:0 0 4px;">Current version: <code style="background:#f0f0f0;padding:2px 6px;border-radius:3px;"><?php echo esc_html($current_ver); ?></code></p>
				<p style="margin:0 0 8px;">→ New version: <strong style="color:green;"><?php echo esc_html($available_ver); ?></strong></p>
			<?php else: ?>
				<p style="color:green;font-weight:bold;margin:0 0 8px;">Up to date</p>
				<p style="margin:0 0 8px;">Version: <code style="background:#f0f0f0;padding:2px 6px;border-radius:3px;"><?php echo esc_html($current_ver ?: '—'); ?></code></p>
			<?php endif; ?>

			<p style="margin:0 0 12px;color:#666;"><small>Last checked: <?php echo $last_checked; ?></small></p>

			<button type="button" id="mediart-force-check-btn" class="button button-primary" style="width:100%;">
				Force Check Now
			</button>
			<div id="mediart-spinner" style="display:none;margin-top:8px;text-align:center;">
				<span style="color:#2271b1;font-weight:bold;">Checking...</span>
			</div>
		</div>

		<style>
		#mediart-check-result code { font-size:11px; }
		#mediart-force-check-btn:disabled { opacity:0.6; }
		</style>

		<script type="text/javascript">
		jQuery(function($){
			$('#mediart-force-check-btn').on('click', function(){
				var btn = $(this);
				var spinner = $('#mediart-spinner');
				var container = $('#mediart-check-result');

				btn.prop('disabled', true);
				spinner.show();

				$.post(ajaxurl, {
					action: 'app_update_force_check',
					post_id: <?php echo $post->ID; ?>,
					nonce: '<?php echo wp_create_nonce('app_update_force_check_nonce'); ?>'
				}, function(r){
					if (r.success) {
						var d = r.data;
						var html = '';

						if (d.update_available) {
							html += '<p style="color:#d63638;font-weight:bold;margin:0 0 8px;">Update Available!</p>';
							html += '<p style="margin:0 0 4px;">Current version: <code style="background:#f0f0f0;padding:2px 6px;border-radius:3px;">'+d.current_version+'</code></p>';
							html += '<p style="margin:0 0 8px;">→ New version: <strong style="color:green;">'+d.available_version+'</strong></p>';
						} else {
							html += '<p style="color:green;font-weight:bold;margin:0 0 8px;">Up to date</p>';
							html += '<p style="margin:0 0 8px;">Version: <code style="background:#f0f0f0;padding:2px 6px;border-radius:3px;">'+(d.current_version || '—')+'</code></p>';
						}

						html += '<p style="margin:0 0 12px;color:#666;"><small>Last checked: just now</small></p>';
						html += '<button type="button" id="mediart-force-check-btn" class="button button-primary" style="width:100%;">Force Check Now</button>';
						html += '<div id="mediart-spinner" style="display:none;margin-top:8px;text-align:center;"><span style="color:#2271b1;font-weight:bold;">Checking...</span></div>';

						container.html(html);
					} else {
						alert('Error: ' + (r.data.message || 'Something went wrong'));
					}
				}).always(function(){
					spinner.hide();
					btn.prop('disabled', false);
				});
			});
		});
		</script>

		<?php
	}
}

/* --------------------------------------------------------------------
* AJAX Handler (same as before — keep this)
* ------------------------------------------------------------------ 
*/	   
if ( ! function_exists( 'apk_update_handle_force_check' ) ) 
{
	add_action('wp_ajax_app_update_force_check', 'apk_update_handle_force_check');
	function apk_update_handle_force_check() 
	{
		check_ajax_referer('app_update_force_check_nonce', 'nonce');

		$post_id 		= isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;
		if (!$post_id || !current_user_can('edit_post', $post_id)) {
			wp_send_json_error(['message' => 'Permission denied']);
		}

		ob_start();
		$has_update 	= app_update_available($post_id, true);
		$debug 			= ob_get_clean();

		wp_send_json_success([
			'updated'				=> $has_update,
			'current_version'   	=> get_post_meta($post_id, 'wp_version_GP', true),
			'available_version' 	=> get_post_meta($post_id, 'available_version', true),
			'available_updated'  	=> get_post_meta($post_id, 'available_updated', true) === 'yes',
			'last_checked'	  		=> human_time_diff(get_post_meta($post_id, '_time_scrape_app_update', true)) . ' ago',
			'debug'			 		=> $debug ? strip_tags($debug) : null
		]);
	}
}

/* --------------------------------------------------------------------
* Add meta box with manual check button (or just inject into post submit box)
* ------------------------------------------------------------------ 
*/	    
if ( ! function_exists( 'available_updates_add_manual_check_button' ) ) 
{
	//add_action( 'post_submitbox_misc_actions', 'available_updates_add_manual_check_button' );
	function available_updates_add_manual_check_button( $post ) 
	{
		// Optional: limit to specific post types
		$allowed_types 	= [ 'post' ];
		if ( ! in_array( $post->post_type, $allowed_types ) ) return;

		$has_gp_id 		= ! empty( get_post_meta( $post->ID, 'wp_GP_ID', true ) );
		if ( ! $has_gp_id ) return;

		// Nonce for security
		$nonce 			= wp_create_nonce( 'available_updates_manual_apk_check_' . $post->ID );
		
		?>
		<div class="misc-pub-section mediart-manual-check" style="border-top:1px solid #ddd;padding-top:10px;margin-top:15px;">
			<strong>Apps Update Check:</strong> 
			
			<?php
			$last 		= get_post_meta( $post->ID, '_time_scrape_app_update', true );
			if ( $last ) {
				echo '<p>Last checked: ' . date_i18n( 'd M Y H:i', $last ) . '</p>';
			}
			?>
			<button type="button" style="margin: .5rem 0;"
					class="button button-secondary"
					id="mediart-manual-check-btn"
					data-post-id="<?php echo esc_attr( $post->ID ); ?>"
					data-nonce="<?php echo esc_attr( $nonce ); ?>"> 
					Check for New Version
			</button>
			
			<p id="mediart-check-result" style="font-weight:bold;"></p>
			<p id="mediart-check-spinner" style="display:none;">Loading...</p>
		</div>

		<script type="text/javascript">
			jQuery(document).ready(function($) {
				$('#mediart-manual-check-btn').on('click', function() {
					var btn	  = $(this);
					var postId   = btn.data('post-id');
					var nonce	= btn.data('nonce');
					var result   = $('#mediart-check-result');
					var spinner  = $('#mediart-check-spinner');

					// UI feedback
					btn.prop('disabled', true);
					spinner.show();
					result.text('');

					$.post(ajaxurl, {
						action: 'available_updates_manual_apk_check',
						post_id: postId,
						nonce: nonce
					}, function( response ) {
						spinner.hide();
						btn.prop('disabled', false);

						if ( response.success ) {
							if ( response.data.update_found ) {
								result.html('<span>⚠️ <b style="color:orange;">UPDATE AVAILABLE!</b> <strong>( v' + response.data.new_version + ' )</strong></span>');
							} else {
								result.html('<span>👍 <b style="color:green;">ITS A LATEST VERSION</b> ( v' + response.data.current_version + ' )</span>');
							}
						} else {
							result.html('<p>&nbsp;</p><span style="color:red;">Error: ' + response.data + '</span>');
						}
					}).fail(function() {
						spinner.hide();
						btn.prop('disabled', false);
						result.html('<span style="color:red;">Request failed</span>');
					});
				});
			});
		</script>
		<?php
	}
}
  
if ( ! function_exists( 'available_updates_handle_manual_apk_check' ) ) 
{
	add_action( 'wp_ajax_available_updates_manual_apk_check', 'available_updates_handle_manual_apk_check' );
	function available_updates_handle_manual_apk_check() 
	{
		// Security checks
		check_ajax_referer( 'available_updates_manual_apk_check_' . $_POST['post_id'], 'nonce' );

		if ( ! current_user_can( 'edit_posts' ) ) {
			wp_send_json_error( 'Permission denied' );
		}

		$post_id 			= absint( $_POST['post_id'] );
		if ( ! $post_id || ! get_post( $post_id ) ) {
			wp_send_json_error( 'Invalid post ID' );
		}

		// Run the actual check with debug = true (we capture output)
		ob_start();
		$update_found 		= app_update_available( $post_id, false ); // true = debug output
		$debug_output 		= ob_get_clean();
		$current_version 	= get_post_meta( $post_id, 'wp_version_GP', true );
		$available_version 	= get_post_meta( $post_id, 'available_version', true );

		if ( $available_version ) {
			wp_send_json_success( [
				'update_found'	 	=> true,
				'new_version'	  	=> $available_version,
				'current_version'  	=> $current_version,
				'debug'				=> $debug_output // optional: for advanced users
			] );
		} else {
			wp_send_json_success( [
				'update_found'	 	=> false,
				'current_version'  	=> $current_version,
				'debug'				=> $debug_output
			] );
		}
	}
}
  
  