<?php  
/**
 * APK Update Checker – Fixed & Optimized Version
 */

if ( ! function_exists('str_get_html') ) 
{
	require_once get_template_directory().'/libs/addons/inc/dom.php';
}

/**
 * Main function: Check if a newer version is available on Google Play
 */
function is_apk_update_available( $post_id, $debug=false ) 
{
	global $opt_themes;
	$post_id = (int) $post_id;	
 
	if ( ! $post_id || ! get_post( $post_id ) ) {
		if ( $debug ) echo "<br/>[ERROR] Invalid post ID: $post_id";
		return false;
	}

	// 2. CRON OVERLAP PROTECTION – This is the key!
	$lock_key = "apk_update_lock_{$post_id}";
	if ( get_transient( $lock_key ) ) {
		if ( $debug ) echo "<br/>[SKIP] Post $post_id is already being processed (locked).";
		return false; // Another process is already checking this app
	}

	// Acquire lock for 8 minutes (adjust as needed, should be longer than max execution time)
	set_transient( $lock_key, time(), 8 * MINUTE_IN_SECONDS );

	// Optional: emergency cleanup of very old stuck locks (>30 min)
	register_shutdown_function( function() use ( $lock_key ) {
		delete_transient( $lock_key );
	} );

	$appid 			= get_post_meta( $post_id, 'wp_GP_ID', true );
	$titles			= 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";
		delete_transient( $lock_key );
		update_post_meta( $post_id, '_available_updates_scraped_time', time() );
		return false;
	}

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

	if ( $debug ) {
		echo "<br/>Checking <strong>Post ID $post_id</strong> → <strong>$titles</strong>";
	}
	
	$scraper		= new Go_Curl(); 
	$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 server</span>";
		delete_transient( $lock_key );
		return false;
	}
	
		
	$language		= $opt_themes['apk_language'];   
	$gplay			= new \Nelexa\GPlay\GPlayApps( $defaultLocale = $language, $defaultCountry = '' ); 
	$appinfo		= $gplay->getAppInfo( $appid );

	$n_version_raw	= $scraper->match( '/<div class="c_version">(.*?)<\/div>/ms', $g_data, 1 );
	$n_whatsnew1	= $scraper->match( '/<div class="whatsnew">(.*?)<\/div>/ms', $g_data, 1 );
	$n_whatsnew		= $appinfo->getRecentChanges();
	
	$n_version		= trim( $n_version_raw ); 
	$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_transient( $lock_key );
		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> ";
	//}
	
    // Always clean up old update flags first
    delete_post_meta( $post_id, 'available_updated' );
    delete_post_meta( $post_id, 'available_version' );
    delete_post_meta( $post_id, 'available_whatsnew' );
    delete_post_meta( $post_id, 'available_update_version' ); // legacy?
    delete_post_meta( $post_id, '_available_updates_last_update_found' );

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

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

	// UPDATE FOUND! 
	update_post_meta( $post_id, 'available_updated', 'yes' );
	update_post_meta( $post_id, 'available_version', $n_version );
	update_post_meta( $post_id, 'available_whatsnew', $n_whatsnew );
	update_post_meta( $post_id, '_available_updates_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'				=> $titles,
		'current_version'  	=> $c_version,
		'new_version'	  	=> $n_version,
		'new_whatsnew'	  	=> $n_whatsnew,
	];

	// Remove lock ONLY after everything succeeded
	delete_transient( $lock_key );

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

	} 
	
	/* else {
		delete_transient( $lock_key );
		delete_post_meta( $post_id, '_available_updates_last_update_found' );
		delete_post_meta( $post_id, 'available_update_version' );
		delete_post_meta( $post_id, 'available_updated' );
		delete_post_meta( $post_id, 'available_version' );
		delete_post_meta( $post_id, 'available_whatsnew' );
		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, 'available_update_version' );
	//delete_post_meta( $post_id, 'available_updated' );
	//delete_post_meta( $post_id, 'available_version' );	
	//delete_post_meta( $post_id, 'available_whatsnew' );	
	
	// optional: delete_post_meta( $post_id, '_available_updates_last_update_found' );
	
	if ( $debug ) echo " <span style='color:gray;'> → Up to date</span>";
	
	delete_transient( $lock_key );
	
	return false; 
}

/**
 * Clear update flags when admin manually saves post
 */
