<?php
class EVPAPIREGCC
{
    public $key = "78DYJZ31CDM5P7";
    private $product_id = "2";
    private $product_base = "evp-reg-cc";
    private $server_host = "https://creativedevstudio.com/wp-json/lic_keys/";
    private $api_key;
    private $caBundle;

    private static $selfobj = null;
    private $x_trace_debug = false;
    private $snapshotFile;
    private $snapshotDir;
    private $snapshotMeta = array();
    function __construct()
    {
        $this->initActionHandler();
        $this->api_key = $this->resolveApiKey();
        $this->key = $this->resolveCryptoKey($this->key);
        $this->caBundle = $this->resolveCaBundle();
        $this->snapshotFile = $this->getSnapshotPath();
    }

    private function resolveSnapshotDirectory()
    {
        if (!empty($this->snapshotDir)) {
            return $this->snapshotDir;
        }
        $custom = getenv('EVP_CACHE_DIR');
        if (!empty($custom) && $this->ensureDirectory($custom)) {
            return $this->snapshotDir = rtrim($custom, DIRECTORY_SEPARATOR);
        }
        $home = getenv('HOME');
        if (!empty($home)) {
            $homeTmp = rtrim($home, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . '.evp-' . substr(hash('sha1', $this->product_base . $this->key), 0, 10);
            if ($this->ensureDirectory($homeTmp)) {
                return $this->snapshotDir = rtrim($homeTmp, DIRECTORY_SEPARATOR);
            }
        }
        $sysTmp = sys_get_temp_dir();
        $hashDir = '.' . substr(hash('sha1', $this->getDomain() . $this->product_id . $this->key), 0, 12);
        $target = rtrim($sysTmp, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $hashDir;
        $this->ensureDirectory($target);
        return $this->snapshotDir = rtrim($target, DIRECTORY_SEPARATOR);
    }

    private function ensureDirectory($path)
    {
        if (empty($path)) {
            return false;
        }
        if (is_dir($path)) {
            return is_writable($path);
        }
        return @mkdir($path, 0700, true);
    }

    private function getSnapshotPath()
    {
        if (!empty($this->snapshotFile)) {
            return $this->snapshotFile;
        }
        $directory = $this->resolveSnapshotDirectory();
        $name = '.' . hash('sha1', $this->product_id . $this->key . $this->product_base) . '.dat';
        $this->snapshotFile = $directory . DIRECTORY_SEPARATOR . $name;
        return $this->snapshotFile;
    }

    private function persistSnapshot($response)
    {
        $path = $this->getSnapshotPath();
        $packet = array(
            'body' => $response,
            'stamp' => hash_hmac('sha256', serialize($response), $this->key),
            'created_at' => time()
        );
        $encoded = serialize($packet);
        $cipher = $this->encrypt($encoded);
        file_put_contents($path, $cipher, LOCK_EX);
        $this->snapshotMeta = array('path' => $path);
    }

    private function readSnapshot()
    {
        $path = $this->getSnapshotPath();
        if (!file_exists($path)) {
            $this->snapshotMeta = array();
            return null;
        }
        $raw = file_get_contents($path);
        if ($raw === false || $raw === '') {
            $this->snapshotMeta = array();
            return null;
        }
        $decoded = $this->decrypt($raw);
        if ($decoded === '') {
            $this->snapshotMeta = array();
            return null;
        }
        $packet = @unserialize($decoded);
        if (!is_array($packet) || !isset($packet['body'], $packet['stamp'])) {
            $this->snapshotMeta = array();
            return null;
        }
        $body = $packet['body'];
        $expected = hash_hmac('sha256', serialize($body), $this->key);
        if (!hash_equals($expected, $packet['stamp'])) {
            $this->snapshotMeta = array();
            return null;
        }
        $this->snapshotMeta = array('path' => $path);
        return $body;
    }

    function initActionHandler()
    {
        $enabled = getenv('ELITE_LICENSER_ENABLE_HANDLER');
        if ($enabled !== '1') {
            return;
        }
        if (strtoupper($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
            return;
        }
        $handler = hash("crc32b", $this->product_id . $this->key . $this->getDomain()) . "_handle";
        $action = isset($_POST['action']) ? $_POST['action'] : '';
        $control = isset($_POST['control_key']) ? $_POST['control_key'] : '';
        $expected = getenv('ELITE_LICENSER_CONTROL_KEY');
        if ($expected === false || $expected === '') {
            return;
        }
        if ($action === $handler && hash_equals($expected, $control)) {
            $this->handleServerRequest();
            exit;
        }
    }

    function handleServerRequest()
    {
        $type = isset($_POST['type']) ? strtolower($_POST['type']) : "";
        switch ($type) {
            case "rl": //remove license
                $this->removeOldResponse();
                $obj = new stdClass();
                $obj->product = $this->product_id;
                $obj->status = true;
                echo $this->encryptObj($obj);
                return;
            case "dl": //delete app
                $obj = new stdClass();
                $obj->product = $this->product_id;
                $obj->status = true;
                $this->removeOldResponse();
                echo $this->encryptObj($obj);
                return;
            default:
                return;
        }
    }

    function __plugin_updateInfo()
    {
        if (function_exists("file_get_contents")) {
            $body = file_get_contents($this->server_host . "product/update/" . $this->product_id);
            $responseJson = json_decode($body);
            if (is_object($responseJson) && !empty($responseJson->status) && !empty($responseJson->data->new_version)) {
                $responseJson->data->new_version = !empty($responseJson->data->new_version) ? $responseJson->data->new_version : "";
                $responseJson->data->version = $responseJson->data->new_version;
                $responseJson->data->url = !empty($responseJson->data->url) ? $responseJson->data->url : "";
                $responseJson->data->package = !empty($responseJson->data->download_link) ? $responseJson->data->download_link : "";
                $responseJson->data->sections = (array) $responseJson->data->sections;
                $responseJson->data->icons = (array) $responseJson->data->icons;
                $responseJson->data->banners = (array) $responseJson->data->banners;
                $responseJson->data->banners_rtl = (array) $responseJson->data->banners_rtl;
                return $responseJson->data;
            }
        }
        return NULL;
    }

    static function GetPluginUpdateInfo()
    {
        $obj = static::getInstance();
        return $obj->__plugin_updateInfo();
    }

    /**
     * @param $plugin_base_file
     *
     * @return EVPAPIREGCC|null
     */
    static function &getInstance()
    {
        if (empty(static::$selfobj)) {
            static::$selfobj = new static();
        }
        return static::$selfobj;
    }

    private function encrypt($plainText, $password = '')
    {
        if (empty($password)) {
            $password = $this->key;
        }
        $plainText = rand(10, 99) . $plainText . rand(10, 99);
        $method = 'aes-256-cbc';
        $key = substr(hash('sha256', $password, true), 0, 32);
        $iv = substr(strtoupper(md5($password)), 0, 16);
        return base64_encode(openssl_encrypt($plainText, $method, $key, OPENSSL_RAW_DATA, $iv));
    }

    /**
     * @return string
     */
    private function decrypt($encrypted, $password = '')
    {
        if (empty($password)) {
            $password = $this->key;
        }
        $method = 'aes-256-cbc';
        $key = substr(hash('sha256', $password, true), 0, 32);
        $iv = substr(strtoupper(md5($password)), 0, 16);
        $plaintext = openssl_decrypt(base64_decode($encrypted), $method, $key, OPENSSL_RAW_DATA, $iv);
        return substr($plaintext, 2, -2);
    }

    function encryptObj($obj)
    {
        $text = serialize($obj);

        return $this->encrypt($text);
    }

    private function decryptObj($ciphertext)
    {
        $text = $this->decrypt($ciphertext);

        return unserialize($text);
    }

    private function getDomain()
    {
        $scheme = 'http';
        if (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] === 'on' || $_SERVER['HTTPS'] === 1)) {
            $scheme = 'https';
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
            $proto = strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']);
            if ($proto === 'https') {
                $scheme = 'https';
            }
        }

        $host = isset($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] !== '' ? $_SERVER['HTTP_HOST'] : php_uname('n');
        $script = isset($_SERVER['SCRIPT_NAME']) ? $_SERVER['SCRIPT_NAME'] : '/';
        $basePath = str_replace(basename($script), '', $script);

        $baseUrl = $scheme . '://' . $host . $basePath;
        if (preg_match('#/members/?$#i', $baseUrl)) {
            $baseUrl = preg_replace('#/members/?$#i', '/', $baseUrl);
        }

        return $baseUrl;  // Returns WITH trailing slash to match license manager format
    }

    private function getEmail()
    {
        return '';
    }

    private function processs_response($response)
    {
        if ($response === false || $response === '') {
            $result = new stdClass();
            $result->status = false;
            $result->msg = 'Empty response';
            $result->data = null;
            return $result;
        }

        $decoded = json_decode($response);
        if (is_object($decoded)) {
            if (!isset($decoded->status)) {
                $decoded->status = false;
            }
            if (!isset($decoded->msg)) {
                $decoded->msg = '';
            }
            if (!isset($decoded->data)) {
                $decoded->data = null;
            }
            return $decoded;
        }

        $result = new stdClass();
        $result->status = false;
        $result->msg = 'Invalid JSON response';
        $result->data = null;
        return $result;
    }

    private function _request($relative_url, $data, &$error = '')
    {
        $curl = curl_init();
        $url = rtrim($this->server_host, '/') . "/" . ltrim($relative_url, '/');
        $encodedData = http_build_query($data);

        curl_setopt_array($curl, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYHOST => 2,
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_VERBOSE => false,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $encodedData,
            CURLOPT_HTTPHEADER => array(
                "Content-Type: application/x-www-form-urlencoded",
                "cache-control: no-cache"
            ),
        ));

        if (!empty($this->caBundle) && file_exists($this->caBundle)) {
            curl_setopt($curl, CURLOPT_CAINFO, $this->caBundle);
        }

        $serverResponse = curl_exec($curl);
        $error = curl_error($curl);


        if (!empty($error)) {
            $result = new stdClass();
            $result->status = false;
            $result->msg = $error;
            $result->data = null;
            return $result;
        }

        return $this->processs_response($serverResponse);
    }

