<?php
namespace App\Libraries;

use CodeIgniter\HTTP\CURLRequest;

class NemoSoftsAPI{
    
    private const PRODUCT_ID = '52621164';
    private const API_URL = 'https://api.nemosofts.com/token/MITB3PVT6ZRLUA3GBJCU5S78S/v1/api.php';

    private function getAPIRequest(array $data){
        $client = \Config\Services::curlrequest();
        $response = $client->post(self::API_URL, [
            'form_params' => $data,
            'timeout' => 30,
            'connect_timeout' => 30,
        ]);
        return json_decode($response->getBody(), true);
    }

    public function getLatestVersion(){
        return $this->getAPIRequest([
            'method_name' => 'latest_version',
            'item_id' => self::PRODUCT_ID
        ]);
    }

    public function checkUpdate(){
        return $this->getAPIRequest([
            'item_id' => self::PRODUCT_ID
        ]);
    }

    public function verifyEnvatoPurchaseCode(string $license){
        return $this->getAPIRequest([
            'method_name' => 'envato_purchase_code',
            'item_id' => self::PRODUCT_ID,
            'license_code' => $license
        ]);
    }

    public function verifyLicenseAndroid(string $license, string $api_key, string $package_name){
        return $this->getAPIRequest([
            'method_name' => 'android_app',
            'envato_purchase_code' => $license,
            'api_key' => $api_key,
            'buyer_admin_url' => $this->getBaseUrlPanel(),
            'package_name' => $package_name
        ]);
    }

    public function deactivateLicense(string $deactivate_password){
        return $this->getAPIRequest([
            'method_name' => 'deactivate_license',
            'deactivate_password' => $deactivate_password
        ]);
    }

    public function activateLicense(string $license, string $client, bool $create_lic = true){
        return $this->getAPIRequest([
            'method_name' => 'activate_license',
            'item_id' => self::PRODUCT_ID,
            'license_code' => $license,
            'client_name' => $client,
            'base_url' => $this->getBaseUrlPanel()
        ]);
    }

    public function getIpFromThirdParty(){
        $client = \Config\Services::curlrequest();
        $response = $client->get('http://ipecho.net/plain', [
            'timeout' => 10,
            'connect_timeout' => 10,
        ]);
        return $response->getBody();
    }

    private function getBaseUrlPanel(){
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
        $host = $_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'] ?? 'localhost';
        $dir = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/');
        return htmlspecialchars("{$protocol}://{$host}{$dir}/", ENT_QUOTES);
    }
}
