<?php  
 
// Make sure SimpleHTMLDOM is available (usually via a plugin or include)
if ( ! function_exists('str_get_html') ) 
{
	require_once get_template_directory().'/libs/addons/inc/dom.php';
}

function is_apk_update_available( $post_id, $debug=false ) 
{
	$post_id = (int) $post_id;	
 
	if ( ! $post_id || ! get_post( $post_id ) ) {
		if ( $debug ) echo "<br/>[ERROR] Invalid post ID: $post_id";
		return false;
	}

	// Prevent duplicate processing (in case multiple cron jobs run at once)
	if ( get_post_meta( $post_id, '_mediart_scraping_progress', true ) ) {
		if ( $debug ) echo "<br/>[SKIP] Post $post_id is already being processed.";
		return false;
	}

	$appid 	= get_post_meta( $post_id, 'wp_GP_ID', true );
	$title_GP	= get_post_meta( $post_id, 'wp_title_GP', true ); 
 
	if ( empty( $appid ) ) {
		if ( $debug ) echo "<br/>[SKIP] Post $post_id has no Google Play ID";
		update_post_meta( $post_id, '_mediart_scraped_time', time() );
		return false;
	}
	 

	// Mark as being processed + update timestamp
	update_post_meta( $post_id, '_mediart_scraping_progress', true );
	update_post_meta( $post_id, '_mediart_scraped_time', time() );

	if ( $debug ) {
		echo "<br/>Checking <strong>Post ID $post_id</strong> → <strong>$title_GP</strong>";
	}
	
	$scraper		= new Go_Curl();
	//$appid		= get_post_meta( get_the_ID(), 'wp_GP_ID', true ); 
	$url			= 'https://a-a.my.id/gps.php?pkgid='.$appid;  
	$g_data 		= $scraper->scrape_sitex( $url );

	if ( ! $g_data || strlen( $g_data ) < 500 ) {
		if ( $debug ) echo " <span style='color:red;'>[ERROR] Failed to fetch data from scraper</span>";
		delete_post_meta( $post_id, '_mediart_scraping_progress' );
		return false;
	}
	
	$n_version_raw	= $scraper->match( '/<div class="c_version">(.*?)<\/div>/ms', $g_data, 1 );
	$n_version	= trim( $n_version_raw ); 
	
	//$c_version	= get_post_meta( $post_id, 'wp_GP_version', true );
	$c_version	= get_post_meta( $post_id, 'wp_version_GP', true );
	
	// Clean version numbers (remove +hotfix, build metadata, etc.)
	//$n_version = preg_replace( '/\+.*$/', '', $n_version1 );
	//$c_version = $c_version1 ? preg_replace( '/\+.*$/', '', trim( $c_version1 ) ) : '';


	if ( empty( $n_version ) ) {
		if ( $debug ) echo " <span style='color:orange;'>[WARN] Could not parse new version from response</span>";
		delete_post_meta( $post_id, '_mediart_scraping_progress' );
		return false;
	}
	
	// Always update the stored version if different (handles rollbacks too)
	if ( $n_version && $n_version !== $c_version ) {
		//update_post_meta( $post_id, 'wp_version_GP', $n_version );
		if ( $debug ) echo " <strong>v.$c_version</strong>";
	}


	//if ( $debug ) {
	//	echo " <strong>v.$c_version</strong> ";
	//}

	// Compare versions
	//if ( version_compare( $c_version, $n_version, '>' ) ) {
		
	if (version_compare($n_version, $c_version ) > 0 ) {

	// UPDATE FOUND!	
	update_post_meta( $post_id, 'update_available', 'yes' );
	update_post_meta( $post_id, 'available_version', $n_version );
	update_post_meta( $post_id, '_mediart_last_update_found', time() );

	if ( $debug ) {
		echo " → v.$n_version <span style='color:green;font-weight:bold;'>UPDATE AVAILABLE!</span>";
	}

	// Prepare app info for action hook
	$appInfo = [
		'post_id'		  => $post_id,
		'appid'			=> $appid,
		'title'			=> $title_GP,
		'current_version'  => $c_version,
		'new_version'	  => $n_version,
	];

	// Remove lock ONLY after everything succeeded
	delete_post_meta( $post_id, '_mediart_scraping_progress' );

	// Trigger action (for downloads, notifications, etc.)
	do_action( 'mediart_apk_update_detected', $post_id, $appInfo );
	return true;

	} else {
		delete_post_meta( $post_id, '_mediart_scraping_progress' ); 
		delete_post_meta( $post_id, '_mediart_last_update_found' );
		delete_post_meta( $post_id, 'update_available' );
		delete_post_meta( $post_id, 'available_version' );
		return true;
	}
	 
	
	// No update – just keep current version
	if ( $c_version !== $n_version ) {
		//update_post_meta( $post_id, 'wp_version_GP', $current_version );
	}
	
	// No update
	delete_post_meta( $post_id, 'update_available' );
	delete_post_meta( $post_id, 'available_version' );	
	// optional: delete_post_meta( $post_id, '_mediart_last_update_found' );
	
	if ( $debug ) echo " <span style='color:gray;'> → Up to date</span>";
	delete_post_meta( $post_id, '_mediart_scraping_progress' );
	return false; 
}