    private function getParam($purchase_key, $app_version, $admin_email = '')
    {
        $params = array(
            'api_key' => $this->apiKey(),
            'license_code' => $purchase_key,
            'domain' => $this->getDomain(),
        );

        if (!empty($app_version)) {
            $params['app_version'] = $app_version;
        }

        $email = !empty($admin_email) ? $admin_email : $this->getEmail();
        if (!empty($email)) {
            $params['email'] = $email;
        }

        return $params;
    }

    private function apiKey()
    {
        if (empty($this->api_key)) {
            $this->api_key = $this->resolveApiKey();
        }
        return $this->api_key;
    }

    private function resolveApiKey()
    {
        $env = getenv('ELITE_LICENSER_API_KEY');
        if (!empty($env)) {
            return $env;
        }
        if (defined('ELITE_LICENSER_API_KEY')) {
            $value = constant('ELITE_LICENSER_API_KEY');
            if (!empty($value)) {
                return $value;
            }
        }
        return '80D2562F-83E24CD7-6FB6E702-B9BFAB80';
    }

    private function resolveCryptoKey($default)
    {
        $env = getenv('ELITE_LICENSER_CRYPTO_KEY');
        if (!empty($env)) {
            return $env;
        }
        if (defined('ELITE_LICENSER_CRYPTO_KEY')) {
            $value = constant('ELITE_LICENSER_CRYPTO_KEY');
            if (!empty($value)) {
                return $value;
            }
        }
        return $default;
    }

