<?php
/**
 * Plugin Name:       APK Auto Updater – Single File Edition
 * Description:       Checks all your apps for Google Play updates in true background. Zero overlap. Ultra fast. One file only.
 * Version:           2.5
 * Author:            Your Name
 * License:           GPL2
 * Text Domain:       apk-auto-updater
 */

if ( ! defined( 'ABSPATH' ) ) exit;

// ===================================================================
// 1. Built-in WP Background Processing (no external file needed)
// ===================================================================
if ( ! class_exists( 'WP_Background_Process' ) ) :

class WP_Background_Process {

    protected $action = 'wp_background_process';
    protected $identifier;
    protected $cron_hook_identifier;
    protected $cron_interval = 5; // minutes

    public function __construct() {
        $this->identifier = $this->action;
        $this->cron_hook_identifier = $this->identifier . '_cron';
        add_action( $this->cron_hook_identifier, [ $this, 'handle_cron_healthcheck' ] );
        add_action( 'init', [ $this, 'maybe_process_queue' ] );
    }

    public function push_to_queue( $data ) {
        $batch = $this->get_batch();
        $batch->data[] = $data;
        update_option( $batch->key, $batch );
        return $this;
    }

    public function save() { return $this; }

    public function dispatch() {
        if ( ! wp_next_scheduled( $this->cron_hook_identifier ) ) {
            wp_schedule_event( time() + 10, 'every_minute', $this->cron_hook_identifier );
        }
        return $this;
    }

    protected function get_batch() {
        global $wpdb;
        $key = $this->identifier . '_batch_1';
        $batch = get_option( $key );
        if ( ! $batch ) {
            $batch = (object) [ 'key' => $key, 'data' => [] ];
        }
        return $batch;
    }

    public function is_queue_empty() {
        $batch = $this->get_batch();
        return empty( $batch->data );
    }

    public function maybe_process_queue() {
        if ( ! $this->is_queue_empty() && ! wp_next_scheduled( $this->cron_hook_identifier ) )  {
            wp_schedule_single_event( time() + 5, $this->cron_hook_identifier );
        }
    }

    public function handle_cron_healthcheck() {
        $batch = $this->get_batch();
        if ( empty( $batch->data ) ) {
            delete_option( $batch->key );
            return;
        }

        $item = array_shift( $batch->data );
        update_option( $batch->key, $batch );

        if ( $this->task( $item ) !== false ) {
            array_unshift( $batch->data, $item );
            update_option( $batch->key, $batch );
        }

        if ( ! empty( $batch->data ) ) {
            wp_schedule_single_event( time() + 5, $this->cron_hook_identifier );
        } else {
            delete_option( $batch->key );
            $this->complete();
        }
    }

    protected function task( $item ) { return false; }
    protected function complete() {}
}

// Add missing schedule
add_filter( 'cron_schedules', function( $schedules ) {
    $schedules['every_minute'] = [ 'interval' => 60, 'display' => 'Every Minute' ];
    return $schedules;
} );

endif;

// ===================================================================
// 2. The Actual APK Background Processor
// ===================================================================
class APK_Auto_Updater_Process extends WP_Background_Process {

    protected $action = 'apk_auto_updater';

    protected function task( $post_id ) {
        $post_id = (int) $post_id;

        if ( ! get_post( $post_id ) ) return false;

        $appid = get_post_meta( $post_id, 'wp_GP_ID', true );
        $title = get_post_meta( $post_id, 'wp_title_GP', true ) ?: get_the_title( $post_id );

        if ( empty( $appid ) ) return false;

        $scraper = new Go_Curl();
        $html = $scraper->scrape_sitex( 'https://a-a.my.id/gps.php?pkgid=' . urlencode( $appid ) );

        if ( ! $html || strlen( $html ) < 500 ) {
            error_log( "[APK Updater] Failed to fetch $title ($appid)" );
            return false;
        }

        $new_version = trim( $scraper->match( '/<div class="c_version">(.*?)<\/div>/ms', $html, 1 ) );
        if ( empty( $new_version ) ) return false;

        $current_version = get_post_meta( $post_id, 'wp_version_GP', true );

        if ( $new_version !== $current_version ) {
            update_post_meta( $post_id, 'wp_version_GP', $new_version );
        }

        if ( version_compare( $new_version, $current_version, '>' ) ) {
            update_post_meta( $post_id, 'available_updated', 'yes' );
            update_post_meta( $post_id, 'available_version', $new_version );
            update_post_meta( $post_id, '_available_updates_last_update_found', time() );

            do_action( 'available_updates_apk_update_detected', $post_id, [
                'post_id'         => $post_id,
                'appid'           => $appid,
                'title'           => $title,
                'current_version' => $current_version ?: 'unknown',
                'new_version'     => $new_version,
            ] );

            error_log( "[APK UPDATER] UPDATE FOUND → $title: $current_version → $new_version" );
        } else {
            delete_post_meta( $post_id, 'available_updated' );
            delete_post_meta( $post_id, 'available_version' );
        }

        update_post_meta( $post_id, '_available_updates_scraped_time', time() );
        return false;
    }

    protected function complete() {
        parent::complete();
        error_log( '[APK Updater] Full scan completed – ' . current_time('mysql') );
    }
}

// ===================================================================
// 3. Start the engine
// ===================================================================
global $apk_updater;
$apk_updater = new APK_Auto_Updater_Process();

// Schedule hourly full scan
add_action( 'wp', function() {
    if ( ! wp_next_scheduled( 'apk_updater_daily_scan' ) ) {
        wp_schedule_event( time(), 'hourly', 'apk_updater_daily_scan' );
    }
} );

add_action( 'apk_updater_daily_scan', function() {
    global $apk_updater;

    if ( ! $apk_updater->is_queue_empty() ) return;

    $posts = get_posts( [
        'post_type'      => 'post',           // CHANGE THIS TO YOUR CPT (e.g. 'app', 'download', 'game')
        'posts_per_page' => -1,
        'post_status'    => 'publish',
        'meta_query'     => [[ 'key' => 'wp_GP_ID', 'compare' => 'EXISTS' ]],
        'fields'         => 'ids',
    ] );

    foreach ( $posts as $id ) {
        $apk_updater->push_to_queue( $id );
    }

    $apk_updater->save()->dispatch();
    error_log( '[APK Updater] Started background check for ' . count($posts) . ' apps' );
} );

// Optional: Manual trigger button
add_action( 'admin_menu', function() {
    add_management_page( 'APK Update Now', 'APK Update Now', 'manage_options', 'apk-update-now', function() {
        if ( isset($_GET['run']) ) {
            do_action( 'apk_updater_daily_scan' );
            echo '<div class="updated"><p>Update check started! Check error log.</p></div>';
        }
        echo '<div class="wrap"><h1>APK Auto Updater</h1>
              <p><a href="?page=apk-update-now&run=1" class="button button-primary">Run Update Check Now</a></p></div>';
    } );
} );