function mediart_clear_update_flag_on_manual_save( $post_id, $post, $update ) 
{

	// Safety checks
	if ( wp_is_post_revision( $post_id ) || wp_is_post_autosave( $post_id ) ) {
		return;
	}

	if ( ! current_user_can( 'edit_post', $post_id ) ) {
		return;
	}

	// Only proceed if this is a real save from edit screen (not cron, import, etc.)
	if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
		return;
	}

	// Optional: only for your specific post type if needed
	// if ( $post->post_type !== 'post' ) return;

	// Check if the version field was submitted (even if empty — means admin saved it)
	if ( isset( $_POST['wp_version_GP'] ) || isset( $_POST['_wpnonce'] ) ) {

		// Clear update flags — admin has acknowledged/updated the version
		delete_post_meta( $post_id, 'update_available' );
		delete_post_meta( $post_id, 'available_version' );
		delete_post_meta( $post_id, '_mediart_last_update_found' ); // optional

		// Optional: add a log that admin cleared it
		add_post_meta( $post_id, '_mediart_update_cleared_by_admin', current_time('mysql'), true );
	}
}

// Add this once (e.g. in functions.php or your plugin)
add_filter( 'cron_schedules', 'mediart_cron_schedule' );
function mediart_cron_schedule( $schedules ) 
{
	$schedules['everyminutes'] = array(
		'interval' => 1 * MINUTE_IN_SECONDS,  // 600 seconds
		'display'  => __( 'Every 1 Minutes' )
	);
	//$schedules['every10minutes'] = array(
	//	'interval' => 1 * MINUTE_IN_SECONDS,  // 600 seconds
	//	'display'  => __( 'Every 10 Minutes' )
	//);
	return $schedules;
}


// Now schedule it properly
if ( ! wp_next_scheduled( 'mediart_check_apk_updates' ) ) 
{
	wp_schedule_event( time(), 'everyminutes', 'mediart_check_apk_updates' );
} 


add_action( 'mediart_check_apk_updates', 'mediart_run_apk_checks' );
function mediart_run_apk_checks() 
{
	// Paste the full query + loop here
	// (same code as above, without the echo if you don't want email noise)
		
		
	// Test one post  
	global $opt_themes;
	// ——— CONFIG ———
	$check_interval   = 1 * MINUTE_IN_SECONDS;	// Change to 3, 12, 24 etc. if you want
	$posts_per_run	= $opt_themes['lim_post'];	// How many apps to check per cron run
	$delay_between	= 750000;	// microseconds (0.75 sec) – be gentle
	$send_email_alert = false;	// Set false if you don’t want emails
	// ——————————————


	$check_interval = 6 * HOUR_IN_SECONDS; // Change 6 to your desired hours (3–24 recommended)
	// Or loop through posts that need checking
	$args = array(
		'posts_per_page' => $opt_themes['lim_post'],
		'post_type'	  => 'post',
		'meta_query'	 => array(
			'relation' => 'OR',
			array(
				'key'	 => '_mediart_scraped_time',
				'value'   => time() - $check_interval, 
				'compare' => '<',
				'type'	=> 'NUMERIC'
			),
			array(
				'key'	 => '_mediart_scraped_time',
				'compare' => 'NOT EXISTS'
			)
		),
		'fields' => 'ids'
	);

	$query = new WP_Query( $args );
	echo "Checking " . count( $query->posts ) . " apps (interval: every " . ($check_interval / 3600) . " hours)\n\n";

	foreach ( $query->posts as $pid ) {
		is_apk_update_available( $pid, true );
		echo "\n";
		// Optional: small delay to be gentle on the scraper
		usleep(500000); // 0.5 second
			
	}

}

add_action('init', function() 
{
	if (!isset($_GET['fastcheck'])) return;
	if (!current_user_can('manage_options')) wp_die('No access');

	$ids = array_filter(array_map('intval', explode(',', $_GET['fastcheck'])));
	echo "<pre style='background:#000;color:#0f0;padding:20px;font-family:monospace;'>";
	foreach ($ids as $id) {
		if (get_post($id)) {
			echo "POST ID $id → ";
			is_apk_update_available($id, false);
			echo "\n\n";
		}
	}
	echo "</pre>";
	die();
});

// ——————————————————————————————————————
// 1. MANUAL CRON + RESET TOOL (with security!)
// ——————————————————————————————————————  

add_action( 'init', 'mediart_manual_cron_and_reset' );
function mediart_manual_cron_and_reset() 
{
	// Only admins can use this
	if ( ! current_user_can( 'manage_options' ) ) {
		return;
	}

	// SECRET KEY – change this to anything you want (prevents random people from running it)
	$secret = 'a123456';   // ← CHANGE THIS!
	
	if ( isset( $_GET['check_updates'] ) && $_GET['check_updates'] === $secret ) {
	//http://zplay.test/?check_updates=123456
		// Optional: show debug output
		$debug = true;
		echo '<pre style="background:#000;color:#0f0;padding:20px;font-family:monospace;">';

		// ——— RESET ALL _mediart_scraped_time (force recheck everything) ———
		if ( isset( $_GET['reset'] ) && $_GET['reset'] === 'yes' ) {
			global $wpdb;
			$deleted = $wpdb->delete(
				$wpdb->postmeta,
				array( 'meta_key' => '_mediart_scraped_time' ),
				array( '%s' )
			);
			echo "RESET: Deleted _mediart_scraped_time from {$deleted} posts.\n\n";
		}

		// ——— MAIN CHECK LOOP ———
		global $opt_themes;

		$posts_per_run = isset( $opt_themes['lim_post'] ) ? (int) $opt_themes['lim_post'] : 50;

		$args = array(
			'posts_per_page' => $posts_per_run,
			'post_type'	  => 'post', 
			'fields'		 => 'ids', 
			'order'		  => 'ASC',
			'meta_query'	 => array(
				'relation' => 'OR',
				array(
					'key'	 => '_mediart_scraped_time',
					'value'   => time() - (6 * MINUTE_IN_SECONDS),  // every 6 minutes when testing
					'compare' => '<',
					'type'	=> 'NUMERIC'
				),
				array(
					'key'	 => '_mediart_scraped_time',
					'compare' => 'NOT EXISTS'
				)
			)
		);

		$query = new WP_Query( $args );

		if ( ! $query->have_posts() ) {
			echo "All apps already checked recently. Nothing to do.\n";
		} else {
			echo "Checking " . count( $query->posts ) . " apps now...\n\n";
			foreach ( $query->posts as $pid ) {
				echo "Post ID $pid → ";
				$has_update = is_apk_update_available( $pid, $debug );
				echo $has_update ? " UPDATE FOUND!\n" : " up to date\n";
				usleep(600000); // 0.6 sec delay – be gentle
			}
		}

		echo "\nDONE! All finished at " . date('Y-m-d H:i:s') . "\n";
		echo '</pre>';
		die();
	}
}