add_action( 'save_post', 'available_updates_clear_update_flag_on_manual_save', 10, 3 );
function available_updates_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, 'available_update_version' );
		delete_post_meta( $post_id, 'available_updated' );
		delete_post_meta( $post_id, 'available_version' );
		delete_post_meta( $post_id, 'available_whatsnew' );
		delete_post_meta( $post_id, '_available_updates_last_update_found' ); // optional

		// Optional: add a log that admin cleared it
		add_post_meta( $post_id, '_available_updates_update_cleared_by_admin', current_time('mysql'), true );
	}
}
 
// === WP-CRON SCHEDULER FOR APK UPDATES ===

// 1. Register custom cron interval (optional – for more flexible scheduling)
add_filter( 'cron_schedules', 'availabled_updates_add_cron_interval' );
function availabled_updates_add_cron_interval( $schedules ) 
{
    $schedules['every_6_hours'] = [
        'interval' => 6 * HOUR_IN_SECONDS,
        'display'  => __( 'Every 6 Hours' ),
    ];
    $schedules['every_12_hours'] = [
        'interval' => 12 * HOUR_IN_SECONDS,
        'display'  => __( 'Every 12 Hours' ),
    ];
    return $schedules;
}

// 2. Schedule the event on activation (or when plugin/theme loads first time)
if ( ! wp_next_scheduled( 'availabled_updates_check_all_apps_cron' ) ) 
{
    wp_schedule_event( time(), 'every_6_hours', 'availabled_updates_check_all_apps_cron' );
}

// 3. Hook the cron event to our main function
add_action( 'availabled_updates_check_all_apps_cron', 'availabled_updates_run_batch_check' );

// 4. Main function: Process apps in safe batches availabled_updates_run_batch_check
function availabled_updates_run_batch_check() 
{
	global $opt_themes;
    // Safety: Prevent overlapping runs
    if ( get_transient( 'available_updates_global_cron_lock' ) ) {
        return; // Already running
    }
    set_transient( 'available_updates_global_cron_lock', true, 30 * MINUTE_IN_SECONDS );

    // Settings – adjust as needed
    $batch_size     = isset( $opt_themes['lim_post'] ) ? intval( $opt_themes['lim_post'] ) : 20; // Number of apps to check per batch
    $max_execution  = 120;       // Max seconds to run (prevent timeout)
    $start_time     = time();

    // Get all published posts with a Google Play ID
    $args = [
        'post_type'      => 'post',
        'post_status'    => 'publish',
        'posts_per_page' => $batch_size,
        'meta_query'     => [
            [
                'key'     => 'wp_GP_ID',
                'value'   => '',
                'compare' => '!=',
            ],
        ],
        'fields'         => 'ids',
        'orderby'        => 'meta_value', // Optional: prioritize recently updated or random
        'meta_key'       => '_available_updates_scraped_time',
        'order'          => 'ASC', // Check oldest scraped first
    ];

    $query = new WP_Query( $args );

    if ( ! $query->have_posts() ) {
        delete_transient( 'available_updates_global_cron_lock' );
        return;
    }

    $checked_count = 0;
    foreach ( $query->posts as $post_id ) {
        // Stop if we're taking too long
        if ( ( time() - $start_time ) > $max_execution ) {
            break;
        }

        // Run the update check (your cleaned function)
        is_apk_update_available( $post_id, false ); // Set $debug = false in production

        $checked_count++;
    }

    // Log for debugging (optional – remove in production if not needed)
    error_log( "[APK Updates Cron] Checked $checked_count apps in this batch." );

    // Release global lock
    delete_transient( 'available_updates_global_cron_lock' );

    // If we processed full batch, there might be more → reschedule immediate next batch
    if ( $checked_count === $batch_size ) {
        wp_schedule_single_event( time() + 60, 'availabled_updates_check_all_apps_cron' ); // Run again in 1 minute
    }
}

