<?php 
  
 

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


function is_apk_update_available( $post_id, $debug=true ) {
    $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> → <code>$title_GP</code> ";
    }
	
	$scraper		= new Go_Curl();
	//$appid		= get_post_meta( get_the_ID(), 'wp_GP_ID', true ); 
	$urlx 			= 'https://a-a.my.id/gps.php?pkgid='.$appid;  
			
	$g_data			= $scraper->scrape_sitex($urlx); 
	$n_versionx		= $scraper->match('/<div class="c_version">(.*?)<\/div>/ms', $g_data, 1);
				 
	$n_version 		= $n_versionx;           // e.g. "2.24.26.78"
	//$c_version   	= get_post_meta( $post_id, 'wp_GP_version', true );
	$c_version   	= get_post_meta( $post_id, 'wp_version_GP', true );

	// Clean versions (remove build metadata like +hotfix)
	//$current_version = preg_replace('/\+.*$/', '', trim( $current_version ) );
	//$saved_version   = preg_replace('/\+.*$/', '', trim( $saved_version ) );

	if ( $debug ) {
		echo " <b>v.$c_version</b> → New versi: <b>v.$n_version</b>";
	}

	// 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 " → <span style='color:green;font-weight:bold;'>UPDATE AVAILABLE! ($n_version)</span>";
	}

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

	delete_post_meta( $post_id, '_mediart_scraping_progress' );
	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 );
	}

	if ( $debug ) echo " → <span style='color:gray;'>Up to date</span>";

    return false;
}

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
    }

    // Build the admin URL to see all apps with updates
    //$updates_url = add_query_arg( array(
    //    'mediart_update_available' => '1',
    //    'post_type'                => 'your_cpt_name', // change to your CPT or remove if using posts
   // ), admin_url( 'edit.php' ) );

    $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
    );


// Test one post
//is_apk_update_available( 123, true );

// Or loop through posts that need checking
$args = array(
    'posts_per_page' => 10,
    'post_type'      => 'post',
    'meta_query'     => array(
        'relation' => 'OR',
        array(
            'key'     => '_mediart_scraped_time',
            'value'   => time() - 30,
            'compare' => '<',
            'type'    => 'NUMERIC'
        ),
        array(
            'key'     => '_mediart_scraped_time',
            'compare' => 'NOT EXISTS'
        )
    ),
    'fields' => 'ids'
);

$query = new WP_Query( $args );
foreach ( $query->posts as $pid ) {
    is_apk_update_available( $pid, true );
}


    ?>
    <div class="notice notice-success is-dismissible">
        <p>
            <?php echo wp_kses_post( $message ); ?>
            <a href="<?php echo esc_url( $updates_url ); ?>" style="margin-left:10px;">
                View all →
            </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)
    $count = $wpdb->get_var(
        "SELECT COUNT(*) FROM {$wpdb->postmeta}
         WHERE meta_key = '_mediart_last_update_found'
         AND meta_value > 0"
    );

    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'] = 'APK Update';
    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, 'available_version', true ) ) {
            echo '<span style="color:green;font-weight:bold;">New version v.'.get_post_meta( $post_id, 'available_version', true ).'</span>';
        } else {
            echo '—';
        }
    }
}


function wp_apps_to_updates2( $post ) {  
echo do_shortcode( '[css]' );	
global $opt_themes, $wpdb, $post, $wp_query; 
	@ini_set('user_agent', 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)');   
	@ini_set('user_agent', 'My-Application/2.5'); 
		 
$list_post = get_posts( array(
	'posts_per_page'   	=> -1,
	'meta_key'   		=> 'update_available',
	'meta_value' 		=> 'yes',
) );

 
 
if ($list_post){ ?>
<div class="play_menu" style="text-transform:uppercase"><b>List all Available app to updates </b></div>
<?php } else { ?>
<div class="play_menu" style="text-transform:uppercase"><b>Welldone... No Available app to updates </b></div>
<?php } if ($list_post){ ?>
<section>
<div class="row">
<?php  
foreach($list_post as $p) {
$appnames				= wp_strip_all_tags(get_post_meta( $p->ID, 'wp_title_GP',  true )); 
$available_version		= get_post_meta($p->ID, 'available_version', true );
$current_version		= get_post_meta($p->ID, 'wp_version_GP', true );
$image_id				= get_post_thumbnail_id($p->ID); 
$image_url				= wp_get_attachment_image_src($image_id, 'thumbnail', true)[0]; 

if (version_compare($available_version, $current_version ) > 0 ) { 
?>
        <div class="col-12 col-md-6 mb-4">
            <span class="position-relative archive-post--remove app-container">
                <div class="flex-shrink-0">
                    <img src="<?php echo $image_url; ?>" class="app-logo " width="64" height="64">
                </div>

                <div class="app-info">
                    <h3 class="h5 font-weight-semibold w-100 app-title up-down-shake"><?php echo $appnames; ?></h3>

                    <div class="text-truncate text-muted app-desc">
                        <span class="clamp-1 w-100" style="color: black;font-weight: 700;"><i>Available updates</i> <b style="color: red;">v<?php echo $current_version; ?></b> to <b style="color: green;">v<?php echo $available_version; ?></b></span>
                    </div>
                </div>

                <div class="app-get">
                    <a style="font-size: 13px;  margin:0 12px;" href="<?php echo get_edit_post_link($p->ID); ?>" target="_blank" class="get-button rotate-shake">Update</a>
                </div>

            </span>
        </div>

        <?php }} ?>
    </div>
</section>

<?php } ?>


<?php 

echo do_shortcode( '[ft_menu]' );
echo do_shortcode( '[ft_js]' ); 
} 