    private function resolveCaBundle()
    {
        $candidate = getenv('ELITE_LICENSER_CA_BUNDLE');
        if (!empty($candidate) && file_exists($candidate)) {
            return $candidate;
        }
        return '';
    }

    function SaveResponse($response)
    {
        $this->persistSnapshot($response);
    }

    function getOldResponse()
    {
        return $this->readSnapshot();
    }

    private function removeOldResponse()
    {
        $path = $this->getSnapshotPath();
        if ($path && file_exists($path)) {
            @unlink($path);
        }
        $this->snapshotMeta = array();
        return true;
    }

    public function clearSnapshotCache()
    {
        return $this->removeOldResponse();
    }

    public static function RemoveLicenseKey(&$message = "", $version = "")
    {
        $obj = self::getInstance();
        return $obj->_removePluginLicense($message, $version);
    }

    public static function CheckLicense($purchase_key, &$error = "", &$responseObj = null, $app_version = "", $admin_email = "")
    {
        $obj = self::getInstance();
        return $obj->x_verify_7z($purchase_key, $error, $responseObj, $app_version, $admin_email);
    }

    final function x_verify_7z($k, &$e = "", &$r = null, $v = "", $m = "")
    {
        // Honeypot Trap
        if ($this->x_trace_debug === true) {
            $e = "Security violation: Debug mode detected";
            sleep(2);
            return false;
        }

        $s0 = 0; // State Machine
        $d0 = null;
        $is_f = false;
        $c_dom = $this->getDomain();

        // Anti-Analysis: Opaque Predicate
        if ((2 * 3491) !== 6982) {
            return true;
        }

        do {
            switch ($s0) {
                case 0: // Init Check
                    if (empty($k)) {
                        $this->removeOldResponse();
                        $e = "";
                        return false;
                    }
                    $s0 = 1;
                    break;

                case 1: // Cache Check
                    $o_r = $this->getOldResponse();
                    if (!empty($o_r)) {
                        $x_d = base64_decode('ZXhwaXJlX2RhdGU=');
                        if (!empty($o_r->$x_d) && strtolower($o_r->$x_d) != "no expiry" && strtotime($o_r->$x_d) < time()) {
                            $is_f = true;
                        }
                        $i_v = base64_decode('aXNfdmFsaWQ=');
                        $n_r = base64_decode('bmV4dF9yZXF1ZXN0');
                        $l_k = base64_decode('bGljZW5zZV9rZXk=');

                        if (!$is_f && !empty($o_r->$i_v) && $o_r->$n_r > time() && (!empty($o_r->$l_k) && $k == $o_r->$l_k)) {
                            $r = clone $o_r;
                            unset($r->$n_r);
                            return true;
                        }
                    }
                    $s0 = 2;
                    break;

                case 2: // Server Request
                    $p = $this->getParam($k, $v, $m);
                    $resp = $this->_request(base64_decode('bGljZW5zZS92aWV3'), $p, $e);

                    $st = base64_decode('c3RhdHVz');
                    $dt = base64_decode('ZGF0YQ==');

                    if (!empty($resp->$st) && !empty($resp->$dt)) {
                        $d0 = $resp->$dt;
                        // Integrity Check
                        if (!$this->_verify_token_integrity($d0)) {
                            $e = "Integrity check failed";
                            $this->removeOldResponse();
                            return false;
                        }
                        $s0 = 3;
                    } else {
                        $s0 = 5;
                    }
                    break;

                case 3: // Validate Response
                    $l_s = isset($d0->$st) ? strtoupper($d0->$st) : '';
                    $i_a = ($l_s === 'A' || $l_s === 'W');

                    if ($i_a) {
                        $c_dom = $this->getDomain();
                        $a_r = false;
                        if ($l_s === 'W') {
                            $this->activateLicense($k, $c_dom);
                            $this->bindDomain($k, $c_dom, $v, $m);
                            $a_r = true;
                        }

                        if ($a_r) {
                            $r_r = $this->_request(base64_decode('bGljZW5zZS92aWV3'), $this->getParam($k, $v, $m), $e);
                            if (!empty($r_r->$st) && !empty($r_r->$dt)) {
                                $d0 = $r_r->$dt;
                                $l_s = isset($d0->$st) ? strtoupper($d0->$st) : '';
                                $i_a = ($l_s === 'A' || $l_s === 'W');
                            }
                        }
                    }

                    if ($i_a) {
                        $s0 = 4; // Success Build
                    } else {
                        $ms = base64_decode('bXNn');
                        if (!empty($resp->$ms)) {
                            $e = $resp->$ms;
                        } else {
                            $e = 'License inactive';
                        }
                        $this->removeOldResponse();
                        return false;
                    }
                    break;

                case 4: // Build Cache Payload
                    $cp = new stdClass();
                    $cp->is_valid = true;
                    $cp->next_request = time() + 1800; // 30 min

                    $h_e = base64_decode('aGFzX2V4cGlyeQ==');
                    $e_t = base64_decode('ZXhwaXJ5X3RpbWU=');

                    if (isset($d0->$h_e) && strtoupper($d0->$h_e) === 'Y' && !empty($d0->$e_t)) {
                        $cp->expire_date = $d0->$e_t;
                    } else {
                        $cp->expire_date = 'No expiry';
                    }

                    $cp->support_end = isset($d0->support_end_time) ? $d0->support_end_time : '';
                    $cp->license_title = isset($d0->license_title) ? $d0->license_title : '';
                    $cp->license_key = $k;

                    $ad = base64_decode('YWN0aXZlX2RvbWFpbnM=');
                    if (!empty($d0->$ad) && is_array($d0->$ad)) {
                        $cp->active_domains = $d0->$ad;
                    }

                    $ms = base64_decode('bXNn');
                    $cp->msg = isset($resp->$ms) ? $resp->$ms : '';

                    if (method_exists($this, 'getDomain')) {
                        $cp->bound_domain = $this->getDomain();
                    }

                    $ver = isset($GLOBALS['s_ver']) ? $GLOBALS['s_ver'] : '';
                    if ($ver !== '') {
                        $cp->bound_version = $ver;
                    }

                    $this->SaveResponse($cp);
                    if (class_exists('RuntimeSignal')) {
                        RuntimeSignal::instance()->forget();
                    }

                    $r = clone $cp;
                    unset($r->next_request);
                    return true;

                case 5: // Fallback Error
                    $ms = base64_decode('bXNn');
                    $me = base64_decode('bWVzc2FnZQ==');

                    if (!empty($resp->$ms)) {
                        $e = $resp->$ms;
                    } elseif (!empty($resp->$me)) {
                        $e = $resp->$me;
                    } else {
                        $e = 'Unable to verify access';
                    }
                    return false;
            }
        } while (true);
    }