// Add meta box with manual check button (or just inject into post submit box)
add_action( 'post_submitbox_misc_actions', 'mediart_add_manual_check_button' );
function mediart_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( 'mediart_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, '_mediart_scraped_time', 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:   'mediart_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
}

add_action( 'wp_ajax_mediart_manual_apk_check', 'mediart_handle_manual_apk_check' );
function mediart_handle_manual_apk_check() 
{
	// Security checks
	check_ajax_referer( 'mediart_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 = is_apk_update_available( $post_id, true ); // 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
		] );
	}
}

add_action( 'admin_bar_menu', 'mediart_admin_bar_update_checker', 999 );
function mediart_admin_bar_update_checker( $wp_admin_bar ) 
{
	if ( ! current_user_can( 'edit_posts' ) ) return;

	// Count how many apps have update_available = 'yes'
	global $wpdb;
	$update_count = (int) $wpdb->get_var(
		"SELECT COUNT(*) FROM {$wpdb->postmeta} 
		 WHERE meta_key = 'update_available' 
		 AND meta_value = 'yes'"
	);

	$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 = 'Available Updates: ' . $badge;

	// Main menu item
	$wp_admin_bar->add_menu( [
		'id'	 => 'mediart-apk-updates',
		'title'  => '<span class="ab-icon dashicons dashicons-update"></span> ' . $title,
		'href'   => '#',
		'meta'   => [ 'title' => 'Apps Update Checker' ]
	] );

	// "Check All Now" button
	$wp_admin_bar->add_menu( [
		'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'   => wp_nonce_url( add_query_arg( 'mediart_force_check', '1' ), 'mediart_force_check_all' ),
		'meta'   => [ 'title' => 'Force check all apps immediately' ]
	] );

	// Show list of apps with pending updates
	if ( $update_count > 0 ) {
		$posts = get_posts( [
			'post_type'	  => 'post', 
			'meta_key'	   => 'update_available',
			'meta_value'	 => 'yes',
			'posts_per_page' => 10,
			'fields'		 => [ 'ID', 'post_title' ]
		] );

		foreach ( $posts as $p ) {
			$new_ver = get_post_meta( $p->ID, 'available_version', true );
			$wp_admin_bar->add_menu( [
				'parent' => 'mediart-apk-updates',
				'id'	 => 'mediart-update-' . $p->ID,
				'title'  => esc_html( $p->post_title ) . " → v{$new_ver}",
				'href'   => get_edit_post_link( $p->ID ),
				'meta'   => [ 'target' => '_blank' ]
			] );
		}
 
		if ( $update_count > 10 ) {
			$wp_admin_bar->add_menu( [
				'parent' => 'mediart-apk-updates',
				'title'  => "… and " . ( $update_count - 10 ) . " more",
				'href'   => admin_url( 'admin.php?page=apps_updates' ),
			] );
		}
	} else {
		$wp_admin_bar->add_menu( [
			'parent' => 'mediart-apk-updates',
			'title'  => 'All apps are up to date',
			'href'   => '#',
		] );
	}
}

// Trigger full check from admin bar link
add_action( 'admin_init', function() 
{
	if ( ! is_admin() || ! current_user_can( 'edit_posts' ) ) return;

	if ( isset( $_GET['mediart_force_check'] ) && $_GET['mediart_force_check'] == 1 ) {
		check_ajax_referer( 'mediart_force_check_all' );

		// Run your existing cron logic immediately
		mediart_run_apk_update_checks(); // ← your function from earlier

		// Redirect back with success message
		wp_redirect( remove_query_arg( 'mediart_force_check' ) );
		exit;
	}
} );

/**
 * Check ALL apps for APK updates
 * Used by: WP-Cron (every 30 min), Admin Bar button, WP-CLI
 */