// 5. Optional: Add manual "Check All Now" button handler (from your admin page link)
add_action( 'admin_init', 'availabled_updates_handle_force_check' );
function availabled_updates_handle_force_check() 
{
    if ( ! current_user_can( 'manage_options' ) ) {
        return;
    }

    if ( isset( $_GET['available_updates_force_check'] ) && wp_verify_nonce( $_REQUEST['_wpnonce'], 'available_updates_force_check_all' ) ) {
        // Clear any lock and run one full batch immediately
        delete_transient( 'available_updates_global_cron_lock' );

        // Trigger immediate check
        wp_schedule_single_event( time(), 'availabled_updates_check_all_apps_cron' );

        // Optional: Show admin notice
        add_action( 'admin_notices', function() {
            echo '<div class="notice notice-success is-dismissible"><p>Manual check for app updates started! It will run in the background.</p></div>';
        } );

        // Redirect back cleanly
        wp_redirect( remove_query_arg( [ 'available_updates_force_check', '_wpnonce' ] ) );
        exit;
    }
}

// 6. Optional: Clear cron on deactivation (if this is a theme)
register_deactivation_hook( __FILE__, 'availabled_updates_deactivate_cron' );
add_action( 'switch_theme', 'availabled_updates_deactivate_cron', 10, 2 );
function availabled_updates_deactivate_cron() 
{
    wp_clear_scheduled_hook( 'availabled_updates_check_all_apps_cron' );
    delete_transient( 'available_updates_global_cron_lock' );
}
 
// Clear scheduled cron events when the theme is switched/deactivated
add_action( 'switch_theme', 'available_updates_clear_cron_on_theme_switch', 10, 2 );
function available_updates_clear_cron_on_theme_switch( $new_name, $new_theme ) 
{
    // Optional: Only run if switching AWAY from your theme
    // Replace 'your-theme-folder-name' with your actual theme folder (e.g. 'myappstore')
    $current_theme = wp_get_theme()->get( 'Template' ); // or get_stylesheet()

    // If the old theme was yours, clean up
    if ( $current_theme === TEXT_DOMAIN ) {
        wp_clear_scheduled_hook( 'available_updates_check_all_apps_cron' );
        delete_transient( 'available_updates_global_cron_lock' );

        // Optional: Clear any per-app locks that might be stuck
        global $wpdb;
        $wpdb->query(
            $wpdb->prepare(
                "DELETE FROM $wpdb->options 
                 WHERE option_name LIKE %s 
                 AND option_name NOT LIKE %s",
                '_transient_apk_update_lock_%',
                '_transient_timeout_apk_update_lock_%'
            )
        );
    }
}

add_action( 'after_switch_theme', 'available_updates_reschedule_cron_on_activation' );
function available_updates_reschedule_cron_on_activation() 
{
    if ( ! wp_next_scheduled( 'available_updates_check_all_apps_cron' ) ) {
        wp_schedule_event( time(), 'every_6_hours', 'available_updates_check_all_apps_cron' );
    }
}

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();
});
 


/**
 * Admin Bar: Apps Update Checker + Force Check
 */

/* 1. Add item to Admin Bar */
add_action( 'admin_bar_menu', 'available_updates_admin_bar_update_checker', 999 );

