<?php 

use Nelexa\GPlay\GPlayApps; 
use Nelexa\GPlay\Exception\GooglePlayException;

class Go_Curl 
{ 
	public function fast_get_contents($url) {
		$ch = curl_init($url);
		curl_setopt_array($ch, [
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_TIMEOUT        => 10,               // jangan terlalu lama
			CURLOPT_CONNECTTIMEOUT => 5,
			CURLOPT_FOLLOWLOCATION => true,
			CURLOPT_MAXREDIRS      => 5,
			CURLOPT_SSL_VERIFYPEER => false,            // matikan jika target SSL bermasalah (hati-hati!)
			CURLOPT_USERAGENT      => 'Mozilla/5.0 (compatible; FastBot/1.0)',
			CURLOPT_ACCEPT_ENCODING => '',              // aktifkan gzip/deflate/brotli otomatis
			CURLOPT_HEADER         => false,
			CURLOPT_NOBODY         => false, 
		]); 
		$response = curl_exec($ch);
		curl_close($ch);
		return $response ?: ''; // fallback kosong jika gagal
	}

	public function scrapesite($url, $ua = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36', $referer = 'https://www.google.com/') {
		if (function_exists('curl_exec')) {
			$header = ["Accept-Language: en-US,en;q=0.9"];

			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
			curl_setopt($ch, CURLOPT_USERAGENT, $ua);
			curl_setopt($ch, CURLOPT_REFERER, $referer);
			curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
			curl_setopt($ch, CURLOPT_TIMEOUT, 30);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Note: insecure, use only if needed
			curl_setopt($ch, CURLOPT_HEADER, false);

			$html = curl_exec($ch);
			if (curl_error($ch)) {
				error_log('cURL error: ' . curl_error($ch));
				$html = false;
			}
			curl_close($ch);
		} else {
			$html = @file_get_contents($url);
		}
		return $html;
	}


	/**
	 * Simple HTTP fetcher (safe for cron)
	 */
	public function scrapesite2( $url, $ua = null, $referer = 'https://www.google.com/' ) {

		if ( ! function_exists( 'curl_exec' ) ) {
			return @file_get_contents( $url );
		}

		$headers = [
			'Accept-Language: en-US,en;q=0.9',
		];

		$user_agent = $ua ?: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36';

		$ch = curl_init();
		curl_setopt_array( $ch, [
			CURLOPT_URL            => $url,
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_CUSTOMREQUEST  => 'GET',
			CURLOPT_USERAGENT      => $user_agent,
			CURLOPT_REFERER        => $referer,
			CURLOPT_HTTPHEADER     => $headers,
			CURLOPT_TIMEOUT        => 15,
			CURLOPT_CONNECTTIMEOUT => 10,
			CURLOPT_HEADER         => false,
			CURLOPT_FOLLOWLOCATION => true,
		]);

		$html = curl_exec( $ch );
		curl_close( $ch );

		return $html;
	}