function mediart_run_apk_update_checks( $debug = false ) 
{

	// Prevent multiple simultaneous runs (global lock)
	if ( get_transient( 'mediart_global_update_check_lock' ) ) {
		if ( $debug ) echo "[SKIP] Another update check is already running.\n";
		return;
	}

	// Lock for max 15 minutes (safety)
	set_transient( 'mediart_global_update_check_lock', true, 15 * MINUTE_IN_SECONDS );

	if ( $debug ) echo "Starting full Apps update check...\n";

	$query = new WP_Query( [
		'post_type'	  => 'post',	// or your CPT: 'apk_app', 'post', etc.
		//'post_status'	=> 'any',
		'posts_per_page' => -1,
		'meta_query'	 => [
			[
				'key'	 => 'wp_GP_ID',
				'value'   => '',
				'compare' => '!=',
			],
		],
		'fields'		 => 'ids',	// Faster: only IDs
		'no_found_rows'  => true,
		'update_post_meta_cache' => false,
		'update_post_term_cache' => false,
	] );

	$query2 = array(
		'posts_per_page' => -1,
		'post_type'	  => 'post',
		'meta_query'	 => array(
			'relation' => 'OR',
			array(
				'key'	 => '_mediart_scraped_time',
				'value'   => time() - 600,	// check every 10*60 minutes (600 sec)
				'compare' => '<',
				'type'	=> 'NUMERIC'
			),
			array(
				'key'	 => '_mediart_scraped_time',
				'compare' => 'NOT EXISTS'
			)
		),
		'fields' => 'ids'
	);
	
	$total_apps = count( $query->posts );
	if ( $total_apps === 0 ) {
		if ( $debug ) echo "No apps found with Google Play ID.\n";
		delete_transient( 'mediart_global_update_check_lock' );
		return;
	}

	if ( $debug ) echo "Found {$total_apps} apps to check...\n";

	$updated_count = 0;
	$checked_count = 0;

	foreach ( $query->posts as $post_id ) {
		$checked_count++;

		// Optional: show progress every 50 apps
		if ( $debug && $checked_count % 50 === 0 ) {
			echo "Checked {$checked_count}/{$total_apps}...\n";
		}

		// Increase max execution time safely
		@set_time_limit( 30 );

		$has_update = is_apk_update_available( $post_id, $debug );

		if ( $has_update ) {
			$title = get_the_title( $post_id );
			$ver   = get_post_meta( $post_id, 'available_version', true );
			if ( $debug ) echo "UPDATE FOUND → #{$post_id} {$title} → v{$ver}\n";
			$updated_count++;
		}
	}

	// Final cleanup
	delete_transient( 'mediart_global_update_check_lock' );

	if ( $debug ) {
		echo "Finished! Checked: {$checked_count}, Updates found: {$updated_count}\n";
	}

	// Optional: trigger a final action
	do_action( 'mediart_full_update_check_complete', $updated_count, $total_apps );
}

add_action( 'admin_notices', 'mediart_show_apk_update_notices' );
function mediart_show_apk_update_notices() 
{
	// Only show to users who can edit posts
	if ( ! current_user_can( 'edit_posts' ) ) {
		return;
	}

	// Optional: limit to specific screens (e.g. only on your CPT list or dashboard)
	$screen = get_current_screen();
	// Uncomment the line below if you want the notice ONLY on your custom post type list
	// if ( $screen->id !== 'edit-your_cpt_name' ) return;

	// Count how many posts have an update pending
	$update_count = mediart_count_posts_with_update();

	if ( $update_count <= 0 ) {
		return; // Nothing to show
	}
 
	$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
	);
	
	//mediart_run_apk_checks();
	
		 
	global $opt_themes;  
	$args = array(
		'posts_per_page' => $opt_themes['lim_post'],
		'post_type'	  => 'post',
		'meta_query'	 => array(
			'relation' => 'OR',
			array(
				'key'	 => '_mediart_scraped_time',
				'value'   => time() - 600,	// check every 10*60 minutes (600 sec)
				'compare' => '<',
				'type'	=> 'NUMERIC'
			),
			array(
				'key'	 => '_mediart_scraped_time',
				'compare' => 'NOT EXISTS'
			)
		),
		'fields' => 'ids',
		//'no_found_rows'  => true,
		//'update_post_meta_cache' => false,
		//'update_post_term_cache' => false,
	);

	$query = new WP_Query( $args );
	foreach ( $query->posts as $pid ) {
		if ( $opt_themes['show_debug'] ) {		
			is_apk_update_available( $pid, true );
		//} else {
		//	is_apk_update_available( $pid, false );
		}
	} 


?>

<div class="notice notice-success is-dismissible">
		<p>
			<?php echo wp_kses_post( $message ); ?>
			<a href="<?php echo admin_url( 'admin.php' ); ?>?page=apps_updates" style="margin-left:10px;">View all → </a>
		</p>
		
		 <p>
			If your site is <b>HEAVY</b> to load, please <b>DISABLE</b> Apps Updates Version Notices Option on Panel Themes.
			<a href="<?php echo admin_url( 'admin.php' ); ?>?page=_options&tab=1">Click Here to Disable</a> 
		</p>
</div>
 
	<?php
}

function mediart_count_posts_with_update() 
{
	global $wpdb;

	// This meta key is set only when an update is detected (see the function above)
	$count2 = $wpdb->get_var(
		"SELECT COUNT(*) FROM {$wpdb->postmeta}
		 WHERE meta_key = 'update_available'
		 AND meta_value > 'yes'"
	);
	
	$count1 = $wpdb->get_var(
		"SELECT COUNT(*) FROM wp_postmeta WHERE (meta_key = 'update_available' AND meta_value = 'yes')"
	);
	
	
	$count = (int) $wpdb->get_var(
		"SELECT COUNT(*) FROM {$wpdb->postmeta} 
		 WHERE meta_key = 'update_available' 
		 AND meta_value = 'yes'"
	);


	//$wpdb->get_results("SELECT * FROM wp_postmeta WHERE (meta_key = 'update_available' AND meta_value = 'yes')");
	
	return (int) $count;
}