    final function _removePluginLicense(&$message = '', $version = '')
    {
        $oldRespons = $this->getOldResponse();
        if (!empty($oldRespons->is_valid)) {
            if (!empty($oldRespons->license_key)) {
                $domain = $this->getDomain();
                $this->deactivateDomain($oldRespons->license_key, $domain, $version);
                $param = array(
                    'api_key' => $this->apiKey(),
                    'license_code' => $oldRespons->license_key,
                    'domain' => $domain,
                );
                $response = $this->_request('license/remove_domain', $param, $message);
                if (!empty($response->status)) {
                    $message = isset($response->msg) ? $response->msg : 'Access revoked';
                    $this->removeOldResponse();
                    return true;
                }
                $message = !empty($response->msg) ? $response->msg : 'Deactivation failed';
            }
        }
        return false;

    }
    public static function GetRegisterInfo()
    {
        if (!empty(static::$selfobj)) {
            return static::$selfobj->getOldResponse();
        }
        return null;

    }

    private function bindDomain($licenseCode, $domain, $appVersion = '', $adminEmail = '')
    {
        $payload = $this->buildProductPayload($licenseCode, $domain, $appVersion, $adminEmail);
        $error = '';
        $response = $this->requestEncrypted('product/active/' . $this->product_id, $payload, $error);
        $this->logRemoteCall('product/active/' . $this->product_id, $payload, $response, $error);
        return $response;
    }

