<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Silence is golden.

/* =====================================================
   EXTREMES – FAST CHECK UPDATES LIGHT PACKAGE
   ===================================================== */

/* -------------------------------------------
   1. Fast & Light App Update Check
-------------------------------------------- */

if ( ! function_exists('fast_app_update_light') ) 
{
    function fast_app_update_light( $post_id ) 
	{
        global $opt_themes;
        $post_id = (int) $post_id;

        // Validasi post
        if ( ! $post_id || ! get_post( $post_id ) ) {
            return [
                'status'  => 'error',
                'message' => 'Invalid post ID',
                'title'   => '',
            ];
        }

        // CRON LOCK
        $lock_key = "apk_update_lock_{$post_id}";
        $lock_time = get_transient( $lock_key );

        if ( $lock_time && ( time() - $lock_time ) > 30 * MINUTE_IN_SECONDS ) {
            delete_transient( $lock_key );
            $lock_time = false;
        }
        if ( $lock_time ) {
            return [
                'status'  => 'skip',
                'message' => 'Locked by another process',
                'title'   => get_the_title($post_id),
            ];
        }
        set_transient( $lock_key, time(), 10 * MINUTE_IN_SECONDS );

        // Meta penting
        $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 ( ! $appid ) {
            update_post_meta( $post_id, '_time_scrape_app_update', time() );
            delete_transient( $lock_key );
            return [
                'status'  => 'skip',
                'message' => 'No Google Play ID',
                'title'   => $title,
            ];
        }

        update_post_meta( $post_id, '_time_scrape_app_update', time() );

        $new_version = false;
        $new_whatsnew = '';
        $source_used = '';

        // Primary: Nelexa/GPlay
        try {
            $language = $opt_themes['apk_language'] ?? 'en-US';
            $country  = $opt_themes['apk_country'] ?? '';
            $gplay    = new \Nelexa\GPlay\GPlayApps( $language, $country );
            $appinfo  = $gplay->getAppInfo( $appid );
            $raw_version = $appinfo->getAppVersion();

            if ( ! empty( $raw_version ) && stripos( $raw_version, 'varies' ) === false ) {
                $new_version  = normalize_version( $raw_version );
                $new_whatsnew = $appinfo->getRecentChanges() ?: '';
                $source_used  = 'GooglePlay';
            }
        } catch ( Exception $e ) {
            // skip silently
        }

        // Fallback: proxy scraper
        if ( ! $new_version ) {
            $url = 'https://a-a.my.id/gps.php?pkgid=' . rawurlencode( $appid );
            $response = wp_remote_get( $url, ['timeout'=>20] );
            if ( ! is_wp_error($response) ) {
                $g_data = wp_remote_retrieve_body($response);
                if ( $g_data && stripos($g_data,'New Version :') !== false ) {
                    if ( preg_match('/<div class="version">(.*?)<\/div>/i', $g_data, $m) ) {
                        $new_version = normalize_version(trim($m[1]));
                    }
                    if ( preg_match('/<div class="whatsnew">(.*?)<\/div>/is', $g_data, $m) ) {
                        $new_whatsnew = strip_tags(trim($m[1]));
                        $new_whatsnew = preg_replace('/^\s*[-•*]\s*/m', '• ', $new_whatsnew);
                    }
                    if ( $new_version ) $source_used = 'exthem.es';
                }
            }
        }

        // Jika versi tidak ditemukan
        if ( ! $new_version ) {
            delete_transient( $lock_key );
            return [
                'status'  => 'failed',
                'message' => 'No version retrieved from any source',
                'title'   => $title,
            ];
        }

        if ( stripos( $new_version, 'varies' ) !== false ) {
            clear_app_update_flags( $post_id );
            delete_transient( $lock_key );
            return [
                'status'  => 'skip',
                'message' => 'Varies with device',
                'title'   => $title,
            ];
        }

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

        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_whatsnew',$new_whatsnew);
            update_post_meta($post_id,'app_last_update_found',time());

            $appInfo = [
                'post_id'         => $post_id,
                'appid'           => $appid,
                'title'           => $title,
                'current_version' => $current_version,
                'new_version'     => $new_version,
                'new_whatsnew'    => $new_whatsnew,
                'source'          => $source_used,
            ];

            delete_transient($lock_key);
            do_action('app_update_detected', $post_id, $appInfo);

            return array_merge(['status'=>'update'], $appInfo);
        }

        // Up to date
        clear_app_update_flags($post_id);
        delete_transient($lock_key);
        return [
            'status'  => 'up_to_date',
            'title'   => $title,
            'current_version' => $current_version,
            'source'  => $source_used,
        ];
    }

    /* ------------------------------
       Generate plain text notice
    ------------------------------- */
    function fast_app_update_light_notice($post_id) {
        $res = fast_app_update_light($post_id);
        if (!is_array($res)) return "❌ Unknown error";

        switch($res['status']){
            case 'update':
                return "✅ UPDATE AVAILABLE\nPost ID: {$post_id}\nTitle: {$res['title']}\nCurrent: {$res['current_version']}\nNew: {$res['new_version']}\n"
                     . (!empty($res['new_whatsnew']) ? "What's New: {$res['new_whatsnew']}\n": "")
                     . "Source: {$res['source']}\n";
            case 'up_to_date':
                return "✔️ UP TO DATE\nPost ID: {$post_id}\nTitle: {$res['title']}\nVersion: {$res['current_version']}\nSource: {$res['source']}\n";
            case 'failed':
                return "❌ FAILED\nPost ID: {$post_id}\nTitle: {$res['title']}\nReason: {$res['message']}\n";
            case 'skip':
                return "⚠️ SKIPPED\nPost ID: {$post_id}\nTitle: {$res['title']}\nReason: {$res['message']}\n";
            case 'error':
            default:
                return "❌ ERROR\nPost ID: {$post_id}\nTitle: {$res['title']}\nReason: {$res['message']}\n";
        }
    }

}