add_action( 'pre_get_posts', 'mediart_filter_posts_with_updates' );

function mediart_filter_posts_with_updates( $query ) 
{
	global $pagenow;

	if ( ! is_admin() || $pagenow !== 'edit.php' || ! $query->is_main_query() ) {
		return;
	}

	if ( isset( $_GET['mediart_update_available'] ) && $_GET['mediart_update_available'] == '1' ) {
		$meta_query = array(
			array(
				'key'	 => '_mediart_last_update_found',
				'value'   => 0,
				'compare' => '>',
				'type'	=> 'NUMERIC'
			)
		);

		$query->set( 'meta_query', $meta_query );
	}
}

// Add column
add_filter( 'manage_edit-your_cpt_name_columns', 'mediart_add_update_column' );
add_filter( 'manage_posts_columns', 'mediart_add_update_column' ); // if using regular posts

function mediart_add_update_column( $columns ) 
{
	$columns['apk_update'] = 'Update Available';
	return $columns;
}

// Populate column
add_action( 'manage_posts_custom_column', 'mediart_fill_update_column', 10, 2 );
function mediart_fill_update_column( $column, $post_id ) 
{
	if ( $column === 'apk_update' ) {
		if ( get_post_meta( $post_id, 'update_available', true ) ) {
			echo '<span style="color:green;font-weight:bold;">v.'.get_post_meta( $post_id, 'available_version', true ).'</span>';
		} else {
			echo '—';
		}
	}
}

if(!function_exists('apps_to_updates_menux')){
function apps_to_updates_menux() 
{
	$update_count = mediart_count_posts_with_update();
	add_menu_page(
		__( 'Apps Updates', THEMES_NAMES ), 
		'Apps Updates <span class="update-plugins count-'.$update_count.'"><span class="plugin-count">'.$update_count.'</span></span>',
		'manage_options',
		'apps_updates',
		'apps_updates',
		'dashicons-info-outline',
		//plugins_url( '/img/imdb.png' ),
		999
	);  
	 
}
add_action('admin_menu', 'apps_to_updates_menux');
} 
 
// === 1. AJAX: Update single app ===
add_action('wp_ajax_mediart_update_single_app', 'mediart_ajax_update_single_app');
function mediart_ajax_update_single_app() 
{
	check_ajax_referer('mediart_refresh_updates_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']);
	}

	$available_version 	= get_post_meta( $post_id, 'available_version', true);
	$app_name 			= get_post_meta( $post_id, 'wp_title_GP', true) ?: 'Unknown App';

	// YOUR REAL UPDATE LOGIC HERE
	$result 			= true; // ← Replace with real function later

	if (is_wp_error($result)) {
		wp_send_json_error(['message' => $result->get_error_message()]);
	}

	delete_post_meta( $post_id, 'update_available' );
	update_post_meta( $post_id, 'wp_version_GP', $available_version);
	update_post_meta( $post_id, 'last_updated', current_time('mysql'));

	wp_send_json_success([
		'message'	 => 'Updated successfully!',
		'app_name'	=> $app_name,
		'new_version' => $available_version,
		'reload'	  => true
	]);
}

// === 2. Dashboard with UPDATE SELECTED ===
function apps_updates($post) 
{
	if (!current_user_can('edit_posts')) {
		echo '<p>You do not have permission to view updates.</p>';
		return;
	}

	echo do_shortcode('[css]');
	$nonce = wp_create_nonce('mediart_refresh_updates_nonce');
	?>
<style>
#wpwrap, #wpbody-content, .manual-refresh-updates  {
  background: rgb(23, 28, 31)!important;
}
.play_menu {
	background: #454a4d !important; 
}
.play_menu, div.play_menu a, .manual-refresh-updates, #subdesc { 
	color: #fff!important;
}