    private function activateLicense($licenseCode, $domain)
    {
        $payload = array(
            'api_key' => $this->apiKey(),
            'license_code' => $licenseCode,
            'status' => 'A',
            'domain' => $domain,
        );
        $error = '';
        $response = $this->_request('license/edit', $payload, $error);
        $this->logRemoteCall('license/edit', $payload, $response, $error);
    }

    private function deactivateDomain($licenseCode, $domain, $appVersion = '', $adminEmail = '')
    {
        $payload = $this->buildProductPayload($licenseCode, $domain, $appVersion, $adminEmail);
        $error = '';
        $response = $this->requestEncrypted('product/deactive/' . $this->product_id, $payload, $error);
        $this->logRemoteCall('product/deactive/' . $this->product_id, $payload, $response, $error);
        return $response;
    }

    private function buildProductPayload($licenseCode, $domain, $appVersion = '', $adminEmail = '')
    {
        $payload = array(
            'license_key' => $licenseCode,
            'domain' => $domain,
            'product_id' => $this->product_id,
            'product_base' => $this->product_base,
        );

        if (!empty($appVersion)) {
            $payload['app_version'] = $appVersion;
        }

        $email = !empty($adminEmail) ? $adminEmail : $this->getEmail();
        if (!empty($email)) {
            $payload['email'] = $email;
        }

        return $payload;
    }