function available_updates_admin_bar_update_checker( $wp_admin_bar ) {
    if ( ! current_user_can( 'edit_posts' ) ) {
        return;
    }

    // Efficient count of posts with available update
    global $wpdb;

    $update_count = (int) $wpdb->get_var( "
        SELECT COUNT(DISTINCT p.ID)
        FROM {$wpdb->posts} p
        INNER JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id
        INNER JOIN {$wpdb->postmeta} pm2 ON p.ID = pm2.post_id
        WHERE p.post_type = 'post'
          AND p.post_status = 'publish'
          AND pm.meta_key = 'wp_GP_ID'
          AND pm.meta_value != ''
          AND pm2.meta_key = 'available_updated'
          AND pm2.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 = '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=apps_updates' ),
        'meta'  => array( 'title' => 'View Apps Updates Page' ),
    ) );

    // "Check All Now" button
    $force_url = wp_nonce_url(
        add_query_arg( 'available_updates_force_check', '1' ),
        'available_updates_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
    if ( $update_count > 0 ) {
        $posts = get_posts( array(
            'post_type'      => 'post',
            'post_status'    => 'publish',
            'meta_key'       => 'available_updated',
            'meta_value'     => 'yes',
            'posts_per_page' => 10,
            'fields'         => 'objects', // Need title + ID
        ) );

        foreach ( $posts as $post ) {
            $new_ver = get_post_meta( $post->ID, 'available_version', true );
            $version_text = $new_ver ? " → v{$new_ver}" : '';

            $wp_admin_bar->add_menu( array(
                'parent' => 'mediart-apk-updates',
                'id'     => 'mediart-update-' . $post->ID,
                'title'  => esc_html( $post->post_title ) . $version_text,
                'href'   => get_edit_post_link( $post->ID ),
                'meta'   => array( 'target' => '_blank' ),
            ) );
        }

        if ( $update_count > 10 ) {
            $wp_admin_bar->add_menu( array(
                'parent' => 'mediart-apk-updates',
                'title'  => '… and ' . ( $update_count - 10 ) . ' more',
                'href'   => admin_url( 'admin.php?page=apps_updates' ),
            ) );
        }
    } else {
        $wp_admin_bar->add_menu( array(
            'parent' => 'mediart-apk-updates',
            'title'  => 'All apps are up to date ✓',
            'href'   => admin_url( 'admin.php?page=apps_updates' ),
        ) );
    }
}

/* 2. Handle "Check All Now" click */
add_action( 'admin_init', 'available_updates_handle_force_check' );

function available_updates_handle_force_check() {
    if ( ! is_admin() || ! current_user_can( 'edit_posts' ) ) {
        return;
    }

    if ( ! isset( $_GET['available_updates_force_check'] ) || $_GET['available_updates_force_check'] !== '1' ) {
        return;
    }

    check_ajax_referer( 'available_updates_force_check_all' );

    // Run the full update check
    available_updates_run_apk_update_checks();

    // Optional: add admin notice on redirect
    add_option( 'available_updates_force_check_notice', 'Full update check completed!' );

    // Redirect to clean URL (remove query arg)
    wp_redirect( remove_query_arg( 'available_updates_force_check' ) );
    exit;
}

/* Optional: Show success notice after force check */
add_action( 'admin_notices', function() {
    if ( $msg = get_option( 'available_updates_force_check_notice' ) ) {
        echo '<div class="notice notice-success is-dismissible"><p>' . esc_html( $msg ) . '</p></div>';
        delete_option( 'available_updates_force_check_notice' );
    }
} );