div.play_menu path {
  fill: white;
}
</style>
	<?php 	
	$linkforce	= wp_nonce_url( add_query_arg( 'mediart_force_check', '1' ), 'mediart_force_check_all' );
	?>
	<div class="play_menu" style="text-transform:uppercase;margin-bottom:15px;display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:15px;">
		<b><span id="mediart-updates-count">Loading...</span> App(s) Available for Update</b>
		<div style="display:flex;align-items:center;gap:12px;flex-wrap:wrap;">
			<a href="<?php echo $linkforce; ?>">Check All Apps Now</a>
			
			<!--
			<span style="color:#888;font-size:13px;">Auto-refresh: <span id="mediart-timer">30</span>s</span>
			<button type="button" class="manual-refresh-updates button button-secondary">Refresh Now</button>
			-->
			
			<button type="button" id="mediart-update-selected" class="button button-primary" style="background:#9b59b6;display:none;padding:8px 16px;border-radius:6px;font-weight:bold;">
				Update Selected (<span id="selected-count">0</span>)
			</button>
			
			<button type="button" id="mediart-update-all" class="button button-primary" style="background:#c7254e;border:none;padding:8px 16px;border-radius:6px;font-weight:bold;">
				Update All (<span id="update-all-count">0</span>)
			</button>
		</div>
	</div>

	<!-- Progress Bar -->
	<div id="mediart-progress-container" style="display:none;margin:20px 0;background:#111;padding:15px;border-radius:8px;border:1px solid #444;">
		<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:10px;color:#fff;">
			<strong id="progress-title">Updating apps...</strong>
			<span id="mediart-progress-text">0 of 0</span>
		</div>
		<div style="width:100%;height:30px;background:#222;border-radius:8px;overflow:hidden;">
			<div id="mediart-progress-bar" style="width:0%;height:100%;background:linear-gradient(90deg,#8b5cf6,#ec4899);transition:width 0.6s ease;"></div>
		</div>
		<div id="mediart-progress-status" style="margin-top:8px;font-size:13px;color:#aaa;">Starting...</div>
	</div>

	<!-- Select All Checkbox -->
	<div style="margin-bottom:15px;padding:10px 0;border-bottom:1px solid #444;">
		<label style="color:#aaa;font-size:14px;">
			<input type="checkbox" id="select-all-apps"> <strong>Select All</strong>
		</label>
	</div>

	<div id="mediart-updates-container" class="mediart-updates-container">
		<?php mediart_render_updates_list(); ?>
	</div>

	<?php 
	echo do_shortcode('[ft_menu]'); 
	echo do_shortcode('[ft_js]'); 
	?>

	<style>
		.mediart-updates-container { transition:opacity .4s; }
		.mediart-updates-container.loading { opacity:.5; pointer-events:none; }
		.highlight-flash { animation:highlightFlash 1.8s ease-out; }
		.app-updating { border:2px solid #8b5cf6 !important; animation:pulse 1.5s infinite; }
		.app-success { border:2px solid #00ba37 !important; background:rgba(0,186,55,.15)!important; }
		.app-error { border:2px solid #d63638 !important; background:rgba(214,54,56,.15)!important; }
		@keyframes highlightFlash { 0%,100%{background:transparent} 50%{background:rgba(139,92,246,.3)} }
		@keyframes pulse { 0%,100%{box-shadow:0 0 0 0 rgba(139,92,246,.7)} 70%{box-shadow:0 0 0 10px transparent} }
		.up-down-shake { animation:upDown 2s infinite; }
		@keyframes upDown { 0%,100%{transform:translateY(0)} 50%{transform:translateY(-5px)} }
		.rotate-shake { animation:rotateShake 2s infinite; }
		@keyframes rotateShake { 0%,100%{transform:rotate(0)} 10%,30%,50%,70%,90%{transform:rotate(-5deg)} 20%,40%,60%,80%{transform:rotate(5deg)} }
		.app-checkbox { margin-right:10px; transform:scale(1.2); }
	</style>

	<script>
	jQuery(function($) {
		let timer = 30, intervalId = null, isUpdating = false;
		const $container = $('#mediart-updates-container');
		const $countSpan = $('#mediart-updates-count');
		const $timerSpan = $('#mediart-timer');
		const $progress = $('#mediart-progress-container');
		const $bar = $('#mediart-progress-bar');
		const $text = $('#mediart-progress-text');
		const $status = $('#mediart-progress-status');
		const $title = $('#progress-title');
		const $updateAll = $('#mediart-update-all');
		const $updateSelected = $('#mediart-update-selected');
		const $selectedCount = $('#selected-count');
		const $allCount = $('#update-all-count');
		const nonce = '<?php echo esc_js($nonce); ?>';

		function updateCounts() {
			const total = $container.find('.app-container').length;
			const selected = $container.find('.app-checkbox:checked').length;
			$allCount.text(total);
			$selectedCount.text(selected);
			$updateSelected.toggle(selected > 0);
			$updateAll.prop('disabled', total === 0 || isUpdating);
		}

		function startTimer() {
			clearInterval(intervalId);
			timer = 30; $timerSpan.text(timer);
			intervalId = setInterval(() => {
				timer--; $timerSpan.text(timer);
				if (timer <= 0 && !isUpdating) refreshUpdates();
			}, 1000);
		}

		function refreshUpdates() {
			if (isUpdating) return;
			$container.addClass('loading');
			$countSpan.text('Checking...');

			$.post(ajaxurl, { action: 'mediart_refresh_updates', nonce }, function(res) {
				if (res.success) {
					$container.html(res.data.html).removeClass('loading');
					if ($container.find('.app-container').length) {
						$container.addClass('highlight-flash');
						setTimeout(() => $container.removeClass('highlight-flash'), 2000);
					}
				}
				updateCounts();
				startTimer();
			}).fail(() => {
				$container.removeClass('loading');
				startTimer();
			});
		}

		// Select All
		$(document).on('change', '#select-all-apps', function() {
			const checked = this.checked;
			$container.find('.app-checkbox').prop('checked', checked);
			updateCounts();
		});

		$(document).on('change', '.app-checkbox', updateCounts);

		$(document).on('click', '.manual-refresh-updates', () => {
			if (!isUpdating) { 
			timer = 0; 
			//refreshUpdates(); 
			}
		});

		// Single Update
		$(document).on('click', '.mediart-single-update', function(e) {
			e.preventDefault();
			if (isUpdating) return;
			const post_id = $(this).data('post-id');
			updateApps([post_id], 'Updating 1 app...');
		});

		// Update Selected
		$updateSelected.on('click', function() {
			const ids = $container.find('.app-checkbox:checked').map(function() {
				return $(this).closest('.app-container').find('.mediart-single-update').data('post-id');
			}).get();
			if (ids.length) updateApps(ids, `Updating ${ids.length} selected app(s)...`);
		});

		// Update All
		$updateAll.on('click', function() {
			const ids = $container.find('.mediart-single-update').map(function() {
				return $(this).data('post-id');
			}).get();
			if (ids.length) updateApps(ids, 'Updating all apps...');
		});

		// Main update function
		function updateApps(post_ids, title) {
			if (!confirm(`Update ${post_ids.length} app(s)?`)) return;

			isUpdating = true;
			$progress.show();
			$title.text(title);
			$bar.css('width', '0%');
			$text.text('0 of ' + post_ids.length);
			$status.text('Starting...');

			let done = 0, failed = 0;

			function processNext() {
				if (done + failed >= post_ids.length) {
					$status.html(`<span style="color:#00ba37">Finished! ${done} updated, ${failed} failed.</span>`);
					$bar.css('width', '100%');
					setTimeout(() => location.reload(), 2500);
					return;
				}

				const post_id = post_ids[done + failed];
				const $box = $container.find(`[data-post-id="${post_id}"]`).closest('.app-container');
				const name = $box.find('h3').text().trim();

				$box.removeClass('app-success app-error').addClass('app-updating');
				$status.html(`Updating: <strong>${name}</strong>`);

				$.post(ajaxurl, { action: 'mediart_update_single_app', post_id, nonce })
				.done(() => done++)
				.fail(() => failed++)
				.always(() => {
					$box.removeClass('app-updating').addClass(failed > done ? 'app-error' : 'app-success');
					$text.text((done + failed) + ' of ' + post_ids.length);
					$bar.css('width', ((done + failed) / post_ids.length * 100) + '%');
					setTimeout(processNext, 800);
				});
			}
			processNext();
		}

		// Init
		updateCounts();
		//startTimer();
	});
	</script>
	<?php
}

// === 3. Render List with Checkboxes ===
function mediart_render_updates_list() 
{
	$posts = get_posts([
		'post_type'	  => 'post',
		'posts_per_page' => -1,
		'meta_query'	 => [['key' => 'update_available', 'value' => 'yes']],
		'fields'		 => 'ids',
		'cache_results'  => false,
		'no_found_rows'  => true,
	]);

	$count = count($posts);

	echo '<script>jQuery(function($){ 
		$("#mediart-updates-count").closest("b").html("' . $count . ' App' . ($count != 1 ? 's' : '') . ' Available for Update");
	});</script>';

	echo '<section><div class="row">';

	if (!$count) {
		echo '<div class="text-center col-12" style="padding:80px;"><h4 style="color:#00ba37;">All apps are up to date</h4></div>';
		echo '</div></section>';
		return;
	}

	$counter = 0;
	foreach ($posts as $post_id) {
		$current   	= get_post_meta( $post_id, 'wp_version_GP', true);
		$available 	= get_post_meta( $post_id, 'available_version', true);
		if (version_compare($available, $current, '<=')) continue;

		$name 		= get_post_meta( $post_id, 'wp_title_GP', true) ?: 'App';
		$img2  		= get_the_post_thumbnail_url($post_id, 'thumbnail') ?: get_post_meta( $post_id, 'wp_poster_GP', true);
		
		$img  		= get_post_meta( $post_id, 'wp_poster_GP', true) ?: get_the_post_thumbnail_url($post_id, 'thumbnail');
		
		$counter++;
		?>
		<div class="col-12 col-md-6 mb-4">
			<div class="app-container" style="display:flex;align-items:center;gap:12px;padding:12px;background:#111;border:1px solid #333;border-radius:8px;">
				<label style="margin:0;cursor:pointer;">
					<input type="checkbox" class="app-checkbox" style="transform:scale(1.3);margin-right:10px;">
				</label>
				<div style="position:relative;">
					<img src="<?php echo esc_url($img); ?>" width="64" height="64" style="border-radius:8px;">
					<span style="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);background:rgba(0,0,0,0.8);color:white;padding:6px 10px;border-radius:6px;font-weight:bold;border:2px solid white;">
						<?php echo $counter; ?>
					</span>
				</div>
				<div style="flex:1;">
					<h3 style="margin:0;font-size:16px;color:#fff;" class="up-down-shake"><?php echo esc_html($name); ?></h3>
					<div style="font-size:13px;color:#aaa;">
						<span style="color:coral;">v.<?php echo esc_html($current); ?></span> → 
						<span style="color:lime;">v.<?php echo esc_html($available); ?></span>
					</div>
				</div>
				<button type="button" class="mediart-single-update rotate-shake1" data-post-id="<?php echo $post_id; ?>"
						style="background:#d63638;color:white;padding:10px 16px;border-radius:6px;border:none;font-weight:bold;cursor:pointer;">
					Update
				</button>
			</div>
		</div>
		<?php
	}
	echo '</div></section>';
}
 