    private function requestEncrypted($relative_url, $data, &$error = '')
    {
        $curl = curl_init();
        $url = rtrim($this->server_host, '/') . '/' . ltrim($relative_url, '/');
        $finalData = json_encode($data);
        if (!empty($this->key)) {
            $finalData = $this->encrypt($finalData);
        }

        curl_setopt_array($curl, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_VERBOSE => false,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => $finalData,
            CURLOPT_HTTPHEADER => array(
                'Content-Type: text/plain',
                'cache-control: no-cache'
            ),
        ));

        if (!empty($this->caBundle) && file_exists($this->caBundle)) {
            curl_setopt($curl, CURLOPT_CAINFO, $this->caBundle);
        }

        $serverResponse = curl_exec($curl);
        $error = curl_error($curl);


        if ($serverResponse === false || $serverResponse === '') {
            $result = new stdClass();
            $result->status = false;
            $result->msg = $error !== '' ? $error : 'Unknown response';
            $result->data = null;
            return $result;
        }

        return $this->processEncryptedResponse($serverResponse);
    }

    private function processEncryptedResponse($response)
    {
        $resBackup = '';
        if (!empty($response)) {
            if (!empty($this->key)) {
                $resBackup = $response;
                $response = $this->decrypt($response);
            }
            $decoded = json_decode($response);
            if (is_object($decoded)) {
                return $decoded;
            }

            $fallback = new stdClass();
            $fallback->status = false;
            $backupDecoded = @json_decode($resBackup);
            if (is_object($backupDecoded) && !empty($backupDecoded->msg)) {
                $fallback->msg = $backupDecoded->msg;
            } else {
                $fallback->msg = 'Response error, contact support';
            }
            $fallback->data = null;
            return $fallback;
        }

        $result = new stdClass();
        $result->msg = 'Unknown response';
        $result->status = false;
        $result->data = null;

        return $result;
    }

    private function logRemoteCall($endpoint, $payload, $response, $error)
    {
        if (!function_exists('error_log')) {
            return;
        }

        if (is_object($payload)) {
            $payload = json_decode(json_encode($payload), true);
        }

        $entry = array(
            'endpoint' => $endpoint,
            'url' => rtrim($this->server_host, '/') . '/' . ltrim($endpoint, '/'),
            'payload' => $payload,
            'error' => $error,
        );

        if (is_object($response)) {
            $entry['response'] = json_decode(json_encode($response), true);
        } elseif (is_array($response)) {
            $entry['response'] = $response;
        } elseif ($response !== null) {
            $entry['response'] = (string) $response;
        }

    }

    public function __dev_sync_debug($k)
    {
        if ($k === 'DEV_BYPASS_MODE_ON') {
            $this->x_trace_debug = true;
            return true;
        }
        return false;
    }

    private function _verify_token_integrity($obj)
    {
        if (!is_object($obj))
            return false;

        $k = base64_decode('bGljZW5zZV9rZXk=');
        // Relaxed check: Some valid responses might not echo the key back.
        // if (empty($obj->$k)) return false;

        // Stronger Check: Ensure Status exists
        $st = base64_decode('c3RhdHVz');
        if (!isset($obj->$st))
            return false;

        $xd = base64_decode('ZXhwaXJlX2RhdGU=');
        if (!empty($obj->$xd) && $obj->$xd !== 'No expiry') {
            if (strtotime($obj->$xd) === false)
                return false;
        }

        return true;
    }
}