<?php
// api_core bootstrap (snapshot)

date_default_timezone_set('Asia/Ho_Chi_Minh');

// These get defined by api.php before include; set safe defaults.
if (!defined('API_ACCOUNT_DIR')) define('API_ACCOUNT_DIR', '/var/www/html.main/mygl/premium3/m12/29052012/m9939k32732');
if (!defined('API_DATA_DIR')) define('API_DATA_DIR', API_ACCOUNT_DIR . '/data');

// Ensure legacy relative paths resolve from account folder
chdir(API_ACCOUNT_DIR);

$__gl_config = require __DIR__ . '/config.snapshot.php';

require __DIR__ . '/engine.snapshot.php';

// Wrapper engine for API use: avoid UI entrypoints.
class GetlinkApiEngine extends stream_get {
    // API v1 leech-only: disable movie list loading (avoids empty path errors)
    public function loadphim() { return; }

    private array $cfg;

    public function __construct(array $cfg) {
        $this->cfg = $cfg;
        // Do NOT call parent constructor chain if it triggers UI cookies; instead call stream_get() directly.
        $this->stream_get();
    }

    // Override config() to apply snapshot limits without including legacy config files.
    public function config() {
        // Minimal subset needed for leech + bw accounting.
        $this->fileinfo_dir = 'data';
        $this->fileinfo = 'info.dat';
        $this->fileinfo_ext = 'dat';

        $this->bw_dir = '/bwplus/';

        $this->limitMBIP = 20*1024; // MB
        $this->plusbw = $this->cfg['plusbw_mb'];
        $this->maxbw = $this->cfg['maxbw_mb'];
        $this->ttl = $this->cfg['ttl_minutes'];

        $this->acc_type = [
            'reset_bw' => (bool)$this->cfg['reset_bw'],
            'type' => 'pre',
            'fullname' => 'pre',
        ];

        // Build hosts map in legacy format (MB)
        $this->hosts = [];
        foreach ($this->cfg['hosts'] as $host => $h) {
            $this->hosts[$host] = [
                'bandwidth' => $h['daily_bw_mb'],
                'total' => $h['counts_to_total'],
                'max_link' => $h['max_link'],
                'daily_bw' => $h['daily_bw_mb'],
                'overlimit_bw' => $h['overlimit_bw_mb'],
            ];
        }

        $this->max_load = 50;
        $this->Deny = false;

        // Load account identity (legacy data/info.php)
        $infoPhp = API_ACCOUNT_DIR . '/data/info.php';
        if (is_file($infoPhp)) {
            $SecureID = $email = $mobile = null;
            @include $infoPhp;
            if (is_string($email ?? null)) $this->email = $email;
            if (is_string($mobile ?? null)) $this->mobile = $mobile;
            if (is_string($SecureID ?? null)) $this->SecureID = $SecureID;
        }

        // Self URL is used in hashing + as leechmng "user" (must be account URL, not api://...)
        if (defined('API_SELF_URL') && is_string(API_SELF_URL) && API_SELF_URL !== '') {
            $this->self = API_SELF_URL;
        } else {
            $this->self = 'http://127.0.0.1/';
        }

        // User agent
        $this->UserAgent = 'GetlinkAPI/0.1';

        // ---- API shim defaults to satisfy legacy engine expectations (reduce PHP warnings) ----
        // Account created timestamp (used in BW calc tables); legacy sets this during login.
        if (!isset($this->created) || !is_numeric($this->created)) $this->created = time();

        // Legacy language strings (avoid undefined $this->lang warnings).
        if (!isset($this->lang) || !is_array($this->lang)) {
            $lang = [];
            $langFile = '/var/www/html.main/mygl/class.user/viet.star.php';
            if (is_file($langFile)) {
                @include $langFile;
                if (is_array($lang)) $this->lang = $lang;
            }
        }
        if (!isset($this->lang) || !is_array($this->lang)) {
            // Minimal fallback keys used in API leech flow.
            $this->lang = [
                'nhaplink' => 'dang leech...',
                'limit_host' => 'Host %s reached max_link %s',
                'max_bw_host_leech' => 'Host BW exceeded',
                'outbw_leech' => 'Out of BW',
                'maxget' => 'Max get',
                'errorlink' => 'Error link',
            ];
        }


        // Ensure required language keys exist (viet.star.php may miss some keys).
        $langDefaults = [
            'nhaplink' => 'dang leech...',
            'create' => 'Created',
            'expired' => 'Expired',
            'yourmail' => 'Email',
            'updatecode' => 'Update code',
            'type' => 'Type',
            'typeacc' => 'Account',
            'bwaccday' => 'BW/day',
            'limit_host' => 'Host %s reached max_link %s',
            'max_bw_host_leech' => 'Host BW exceeded',
            'outbw_leech' => 'Out of BW',
            'maxget' => 'Max get',
            'errorlink' => 'Error link',
        ];
        foreach ($langDefaults as $k => $v) {
            if (!isset($this->lang[$k])) $this->lang[$k] = $v;
        }

        // Expiry timestamp used in some HTML/status paths.
        if (!isset($this->expired) || !is_numeric($this->expired)) $this->expired = time() + 10*365*24*60*60;

        // ISP check endpoint (legacy uses this to tag requests).
        if (!isset($this->checkisp) || !is_string($this->checkisp) || $this->checkisp === '') {
            $checkisp = 'http://checkisp2022.getlink.vn:8081/newisp/';
            $this->checkisp = $checkisp.'?url='.urlencode($this->self).'&ip=';
        }
        // --------------------------------------------------------------------

        // legacy filterhost mapping (Cách 1): normalize alias domains (e.g. rg.to -> rapidgator.net)
        // Copy from class.user/config.all.php
        $this->filterhost = [
            'uploaded.net' => ['uploaded.to','ul.to'],
            'rapidgator.net' => ['rapidgator.to','rg.to'],
            'turbobit.net' => ['turbo-bit.net','trbbt.net','tbit.to','turbo.to','turbobit.cc','turb.to','turb.cc'],
            '1fichier.com' => ['alterupload.com','cjoint.net','dl4free.com','tenvoi.com','pjointe.com','megadl.fr','piecejointe.net','mesfichiers.org','dfichiers.com','desfichiers.com'],
            'hitfile.net' => ['hitf.to','hitf.cc','hitfile.cc'],
            'mega.nz' => ['mega1.nz','mega.co.nz'],
            'youtube.com' => ['youtube1.com','youtu.be'],
            'upstore.net' => ['upstore1.net','upsto.re'],
            'k2s.cc' => ['keep2share.cc','keep2s.cc','k2share.cc'],
            'katfile.com' => ['katfile.online','katfile.cloud'],
            'fboom.me' => ['fileboom.me','fileboom.com'],
            '4share.vn' => ['up2.4share.vn','up.4share.vn'],
            'nitro.download' => ['nitroflare.com'],
        ];

        // routing to leech manager (v1.1)
        $rt = $this->cfg['routing'] ?? [];
        $this->passleech = (string)($rt['passleech'] ?? '');
        $this->mng_normal = (array)($rt['mng_normal'] ?? []);
        if (!isset($this->mng_normal['other'])) $this->mng_normal['other'] = '';
        // default manager endpoint
        $this->leechmng = $this->mng_normal['other'];
        if (isset($rt['mng_rieng'])) $this->mng_rieng = (array)$rt['mng_rieng'];
        $this->mng_error = (string)($rt['mng_error'] ?? '');
        $this->mng_fshare = (string)($rt['mng_fshare'] ?? '');
        $this->checklink = (string)($rt['checklink'] ?? '');

        // dummy values required by some code paths
        // Provide minimal server maps to satisfy legacy leech() paths
        $this->server = ['us' => 'US'];
        $this->sv_root = ['vnpt' => ['us'], 'other' => ['us']];
        $this->maxsv = 1;
    }

    // Pure leech entrypoint for API
    public function leech_api(string $url): string {
        $_POST = [
            'urllist' => $url,
            'download' => 'leech',
            'leech' => '1',
        ];
        // Most of the legacy code expects myip/owner; set safe defaults.
        $this->myip = '127.0.0.1';
        $this->owner = 1;

        // Ensure legacy cookies exist for leech() (prevents Undefined array key "network")
        if (!isset($_COOKIE['network'])) $_COOKIE['network'] = 'api';

        // Call leech directly (avoid main())
        return (string)$this->leech($url);
    }
}

function getlink_api_engine(): GetlinkApiEngine {
    global $__gl_config;
    static $engine = null;
    if ($engine instanceof GetlinkApiEngine) return $engine;
    $engine = new GetlinkApiEngine($__gl_config);
    return $engine;
}