// 1. Add the dashboard widget
add_action( 'wp_dashboard_setup', 'apk_updates_dashboard_widget' );

function apk_updates_dashboard_widget() 
{
	wp_add_dashboard_widget(
		'apk_updates_widget',
		'Apps Updates Available',
		'apk_updates_widget_display',
		null,	// control callback (optional)
		null,	// args (optional)
		'side',	// ← context: 'side' instead of default 'normal'
		'high'	// ← priority: 'core', 'high', 'low'
	);
}

function apk_updates_widget_display() 
{
	$widget_id = 'apk_updates_widget'; // Must match the ID from wp_add_dashboard_widget
	?>
	<div id="<?php echo $widget_id; ?>-container">
		<div id="<?php echo $widget_id; ?>-content">
			<?php render_apk_updates_table(); // Initial load ?>
		</div>
		 
		
		<div style="text-align:center; padding:10px 0; font-size:12px; color:#666;">
			<span id="<?php echo $widget_id; ?>-status">
				Auto-refresh in <span id="<?php echo $widget_id; ?>-countdown">60</span>s
			</span>
			<span id="<?php echo $widget_id; ?>-spinner" style="display:none; margin-left:8px;">
				Loading...
			</span>
		</div>
	</div>

	<script type="text/javascript">
		(function() {
			const widgetId = '<?php echo $widget_id; ?>';
			const container = document.getElementById(widgetId + '-container');
			const contentDiv = document.getElementById(widgetId + '-content');
			const statusText = document.getElementById(widgetId + '-status');
			const spinner = document.getElementById(widgetId + '-spinner');
			const countdownEl = document.getElementById(widgetId + '-countdown');

			let countdown = 60;

			function refreshWidget() {
				spinner.style.display = 'inline';
				statusText.style.display = 'none';

				fetch(ajaxurl, {
					method: 'POST',
					credentials: 'same-origin',
					headers: {
						'Content-Type': 'application/x-www-form-urlencoded',
					},
					body: 'action=apk_updates_widget_refresh&_wpnonce=<?php echo wp_create_nonce('apk_widget_refresh'); ?>'
				})
				.then(response => response.text())
				.then(html => {
					contentDiv.innerHTML = html;
					spinner.style.display = 'none';
					statusText.style.display = 'block';
					countdown = 60;
					countdownEl.textContent = countdown;
					startCountdown();
				})
				.catch(err => {
					contentDiv.innerHTML = '<p style="color:red;">Refresh failed. Retrying...</p>';
					spinner.style.display = 'none';
					setTimeout(refreshWidget, 10000); // retry in 10s
				});
			}

			function startCountdown() {
				const interval = setInterval(() => {
					countdown--;
					countdownEl.textContent = countdown;
					if (countdown <= 0) {
						clearInterval(interval);
						refreshWidget();
					}
				}, 1000);
			}

			// Start countdown on load
			startCountdown();

			// Optional: manual refresh button
			const refreshBtn = document.createElement('a');
			refreshBtn.href = '#';
			refreshBtn.textContent = 'Refresh now';
			refreshBtn.style = 'margin-left:15px; font-size:11px; color:#0073aa;';
			refreshBtn.onclick = (e) => {
				e.preventDefault();
				countdown = 0;
				refreshWidget();
			};
			statusText.appendChild(refreshBtn);
		})();
	</script>
	<?php
}