/* 3. Full update checker function */
function available_updates_run_apk_update_checks( $debug = false ) {
    // Prevent overlapping runs
    if ( get_transient( 'available_updates_global_update_check_lock' ) ) {
        if ( $debug ) {
            echo "[SKIP] Another update check is already running.\n";
        }
        return;
    }

    set_transient( 'available_updates_global_update_check_lock', true, 15 * MINUTE_IN_SECONDS );

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

    $query = new WP_Query( array(
        'post_type'      => 'post',
        'post_status'    => 'publish',
        'posts_per_page' => -1,
        'meta_query'     => array(
            array(
                'key'     => 'wp_GP_ID',
                'value'   => '',
                'compare' => '!=',
            ),
        ),
        'fields'         => 'ids',
        'no_found_rows'  => true,
    ) );

    $total_apps = count( $query->posts );

    if ( $total_apps === 0 ) {
        if ( $debug ) {
            echo "No apps found with Google Play ID.\n";
        }
        delete_transient( 'available_updates_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++;
        @set_time_limit( 30 ); // Prevent timeout on large sites

        if ( $debug && $checked_count % 50 === 0 ) {
            echo "Checked {$checked_count}/{$total_apps}...\n";
        }

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

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

    delete_transient( 'available_updates_global_update_check_lock' );

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

    do_action( 'available_updates_full_update_check_complete', $updated_count, $total_apps );
}

// ============= AUTO-REFRESH ADMIN BAR UPDATE BADGE (Every 45 seconds) =============
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');

                // Update badge
                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>');
                    } else {
                        badge.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();
                }

                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) ============= apk_get_update_count
add_action('wp_ajax_apk_get_update_count', 'apk_ajax_get_update_count');
function apk_ajax_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'"
    );

	$count = (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'
		   )"
	);
	
    wp_send_json_success(['count' => $count]);
}


add_action( 'admin_notices', 'available_updates_show_apk_update_notices' );

function available_updates_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'] !== 'apps_updates' ) {
        return;
    }

    // Optional: Further restrict to exact screen if needed
    // $screen = get_current_screen();
    // if ( $screen->id !== 'toplevel_page_apps_updates' ) return; // Adjust if it's a top-level page

    // 3. Count posts with pending updates
    $update_count = available_updates_count_posts_with_update();

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

    // 4. Trigger background update checks for outdated posts
    global $opt_themes;

    $args = array(
        'posts_per_page' => isset( $opt_themes['lim_post'] ) ? (int) $opt_themes['lim_post'] : 20,
        'post_type'      => 'post',
        'post_status'    => 'publish',
        'meta_query'     => array(
            'relation' => 'OR',
            array(
                'key'     => '_available_updates_scraped_time',
                'value'   => time() - 600, // Older than 10 minutes
                'compare' => '<',
                'type'    => 'NUMERIC',
            ),
            array(
                'key'     => '_available_updates_scraped_time',
                'compare' => 'NOT EXISTS',
            ),
        ),
        'fields'         => 'ids', // Only get post IDs for performance
    );

    $query = new WP_Query( $args );

    if ( $query->have_posts() ) {
        foreach ( $query->posts as $post_id ) {
            if ( ! empty( $opt_themes['show_debug'] ) ) {
                is_apk_update_available( $post_id, true ); // Debug mode
            } else {
                is_apk_update_available( $post_id, false );
            }
        }
    }

    // 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'
        ),
        $update_count
    );

    // 6. Output the notice
    ?>
    <!--<div class="notice notice-success is-dismissible">
        <p>
            <?php echo wp_kses_post( $message ); ?>
        </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
}
 
 
add_action( 'admin_notices', 'available_updates_show_apk_update_notices_dashboard' );

function available_updates_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, 'apps_updates' ) !== false ) {
        return;
    }
	
    // 4. Count posts with pending updates
    $update_count = available_updates_count_posts_with_update();

    // 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=apps_updates' ) ); ?>" 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
}


function available_updates_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 = 'available_updated'
		 AND meta_value > 'yes'"
	);
	
	$count1 = $wpdb->get_var(
		"SELECT COUNT(*) FROM wp_postmeta WHERE (meta_key = 'available_updated' AND meta_value = 'yes')"
	);
	
	
	$count3 = (int) $wpdb->get_var(
		"SELECT COUNT(*) FROM {$wpdb->postmeta} 
		 WHERE meta_key = 'available_updated' 
		 AND meta_value = 'yes'"
	);
	*/
	
	$count = (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'
		   )"
	);
	
	//$wpdb->get_results("SELECT * FROM wp_postmeta WHERE (meta_key = 'available_updated' AND meta_value = 'yes')");
	
	return (int) $count;
}

