<?php 
/* --------------------------------------------------------------------
 * Main function: Check if a newer version is available on Google Play
 * Updated: December 16, 2025 - Integrated reliable fallback proxy
 * ------------------------------------------------------------------ 
*/
if ( ! function_exists( 'app_update_available' ) ) 
{

	function app_update_available( $post_id, $debug = false ) 
	{
		global $opt_themes;

		$post_id = (int) $post_id;

		/* --------------------------------------------------------------------
		 * Validate post
		 * ------------------------------------------------------------------ */
		if ( ! $post_id || ! get_post( $post_id ) ) {
			if ( $debug ) {
				echo '<div class="notice notice-error is-dismissible app-update-debug-notice">';
				echo "<p>⚠️ [ERROR] Invalid post ID: $post_id ⚠️</p>";
				echo '</div>';
			}
			return false;
		}

		/* --------------------------------------------------------------------
		 * 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 ) {
			if ( $debug ) {
				echo '<div class="notice notice-error is-dismissible app-update-debug-notice">';
				echo "<p>⚠️ [SKIP] Post <strong>#$post_id</strong> is locked ⚠️</p>";
				echo '</div>';
			}
			return false;
		}

		set_transient( $lock_key, time(), 10 * MINUTE_IN_SECONDS );

		try {

			/* ----------------------------------------------------------------
			 * Required meta
			 * -------------------------------------------------------------- */
			$appid = get_post_meta( $post_id, 'wp_GP_ID', true );
			$title = get_post_meta( $post_id, 'wp_title_GP', true );
			$title = $title ?: get_the_title( $post_id );

			if ( ! $appid ) {
				if ( $debug ) {
					echo '<div class="notice notice-warning is-dismissible app-update-debug-notice">';
					echo "<p>⚠️ <strong>[SKIP]</strong> #$post_id <strong>{$title}</strong> No Google Play ID ⚠️</p>";
					echo '</div>';
				}
				update_post_meta( $post_id, '_time_scrape_app_update', time() );
				return false;
			}

			if ( $debug ) {
				echo '<div class="notice notice-success is-dismissible app-update-debug-notice">';
				echo "<p>Checking <strong style='color:#2271b1;'>#$post_id</strong> → ";
				echo "<strong style='color:#2271b1;font-weight:bold;padding:0 5px;'>{$title}</strong> → ";
			}

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

			/* ----------------------------------------------------------------
			 * Primary: Google Play
			 * -------------------------------------------------------------- */
			try {
				$lang    = $opt_themes['apk_language'] ?? 'en-US';
				$country = $opt_themes['apk_country'] ?? '';
				$gplay   = new \Nelexa\GPlay\GPlayApps( $lang, $country );
				$info    = $gplay->getAppInfo( $appid );

				$raw = $info->getAppVersion();

				if ( $raw && stripos( $raw, 'varies' ) === false ) {
					$new_version  = function_exists( 'normalize_version' ) ? normalize_version( $raw ) : $raw;
					$new_whatsnew = $info->getRecentChanges() ?: '';
					$source_used = 'GooglePlay';
				}
			} catch ( Exception $e ) {
				if ( $debug ) {
					echo " ⚠️ <span style='color:orange'>[ERROR]</span> GooglePlay failed: "
					   . esc_html( $e->getMessage() );
				}
			}

			/* ----------------------------------------------------------------
			 * Fallback: exthem.es
			 * -------------------------------------------------------------- */
			if ( ! $new_version ) {

				$url = 'https://a-a.my.id/gps.php?pkgid=' . rawurlencode( $appid );
				$response = wp_remote_get( $url, [
					'timeout' => 12,
					'headers' => [
						'User-Agent' => 'Mozilla/5.0 (WordPress App Update Bot)'
					]
				]);

				if ( is_wp_error( $response ) ) {
					if ( $debug ) {
						echo " ⚠️ <span style='color:maroon'>[ERROR]</span> Fallback request failed: "
						   . esc_html( $response->get_error_message() );
					}
				} else {
					$body = wp_remote_retrieve_body( $response );

					if ( preg_match( '/<div class="version">(.*?)<\/div>/i', $body, $m ) ) {
						$new_version = function_exists( 'normalize_version' )
							? normalize_version( trim( $m[1] ) )
							: trim( $m[1] );
						$source_used = 'exthem.es';
					}

					if ( preg_match( '/<div class="whatsnew">(.*?)<\/div>/is', $body, $m ) ) {
						$new_whatsnew = trim( strip_tags( $m[1] ) );
					}
				}
			}

			/* ----------------------------------------------------------------
			 * Final compare
			 * -------------------------------------------------------------- */
			if ( ! $new_version ) {
				if ( $debug ) {
					echo " <span style='color:red'>[FAILED]</span> No version retrieved ⚠️";
					echo '</p></div>';
				}
				update_post_meta( $post_id, '_time_scrape_app_update', time() );
				return false;
			}

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

			if ( version_compare( $new_version, $current, '>' ) ) {

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

				if ( $debug ) {
					echo "<strong style='color:crimson;font-weight:bold;padding:0 5px;'>v{$current}</strong> ↪️ ";
					echo "<strong style='color:crimson;font-weight:bold;padding:0 5px;'>v{$new_version}</strong> ";
					echo "<span style='color:green;font-weight:bold'>[UPDATE AVAILABLE]</span>";
					echo " -== checked by {$source_used} ==-</p></div>";
				}

				do_action( 'app_update_detected', $post_id, [
					'post_id'         => $post_id,
					'appid'           => $appid,
					'title'           => $title,
					'current_version' => $current,
					'new_version'     => $new_version,
					'new_whatsnew'    => $new_whatsnew,
					'source'          => $source_used,
				] );

			} else {
				clear_app_update_flags( $post_id );
				if ( $debug ) {
					echo "<strong style='color:crimson;font-weight:bold;padding:0 5px;'>v{$current}</strong> ";
					echo "✔️ <span style='color:dodgerblue;font-weight:bold'>[UP TO DATE]</span>";
					echo " -== checked by {$source_used} ==-</p></div>";
				}
			}

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

		} finally {
			delete_transient( $lock_key );
		}
	}
}