// Render the actual table (used both on load and AJAX)
function render_apk_updates_table() 
{
	$query = new WP_Query( array(
		'post_type'	=> 'post',
		'posts_per_page' => 100,
		'meta_query'	=> array(
			array( 
				'key' => 'update_available', 
				'value' => 'yes' 
			),
		), 
		
	) );
	
	$linkforce	= wp_nonce_url( add_query_arg( 'mediart_force_check', '1' ), 'mediart_force_check_all' );

	if ( ! $query->have_posts() ) {
		echo '<p><strong>All apps are up to date!</strong>  <a style="float: right;" href="' . admin_url('admin.php?page=apps_updates') . '">Check All Apps Now →</a></p>';
		wp_reset_postdata();
		return;
	}
	echo '<p><strong>' . mediart_count_posts_with_update() . ' app(s) have updates!</strong>  <a style="float: right;" href="' . admin_url('admin.php?page=apps_updates') . '">View all →</a></p>';
	echo '<div style="max-height:250px; overflow-y:auto; border:1px solid #ddd; border-radius:6px;">';
	echo '<table class="widefat striped" style="margin:0; font-size:12px;">';
	echo '<thead style="position:sticky; top:0; background:#f1f1f1; z-index:10;">
			<tr>
				<th style="padding:8px 10px;">App</th>
				<th style="padding:8px 10px; width:100px;">New Version</th>
				<th style="padding:8px 10px; width:70px;">Actions</th>
			</tr>
		  </thead><tbody>';

	while ( $query->have_posts() ) {
		$query->the_post();
		$post_id = get_the_ID();
		$title   = get_the_title() ?: '(No title)';
		$edit	= get_edit_post_link( $post_id );
		$view	= get_permalink( $post_id );
		$ver	 = get_post_meta( $post_id, 'available_version', true );
		$cur	 = get_post_meta( $post_id, 'wp_version_GP', true );

		echo '<tr>';
		echo '<td style="padding:8px 10px;"><a href="' . esc_url($edit) . '"><strong>' . esc_html($title) . '</strong></a>';
		if ( $cur && $cur !== $ver ) echo '<br><small style="color:#666;">Version: v.' . esc_html($cur) . '</small>';
		echo '</td>';
		echo '<td style="padding:8px 10px; color:green; font-weight:bold;">' . esc_html($ver ?: '—') . '</td>';
		echo '<td style="padding:8px 10px; font-size:11px;">
				<a href="' . esc_url($edit) . '" target="_blank">Edit</a> |
				<a href="' . esc_url($view) . '" target="_blank">View</a>
			  </td>';
		echo '</tr>';
	}
	echo '</tbody></table></div>';
	
	wp_reset_postdata();
	
	//if ( $query->found_posts > 30 ) {
	//	echo '<div style="text-align:center; padding:10px 0; font-size:12px; color:#666;"><a href="' . admin_url('admin.php?page=apps_updates') . '">View all →</a></div>';
	//}
	
	
}

// AJAX refresh endpoint
add_action( 'wp_ajax_apk_updates_widget_refresh', 'apk_updates_widget_ajax_refresh' );
function apk_updates_widget_ajax_refresh() 
{
	check_ajax_referer( 'apk_widget_refresh' );
	render_apk_updates_table(); // This outputs the table only
	wp_die();
}