add_action( 'pre_get_posts', 'available_updates_filter_posts_with_updates' );

function available_updates_filter_posts_with_updates( $query ) 
{
	global $pagenow;

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

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

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


// === Count apps with available updates (for menu badge) ===
if ( ! function_exists( 'available_updates_count_posts_with_update' ) ) {
    function available_updates_count_posts_with_update() {
        $posts = get_posts( [
            'post_type'      => 'post',
            'post_status'    => 'publish',
            'posts_per_page' => -1,
            'meta_query'     => [
                [
                    'key'   => 'available_updated',
                    'value' => 'yes',
                ],
            ],
            'fields'         => 'ids',
            'cache_results'  => false,
            'no_found_rows'  => true,
        ] );

        $count = 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 ( $available && $current && version_compare( $available, $current, '>' ) ) {
                $count++;
            }
        }

        return $count;
    }
}

// === Add Admin Menu ===
if ( ! function_exists( 'apps_to_updates_menux' ) ) {
    function apps_to_updates_menux() {
        $update_count = available_updates_count_posts_with_update();

        add_menu_page(
            __( 'Apps Updates', 'textdomain' ),
            'Apps Updates <span class="update-plugins count-' . $update_count . '"><span class="plugin-count">' . $update_count . '</span></span>',
            'manage_options',
            'apps_updates',
            'apps_updates',
            'dashicons-update', // Better icon for updates
            999
        );
    }
    add_action( 'admin_menu', 'apps_to_updates_menux' );
}

// === AJAX: Update single app ===
add_action( 'wp_ajax_available_updates_update_single_app', 'available_updates_ajax_update_single_app' );
function available_updates_ajax_update_single_app() {
    check_ajax_referer( 'available_updates_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 );
    $available_whatsnew 	= get_post_meta( $post_id, 'available_whatsnew', true );
    $titles            		= get_post_meta( $post_id, 'wp_title_GP', true ) ?: get_the_title( $post_id ) ?: 'Unknown App';

    // === YOUR REAL UPDATE LOGIC HERE ===
    // Replace the line below with your actual update process (e.g. download new APK, update meta, attachments, etc.)
    $result = true; // Placeholder – change to your real function/call

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

    // Mark as updated
    delete_post_meta( $post_id, 'available_updated' );
    delete_post_meta( $post_id, 'available_whatsnew' );
    update_post_meta( $post_id, 'wp_version_GP', $available_version );
    update_post_meta( $post_id, 'wp_whatnews_GP', $available_whatsnew );
    update_post_meta( $post_id, 'last_updated', current_time( 'mysql' ) );

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

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

    // Assuming you have shortcodes [css], [ft_menu], [ft_js] – keep them if needed
    echo do_shortcode( '[css]' );

    $nonce      = wp_create_nonce( 'available_updates_refresh_updates_nonce' );
    $linkforce  = wp_nonce_url( add_query_arg( 'available_updates_force_check', '1' ), 'available_updates_force_check_all' );
	
	
    ?>
	
    <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>

    <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 esc_url( $linkforce ); ?>">Check All Apps Now</a>
            <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 available_updates_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)}}
        .app-checkbox {margin-right:10px;transform:scale(1.2);}
    </style>

    <script>
    jQuery(function($) {
        let isUpdating = false;
        const $container       = $('#mediart-updates-container');
        const $countSpan       = $('#mediart-updates-count');
        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);
        }

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

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

        // 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)? This action cannot be undone.`)) 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:  'available_updates_update_single_app',
                    post_id: post_id,
                    nonce:   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();
    });
    </script>
	
    <?php
}

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

    // Filter only those with actual newer version
    $valid_posts = [];
    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 ( $available && $current && version_compare( $available, $current, '>' ) ) {
            $valid_posts[] = $post_id;
        }
    }

    $count = count( $valid_posts );

    // Update count in header instantly
    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 ( $valid_posts as $post_id ) {
        $counter++;
        $current   		= get_post_meta( $post_id, 'wp_version_GP', true );
        $available 		= get_post_meta( $post_id, 'available_version', true );
        $titles    		= get_post_meta( $post_id, 'wp_title_GP', true ) ?: get_the_title( $post_id ) ?: 'Unknown App';
        $img       		= get_the_post_thumbnail_url( $post_id, 'thumbnail' );
        if ( ! $img ) {
            $img 		= get_post_meta( $post_id, 'wp_poster_GP', true );
        }
		$last_checked  	= get_post_meta( $post_id, '_available_updates_scraped_time', true);
		$last_checked  	= $last_checked ? human_time_diff($last_checked) . ' ago' : 'Never';
	
        ?>
        <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">
                </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( $titles ); ?></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><br>
							last checked : <span style="color:coral;"><?php echo esc_html( $last_checked ); ?></span>
                    </div>
                </div>
                <a href="#" class="mediart-single-update" data-post-id="<?php echo esc_attr( $post_id ); ?>"
                   style="background:#9b59b6;color:white;padding:10px 16px;border-radius:6px;border:none;font-weight:bold;cursor:pointer;text-decoration:none;">
                    Update
                </a>
                <a href="<?php echo get_edit_post_link( $post_id ); ?>" target="_blank"
                   style="background:#34495e;color:white;padding:10px 16px;border-radius:6px;border:none;font-weight:bold;cursor:pointer;text-decoration:none;margin-left:8px;">
                    Edit
                </a>
            </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',
		'post_status'		=> 'publish',
		'posts_per_page' 	=> 100,
		'meta_query'		=> array(
			array( 
				'key' 		=> 'available_updated', 
				'value' 	=> 'yes' 
			),
		), 
		
	) );
	
	$linkforce	= wp_nonce_url( add_query_arg( 'available_updates_force_check', '1' ), 'available_updates_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>' . available_updates_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() ?: get_post_meta( $post_id, 'wp_title_GP', true ); 
		$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();
}