    public function scrapex($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);
        $ip = rand(0, 255) . '.' . rand(0, 255) . '.' . rand(0, 255) . '.' . rand(0, 255);
        curl_setopt($curl, CURLOPT_HTTPHEADER, ["REMOTE_ADDR: $ip", "HTTP_X_FORWARDED_FOR: $ip"]);
        curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
        curl_setopt($curl, CURLOPT_REFERER, "http://www.google.com");
        curl_setopt($curl, CURLOPT_AUTOREFERER, true);
        $data = curl_exec($curl);
        curl_close($curl);
        return $data;
    }

	public function scrape_sitex($url, $ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36', $referer = 'http://www.google.com/') {
	  if (function_exists('curl_exec')) {
		$header[0] 	= "Accept-Language: en-us,en;q=0.5";
		$agent 		= 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36';
		$agent2		= 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36';
		$agent3		= 'facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)';
		$agent4		= 'Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148';
		$agent5		= 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.83 Safari/537.36';
		$agent6		= 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36';
		$referer 	= 'http://www.google.com/';
		$ip 		= rand(0,255).'.'.rand(0,255).'.'.rand(0,255).'.'.rand(0,255); 
		$ips 		= '51.68.87.157:49320';
			
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');   
		curl_setopt($ch, CURLOPT_USERAGENT, $agent);
		curl_setopt($ch, CURLOPT_REFERER, $referer);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
		//curl_setopt($ch, CURLOPT_TIMEOUT, 10);	
		curl_setopt($ch, CURLOPT_HEADER, false); 
		curl_setopt($ch, CURLOPT_HTTPHEADER, ["REMOTE_ADDR: $ip", "HTTP_X_FORWARDED_FOR: $ip"]);
		
		$html = curl_exec($ch);
		curl_close($ch);
	  } else { 
		//$html = file_get_contents($url);
		$html = @file_get_contents($url);
	  }
	  return $html;
	}
	
	public function file_get_contents_curlx($url, $retries=5){
		$ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.82 Safari/537.36';

		if (extension_loaded('curl') === true) {
			$ch = curl_init();

			curl_setopt($ch, CURLOPT_URL, $url); // The URL to fetch. This can also be set when initializing a session with curl_init().
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); // TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
			curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); // The number of seconds to wait while trying to connect.
			curl_setopt($ch, CURLOPT_USERAGENT, $ua); // The contents of the "User-Agent: " header to be used in a HTTP request.
			curl_setopt($ch, CURLOPT_FAILONERROR, TRUE); // To fail silently if the HTTP code returned is greater than or equal to 400.
			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); // To follow any "Location: " header that the server sends as part of the HTTP header.
			curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE); // To automatically set the Referer: field in requests where it follows a Location: redirect.
			curl_setopt($ch, CURLOPT_TIMEOUT, 10); // The maximum number of seconds to allow cURL functions to execute.
			curl_setopt($ch, CURLOPT_MAXREDIRS, 5); // The maximum number of redirects

			$result = curl_exec($ch);

			curl_close($ch);
		} else {
			$result = @file_get_contents($url);
		} if (empty($result) === true) {
			$result = false;

			if ($retries >= 1) {
				sleep(1);
				return file_get_contents_curlx($url, --$retries);
			}
		}    

		return $result;
	}
	
	public function get_linkx($url){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
		$ip = rand(0,255).'.'.rand(0,255).'.'.rand(0,255).'.'.rand(0,255); 
		curl_setopt($ch, CURLOPT_HTTPHEADER, array("REMOTE_ADDR: $ip", "HTTP_X_FORWARDED_FOR: $ip"));
		//curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/".rand(3,5).".".rand(0,3)." (Windows NT ".rand(3,5).".".rand(0,2)."; rv:2.0.1) Gecko/20100101 Firefox/".rand(3,5).".0.1");
		curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36");
		//curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:130.0) Gecko/20100101 Firefox/130.0");
		curl_setopt($ch, CURLOPT_REFERER, "http://www.google.com");
		curl_setopt($ch, CURLOPT_AUTOREFERER, true);
		$html = curl_exec($ch);
		curl_close($ch);
		return $html;
	}
	
	public function my_curl_functionx($url) {
		$curl_handle = curl_init();
		curl_setopt($curl_handle, CURLOPT_URL, $url);
		curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
		curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($curl_handle, CURLOPT_USERAGENT, 'name');
		$html = curl_exec($curl_handle);
		curl_close($curl_handle);
		return $html;
	}
	
	public function scraperapix($url){
		global $opt_themes;
		$apikey		= $opt_themes['api_zenrow']; 
		$country	= 'us'; 
		$url 		= "http://api.scraperapi.com?api_key=".$apikey."&url=".$url."&render=true&country_code=".$country;
		$ch 		= curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($ch, CURLOPT_HEADER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		$response 	= curl_exec($ch);
		curl_close($ch);
		return $response;
	}
	
	public function api_randx(){ 
		global $opt_themes;		
		//$token = "13bd9cbd09e74dc1a658b0c29a9e3b40ef962b05205"; //dgsila
		//$token2 = "db9f3324a69f4b2a95e0c2887e3f2018079ccba050f"; //jadwal21
		//$token3 = "68cf4525303b4d9b9a9583c6edfa5b9611b5d3facd7"; //manggalawebsite
		$keyz			= $opt_themes['api_key_scrape'];
		$rand_apikey 	= array_rand($keyz);
		$apikey 		= $keyz[$rand_apikey];  	
		return $apikey; 
	}
	
	public function scrapedox($url){ 
	global $opt_themes;
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_HEADER, false);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
		//$url = "https://httpbin.co/anything";
		//$token = "YOUR_TOKEN";
		$apikey	= $this->api_randx();  	
		$proxy = sprintf("http://%s:@proxy.scrape.do:8080", $apikey);
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');
		curl_setopt($curl, CURLOPT_PROXY, $proxy);
		curl_setopt($curl, CURLOPT_HTTPHEADER, array(
			"Accept: */*",
		));
		$response = curl_exec($curl);
		curl_close($curl);
		return $response;
		//echo $response;
	}
	
	public function get_http_response_codesx($url) {
		if (filter_var($url, FILTER_VALIDATE_URL) === false) {
			return false;
		}

		$ch = curl_init($url);

		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_NOBODY, true);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
		curl_setopt($ch, CURLOPT_TIMEOUT, 5);

		$ip = rand(0, 255) . '.' . rand(0, 255) . '.' . rand(0, 255) . '.' . rand(0, 255);

		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
			"REMOTE_ADDR: $ip",
			"HTTP_X_FORWARDED_FOR: $ip",
			"User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
			"Referer: http://m.apkpure.com",
		));

		curl_exec($ch);

		$response_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

		curl_close($ch);

		return $response_code === 200;
	}
	
	public function http_responsex($url) { 
		$ch			= curl_init(); 
		curl_setopt($ch, CURLOPT_URL, $url); 
		curl_setopt($ch, CURLOPT_HEADER, TRUE); 
		curl_setopt($ch, CURLOPT_NOBODY, TRUE); 
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
		$head		= curl_exec($ch); 
		$httpCode	= curl_getinfo($ch, CURLINFO_HTTP_CODE); 
		curl_close($ch); 
		if(!$head){  
		return FALSE; 
		}
		return $httpCode;
		sleep(rand(1, 5));
	}
	
	public function ouo_io($url) {
		$apikey		= 'mH4aOrLs'; 
		$url 		= "http://ouo.io/api/{$apikey}?s=".urlencode($url);
		$ch 		= curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($ch, CURLOPT_HEADER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		$response 	= curl_exec($ch);
		curl_close($ch);
		$html 		= @file_get_contents($url);
		if( $html ){
			return $html;
		}
	}
	
    public function match_all_key_value($regex, $str, $keyIndex = 1, $valueIndex = 2) {
        $arr = array();
        preg_match_all($regex, $str, $matches, PREG_SET_ORDER);
        foreach ($matches as $m) {
            $arr[$m[$keyIndex]] = $m[$valueIndex];
        }
        return $arr;
    }

    public function match_all($regex, $str, $index = 0) {
        if (preg_match_all($regex, $str, $matches) === false) {
            return false;
        } else {
            return $matches[$index];
        }
    }

    public function match($regex, $str, $index = 0) {
        if (preg_match($regex, $str, $match) == 1) {
            return $match[$index];
        } else {
            return false;
        }
    }
	
	/**
	 * Validate and extract a clean Google Play package ID from various input formats
	 *
	 * Accepts:
	 *   - Full URLs: https://play.google.com/store/apps/details?id=com.example.app
	 *   - Short URLs: play.google.com/store/apps/details?id=com.example.app
	 *   - Partial with params: ...?id=com.example.app&hl=en
	 *   - Just the ID: com.example.app
	 *
	 * Returns:
	 *   - string: Valid package ID (e.g., 'com.supercell.clashofclans')
	 *   - bool: false if invalid or not found
	 *
	 * @param string $gplay_url The input string containing the Play Store URL or ID
	 * @return string|false
	 */
	public function validate_gplay_id($gplay_url) {
		if (empty($gplay_url) || !is_string($gplay_url)) {
			return false;
		}

		$input = trim($gplay_url);

		// === Step 1: Extract ?id= parameter from any URL ===
		if (preg_match('/[?&]id=([a-zA-Z0-9._]+)/i', $input, $matches)) {
			$package_id = $matches[1];
		}
		// === Step 2: If no ?id=, check if the input is already a package name ===
		elseif (preg_match('/^[a-zA-Z0-9._]+$/', $input) && strpos($input, '.') !== false) {
			$package_id = $input;
		}
		// === Not a recognizable format ===
		else {
			return false;
		}

		// === Step 3: Strict validation of package name format ===
		// Must:
		// - Start with a lowercase letter or number
		// - Contain only lowercase letters, numbers, underscores, and dots
		// - Have at least two segments (e.g., com.example)
		// - Not end with a dot
		// - No consecutive dots
		if (
			!preg_match('/^[a-z0-9][a-z0-9._]*[a-z0-9]$/i', $package_id) ||           // Valid chars + doesn't start/end with special
			strpos($package_id, '..') !== false ||                                   // No double dots
			substr($package_id, -1) === '.' ||                                       // Doesn't end with dot
			substr($package_id, 0, 1) === '.' ||                                     // Doesn't start with dot
			substr_count($package_id, '.') < 1                                        // At least one dot (com.example)
		) {
			return false;
		}

		// Optional: Convert to lowercase (Google Play IDs are case-insensitive, but usually lowercase)
		$package_id = strtolower($package_id);

		// === Final sanity check: Should start with common reverse domain (com, net, org, etc.) ===
		// This helps filter out garbage like "123" or "abc"
		if (!preg_match('/^(com|net|org|edu|gov|app|game|io|co|me|tv|dev)\./', $package_id)) {
			// You can make this stricter or looser depending on your needs
			// Comment out the above line if you want to allow uncommon prefixes
		}

		return $package_id;
	}
	
	public function get_playstore_id_by_title1($title) {
		$gplay = new GPlayApps();

		// Search app berdasarkan judul (bisa tambah locale, country, dll)
		$results = $gplay->search($title, 5); // ambil 5 hasil teratas untuk akurasi

		if (!empty($results)) {
			// Ambil hasil pertama (biasanya paling relevan)
			$app = $results[0];
			return $app->getId(); // return package ID, misal: com.whatsapp
		}

		return null;
		
	}
	
	public function get_playstore_id_by_title($title, $limit = 10) {
		$gplay = new GPlayApps(); // Bisa set locale/country: new GPlayApps('id_ID', 'id');

		try {
			$results = $gplay->search($title, $limit); // Search langsung di Play Store

			if (!empty($results)) {
				// Hasil pertama biasanya paling relevan
				// Atau loop untuk cek nama exact match jika mau lebih presisi
				foreach ($results as $app) {
					if (strtolower($app->getName()) === strtolower($title)) {
						return $app->getId();
					}
				}
				// Fallback ke hasil pertama
				return $results[0]->getId();
			}
		} catch (GooglePlayException $e) {
			error_log('GPlay Error: ' . $e->getMessage());
		}

		return null;
	}
	
	public function get_playstore_id_by_title_google($title) {
		// Langsung scrape halaman search Play Store (lebih akurat daripada via Google/Bing)
		// Hanya pakai cURL built-in PHP, tanpa library eksternal

		$query = urlencode($title);
		$url = "https://play.google.com/store/search?q={$query}&c=apps&hl=en_US&gl=us"; // hl=en_US & gl=us untuk hasil konsisten

		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Untuk testing, matikan di produksi
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36');
		curl_setopt($ch, CURLOPT_HTTPHEADER, [
			'Accept-Language: en-US,en;q=0.9'
		]);

		$html = curl_exec($ch);
		$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		curl_close($ch);

		if ($httpCode != 200 || empty($html)) {
			return null;
		}

		// Regex untuk cari link details?id= di HTML (biasanya ada di href="/store/apps/details?id=...")
		// Pattern ini works di 2026 berdasarkan struktur terkini: href sering "/store/apps/details?id=com.example.app"
		if (preg_match('/\/store\/apps\/details\?id=([a-zA-Z0-9\._]+)/', $html, $match)) {
			return $match[1]; // Package ID pertama (biasanya paling relevan)
		}

		// Alternatif regex jika format beda (full URL)
		if (preg_match('/play\.google\.com\/store\/apps\/details\?id=([a-zA-Z0-9\._]+)/', $html, $match)) {
			return $match[1];
		}

		return null;
	}
 
	public function getAppTitle(
		string $packageId,
		string $lang = 'en_US',
		string $country = 'US'
	): string {
		$gplay = new \Nelexa\GPlay\GPlayApps($defaultLocale = $lang, $defaultCountry = $country);
		
		try {
			$appInfo = $gplay->getAppInfo($packageId);
			return $appInfo->getName(); // ← benar, ini mengembalikan judul/nama aplikasi
		} catch (\Nelexa\GPlay\Exception\GooglePlayException $e) {
			return "Not found or error: " . $e->getMessage();
		}
	}
	
	public function getAppsCategory(
		string $packageId,
		string $lang = 'en_US',
		string $country = 'US'
	): string {   // ← changed return type to string
		$gplay = new \Nelexa\GPlay\GPlayApps($lang, $country);
		
		try {
			$appInfo = $gplay->getAppInfo($packageId);
			return $appInfo->getCategory()->getName();
		} catch (\Nelexa\GPlay\Exception\GooglePlayException $e) {
			return "Not found or error: " . $e->getMessage();
		}
	}
	
	public function getAppsPoster(
		string $packageId,
		string $lang = 'en_US',
		string $country = 'US'
	): string {   // ← changed return type to string
		$gplay = new \Nelexa\GPlay\GPlayApps($lang, $country);
		
		try {
			$appInfo = $gplay->getAppInfo($packageId);
			return $appInfo->getIcon()->getUrl();
		} catch (\Nelexa\GPlay\Exception\GooglePlayException $e) {
			return "Not found or error: " . $e->getMessage();
		}
	}
	
	public function getAppsLink(
		string $packageId,
		string $lang = 'en_US',
		string $country = 'US'
	): string {   // ← changed return type to string
		$gplay = new \Nelexa\GPlay\GPlayApps($lang, $country);
		
		try {
			$appInfo = $gplay->getAppInfo($packageId);
			return $appInfo->getUrl();
		} catch (\Nelexa\GPlay\Exception\GooglePlayException $e) {
			return "Not found or error: " . $e->getMessage();
		}
	}
	
	public function getAppsVersi(
		string $packageId,
		string $lang = 'en_US',
		string $country = 'US'
	): string {   // ← changed return type to string
		$gplay = new \Nelexa\GPlay\GPlayApps($lang, $country);
		
		try {
			$appInfo = $gplay->getAppInfo($packageId);
			return $appInfo->getAppVersion();
		} catch (\Nelexa\GPlay\Exception\GooglePlayException $e) {
			return "Not found or error: " . $e->getMessage();
		}
	}
	
	public function getTopFreeGames($limit = 25)
	{
		//$url = "https://play.google.com/store/games?device=phone?hl={$lang}&gl={$country}";
		//$url = "https://play.google.com/store/games?device=phone&hl=en_US&gl=US";
		$url = "https://play.google.com/store/games";
		$ch = curl_init();
		curl_setopt_array($ch, [
			CURLOPT_URL            => $url,
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_FOLLOWLOCATION => true,
			CURLOPT_TIMEOUT        => 45,
			CURLOPT_USERAGENT      => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
			CURLOPT_HTTPHEADER     => ['Accept-Language: en-US,en;q=0.9'],
			CURLOPT_SSL_VERIFYPEER => false,
		]);

		$html = curl_exec($ch);
		$error = curl_error($ch);
		curl_close($ch);

		if ($error || empty($html)) {
			return "Failed to fetch page: " . ($error ?: "No content");
		}

		$doc = new DOMDocument();
		@$doc->loadHTML($html); // @ untuk suppress warning HTML5
		$xpath = new DOMXPath($doc);

		$games = [];
		$rank = 1;

		// XPath utama untuk card game di Top Free (struktur umum 2026)
		$cards = $xpath->query("//div[contains(@class, 'VfPpkd-EScbFb-JIbuQc') or contains(@class, 'ULeU3b')]//a[contains(@href, '/store/apps/details?id=')]");

		foreach ($cards as $card) {
			if (count($games) >= $limit) break;

			// 1. Link detail & Package ID
			$link = $card->getAttribute('href');
			if (!str_contains($link, 'details?id=')) continue;
			$fullLink = 'https://play.google.com' . $link;
			parse_str(parse_url($link, PHP_URL_QUERY), $params);
			$package = $params['id'] ?? 'unknown';
			
			// Extract package ID sebagai fallback judul
			preg_match('/id=([^&]+)/', $link, $matches);
			$packageId = $matches[1] ?? 'unknown.id';
			
			// 2. Judul
			$titleNode = $xpath->query(".//span[contains(@class, 'DdYX5') or contains(@class, 'Epkrse') or contains(@class, 'title')]", $card)->item(0);
			$title = $titleNode ? trim($titleNode->textContent) : 'No Title';

			// 3. Image Icon (cari img dengan srcset untuk resolusi tinggi)
			$imgNode = $xpath->query(".//img[contains(@srcset, 'play-lh.googleusercontent') or contains(@src, 'play-lh.googleusercontent')]", $card)->item(0);
			$image = '';
			if ($imgNode) {
				$srcset = $imgNode->getAttribute('srcset');
				if ($srcset) {
					// Ambil URL resolusi tertinggi dari srcset
					$parts = explode(',', $srcset);
					$highest = trim(end($parts));
					$image = explode(' ', $highest)[0] ?? $imgNode->getAttribute('src');
				} else {
					$image = $imgNode->getAttribute('src');
				}
			}

			if ($title !== 'No Title' && $fullLink) {
				$games[] = [
					'rank'   => $rank++,
					'package_id' => $packageId,
					'title'  => $title,
					'link'   => $fullLink,
					'image'  => $image ?: 'No image found'
				];
			}
		}

		return $games ?: ['error' => 'Couldn\'t find the game (HTML structure may have changed)'];
	}
	
	public function scrapeGooglePlayApps(
		string $country = 'US',
		string $lang = 'en_US',
		int $limit = 15,
		string $collection = 'topselling_free' // kosongkan '' untuk halaman utama popular
	): array {
		$base = "https://play.google.com/store/";
		$url = $collection 
			? $base . "apps/collection/{$collection}?hl={$lang}&gl={$country}&device=phone"
			: $base . "apps?hl={$lang}&gl={$country}&device=phone";

		$ch = curl_init();
		curl_setopt_array($ch, [
			CURLOPT_URL            => $url,
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_FOLLOWLOCATION => true,
			CURLOPT_TIMEOUT        => 20,
			CURLOPT_USERAGENT      => 'Mozilla/5.0 (Linux; Android 14; Pixel 9) AppleWebKit/537.36 '
									 . '(KHTML, like Gecko) Chrome/132.0.0.0 Mobile Safari/537.36',
			CURLOPT_HTTPHEADER     => ['Accept-Language: ' . $lang],
			CURLOPT_SSL_VERIFYPEER => false, // hanya testing
		]);

		$html = curl_exec($ch);
		$err  = curl_error($ch);
		curl_close($ch);

		if ($err || strlen($html) < 4000) {
			return ['error' => 'Failed to fetch page (possibly JS-only):' . ($err ?: 'content too small')];
		}

		libxml_use_internal_errors(true);
		$doc = new DOMDocument();
		$doc->loadHTML('<?xml encoding="utf-8"?>' . $html);
		$xpath = new DOMXPath($doc);

		$apps = [];

		// Cari semua link detail app (sinyal paling stabil yang tersisa di static HTML)
		$linkNodes = $xpath->query("//a[contains(@href, '/store/apps/details?id=')]");

		if ($linkNodes->length === 0) {
			$debugFile = 'play_debug_' . time() . '.html';
			file_put_contents($debugFile, $html);
			return ['error' => "No app link found in static HTML → full JS dependent. Debug saved: $debugFile"];
		}

		$rank = 1;
		foreach ($linkNodes as $link) {
			if ($rank > $limit) break;

			$href = $link->getAttribute('href');
			$detailUrl = str_starts_with($href, 'http') ? $href : 'https://play.google.com' . $href;

			// Extract package ID sebagai fallback judul
			preg_match('/id=([^&]+)/', $href, $matches);
			$packageId = $matches[1] ?? 'unknown.id';

			// Percobaan ekstrak title (prioritas pola lama + fallback)
			$titleQueries = [
				// Pola utama yang kamu inginkan (ubGTjb + sT93pb DdYX5 OnEJge)
				".//div[contains(@class, 'ubGTjb')]//span[contains(@class, 'sT93pb') and contains(@class, 'DdYX5') and contains(@class, 'OnEJge')]",
				// Alternatif lain
				".//div[contains(@class, 'ubGTjb')]/span[contains(@class, 'sT93pb')]",
				".//span[contains(@class, 'DdYX5') or contains(@class, 'Epkrse') or contains(@class, 'OnEJge')]",
				".//span[string-length(normalize-space()) > 5]",
			];

			$title = ''; // mulai kosong
			foreach ($titleQueries as $q) {
				$titleNodes = $xpath->query($q, $link);
				if ($titleNodes->length > 0) {
					$title = trim($titleNodes->item(0)->textContent);
					if (strlen($title) > 4) break; // cukup bagus, stop
				}
			}

			// Jika title masih kosong / terlalu pendek → ganti jadi package ID
			if (strlen($title) <= 4 || empty($title)) {
				$title = $packageId;
			}

			// Icon (sangat jarang ada di static HTML)
			$icon = '(icon tidak ditemukan - lazy load)';
			$imgNodes = $xpath->query(".//img[contains(@src,'play-lh.googleusercontent') or @data-src]", $link);
			if ($imgNodes->length > 0) {
				$src = $imgNodes->item(0)->getAttribute('data-src') ?: $imgNodes->item(0)->getAttribute('src');
				if ($src) {
					$icon = preg_replace('/=s\d+|=w\d+-h\d+/', '=w512-h512-rw', $src);
				}
			}
			
			$category = $packageId;
			
			$apps[] = [
				'rank'       => $rank++,
				'title'      => $title,
				'package_id' => $packageId,
				'detail_url' => $detailUrl,
				'icon_url'   => $icon,
				'category'   => $category,
			];
		}
		return $apps;
	}
	 
	/**
	 * Fungsi untuk membuat shortlink menggunakan API https://url.exthem.es/api.php
	 * 
	 * @param string $long_url   URL panjang yang akan dipendekkan
	 * @param string $api_key    API key yang sudah diset di api.php
	 * @return array             Hasil berupa ['success' => bool, 'short_url' => string, 'error' => string (opsional)]
	 */
	public function shortlink(string $long_url, string $api_key): array
	{
		$api_url = "https://url.exthem.es/api.php";

		$data = [
			'url'     => $long_url,
			'api_key' => $api_key
		];

		$payload = json_encode($data);

		$options = [
			'http' => [
				'method'  => 'POST',
				'header'  => "Content-Type: application/json\r\n" .
							 "Accept: application/json\r\n" .
							 "Content-Length: " . strlen($payload) . "\r\n",
				'content' => $payload,
				'timeout' => 15
			]
		];

		$context = stream_context_create($options);
		$response = @file_get_contents($api_url, false, $context);

		// Jika gagal request (timeout, koneksi error, dll)
		if ($response === false) {
			return [
				'success' => false,
				'error'   => 'Failed to make a request to the API. Check your internet connection or API server.'
			];
		}

		// Coba decode JSON response
		$result = json_decode($response, true);

		if (json_last_error() !== JSON_ERROR_NONE || !is_array($result)) {
			return [
				'success' => false,
				'error'   => 'Response from API is not valid JSON:' . $response
			];
		}

		// Cek apakah sukses atau ada error dari API
		if (isset($result['success']) && $result['success'] === true) {
			return [
				'success'   => true,
				'short_url' => $result['short_url'] ?? '',
				'id'        => $result['id'] ?? '',
				'original'  => $result['original_url'] ?? $long_url
			];
		}

		// Jika API mengembalikan error (misal invalid key, invalid URL)
		return [
			'success' => false,
			'error'   => $result['error'] ?? 'An unknown error occurred from the API'
		];
	}	

	// Tampilkan hasil
	/* $result = $Go_Curl->shortlink(
    'https://www.google.com/search?q=contoh+url+panjang',
    'rahasia123'  // Ganti dengan API key asli kamu
	);
	if ($result['success']) {
		echo "Shortlink berhasil dibuat!\n";
		echo "Short URL : " . $result['short_url'] . "\n";
		echo "ID        : " . $result['id'] . "\n";
	} else {
		echo "Gagal membuat shortlink!\n";
		echo "Error     : " . $result['error'] . "\n";
	} 
	*/

	
}

