<?php
  

require_once get_template_directory().'/libs/addons/vendor_7/autoload.php'; 
use Nelexa\GPlay\GPlayApps;
use Nelexa\GPlay\Model\App;

class Scrapes
{
    private GPlayApps $gplay;
    private string $language;
    private string $country;

    /**
     * Constructor – automatically reads language from your $opt_themes global
     */
    public function __construct()
    {
        global $opt_themes;

        // Get language from your theme settings (fallback to en_US)
        $this->language = $opt_themes['apk_language'] ?? 'en_US';
        $this->country  = $opt_themes['apk_country']  ?? 'us'; // recommended: add this option too

        // Initialize Google Play scraper with proper locale & country
		/*  
		$this->gplay = new GPlayApps(
            //defaultLocale: $this->language,
            //defaultCountry: $this->country
        ); 
		*/
		
		$this->gplay	= new \Nelexa\GPlay\GPlayApps( $defaultLocale = $this->language, $defaultCountry = $this->country ); 

    }

    /**
     * Main method: Get full app info by package name
     *
     * @param string $titleId   Package name like "com.whatsapp" or "com.spotify.music"
     * @return array            Clean array with app data or error
     */
    public function scrape_web_info(string $titleId): array
    {
        $titleId = trim($titleId);
        if (empty($titleId)) {
            return ['success' => false, 'error' => 'Empty package name'];
        }

        try {
            // Polite delay – VERY important to avoid Google ban
            usleep(rand(1000000, 3500000)); // 1–3.5 seconds

            /** @var App $appInfo */
            $appInfo = $this->gplay->getAppInfo($titleId);

            return [
                'success'       => true,
                'package_name'  => $appInfo->getId(),
                'name'          => $appInfo->getName(),
                'developer'     => $appInfo->getDeveloperName(),
                'rating'        => number_format($appInfo->getScore(), 1),
                'voted'       	=> $appInfo->getNumberVoters(),
                'installs'      => $appInfo->getInstallsText(),
                'installs_num'  => $appInfo->getInstalls(),
                'price'         => $appInfo->isFree() ? 'Free' : $appInfo->getPrice(),
                'currency'      => $appInfo->getCurrency(),
                'is_free'       => $appInfo->isFree(),
                'size'			=> $appInfo->getSize() ?? 'Varies',
                'version'       => $appInfo->getAppVersion() ?? 'Varies',
                'updated'       => $appInfo->getUpdated()?->format('Y-m-d'), 
                'category'      => $appInfo->getCategory()->getName(),
                'description'   => $appInfo->getDescription(),
                'whats_new'     => $appInfo->getRecentChanges(),
                'video'			=> $appInfo->getVideo(),
                'icon'          => $appInfo->getIcon()->getUrl(),
                'cover'         => $appInfo->getCover()?->getUrl(),
                'screenshots'   => array_map(fn($img) => $img->getUrl(), $appInfo->getScreenshots()),
                'url'           => $appInfo->getUrl(),
                'scraped_at'    => date('Y-m-d H:i:s')
            ];

        } catch (\Nelexa\GPlay\Exception\GooglePlayException $e) {
            return [
                'success' => false,
                'error'   => $e->getMessage(),
                'code'    => $e->getCode(),
                'package' => $titleId
            ];
        } catch (Exception $e) {
            return [
                'success' => false,
                'error'   => 'Unexpected error: ' . $e->getMessage(),
                'package' => $titleId
            ];
        }
    }
			 

}