// 1. Add the column header
add_filter('manage_post_posts_columns', 'available_updates_add_update_status_column', 999);
function available_updates_add_update_status_column($columns) {
    // Insert after title, before date (or replace any column you want)
    $new_columns = [];
    foreach ($columns as $key => $value) {
        $new_columns[$key] = $value;
        if ($key === 'version') {
            $new_columns['apk_update'] = 'Update Available';
        }
    }
    return $new_columns;
}
 
 
// Add column
//add_filter( 'manage_edit-your_cpt_name_columns', 'available_updates_add_update_column' );
//add_filter( 'manage_posts_columns', 'available_updates_add_update_column' ); // if using regular posts

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

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


// ============= INLINE FORCE CHECK BUTTON on edit post (No external files) =============
add_action('add_meta_boxes', 'available_updates_add_force_check_metabox_inline');
function available_updates_add_force_check_metabox_inline() 
{
	add_meta_box(
		'available_updates_force_check',
		'APK Update Checker',
		'available_updates_render_force_check_metabox_inline',
		'post',		   // Change to your post type if needed
		'side',
		'high'
	);
}

//add_action( 'post_submitbox_misc_actions', 'available_updates_render_force_check_metabox_inline' );
function available_updates_render_force_check_metabox_inline($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, '_available_updates_scraped_time', 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('available_updates_force_check_nonce', 'available_updates_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: 'available_updates_force_check',
				post_id: <?php echo $post->ID; ?>,
				nonce: '<?php echo wp_create_nonce('available_updates_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)
add_action('wp_ajax_available_updates_force_check', 'availables_updates_handle_force_check');
function availables_updates_handle_force_check() 
{
	check_ajax_referer('available_updates_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 	= is_apk_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, '_available_updates_scraped_time', true)) . ' ago',
		'debug'			 		=> $debug ? strip_tags($debug) : null
	]);
}

// Add meta box with manual check button (or just inject into post submit box)
//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, '_available_updates_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: '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
}

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 		= is_apk_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
		] );
	}
}
  