<?php
/* For Get Token */
class PHPClass
{

    function getToken()
    {
        $url = tokenRest;
        //$encPass  = 'password';
        $encPass  = $this->encryptPassword('password');
        $fields = array(
            'client_id' => 'publicclient',
            'client_secret' => '$edu#pub@21',
            'grant_type' => 'password',
            'username' => 'PUBLIC_PORTAL_USER',
            'portal_code' => 'PUBLIC_PORTAL',
            'code' => 'PUBLIC_PORTAL',
            'password' => $encPass,
        );

        $payload = http_build_query($fields);

        /*
            create the content-length header string - use `strlen` to get the length!
        */
        $contentlength = strlen($payload);

        $fields_string = "";

        //url-ify the data for the POST
        foreach ($fields as $key => $value) {
            $fields_string .= $key . '=' . $value . '&';
        }
        rtrim($fields_string, '&');

        //open connection
        $ch = curl_init();

        //set the url, number of POST vars, POST data
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, $contentlength);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Accept: application/json'
          )
        );
        //execute post
        $result = curl_exec($ch);
        // if (curl_errno($ch)) {
        //  echo   $error_msg = curl_error($ch);exit;
        // }
        curl_close($ch);
        return $result;
    }

    public function encryptPassword($plaintext)
    {
        include_once(__DIR__.'/../phpseclib/Crypt/RSA.php');

        // use phpseclib\Crypt\RSA;

        $public_key = PUBLIC_KEY;
        $key = "-----BEGIN PUBLIC KEY-----\n" . wordwrap($public_key, 64, "\n", true) . "\n-----END PUBLIC KEY-----";

        $rsa = new Crypt_RSA();
        $rsa->loadKey($public_key); // public key

        $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
        $ciphertext = $rsa->encrypt($plaintext);

        //print_r($ciphertext);

        $data = base64_encode($ciphertext);
        return $data;
    }

    function secMe($options)
    {
        $nonce = "";
        if ($options['public_key'] != '' || $options['public_key'] != NULL)
        {
            $tkn = $options['access_token'];
            $tknHash = hash('sha256', $tkn);
            $tknPramHash32 = (strlen($tknHash) > 16) ? substr($tknHash, 0, 16) : $tknHash;

            $timeInMillSec = round(microtime(true) * 1e6);
            $timeHash = hash('sha256', $timeInMillSec);
            $nanoPramHash32 = (strlen($timeHash) > 16) ? substr($timeHash, 0, 16) : $timeHash;

            $urlParams = "BLANK";
            if ($options && $options['params'])
            {
                $options['params'] = str_replace('%20', ' ', $options['params']);
                $options['params'] = str_replace('%2C', ',', $options['params']);
                $urlParams = $this->sumAscVal($options['params']);
            }
            // echo $urlParams.'===GET';
            $urlParamHash = hash('sha256', $urlParams);
            $urlPramHash32 = (strlen($urlParamHash) > 16) ? substr($urlParamHash, 0, 16) : $urlParamHash;

            $jsonData = $options['jsonData'];

            $bodyJsonObj = [];
            if ($jsonData)
            {
                $bodyJsonObj = is_string($jsonData) ? json_decode($jsonData, true) : $jsonData;
            }
            $bodyParams = "BLANK";
            if (count($bodyJsonObj) > 0)
            {
                $bodyParams = json_encode($bodyJsonObj);
                $bodyParams = $this->sumAscVal($bodyParams);
            }
            $bodyParamHash = hash('sha256', $bodyParams);
            $bodyParamHash32 = (strlen($bodyParamHash) > 16) ? substr($bodyParamHash, 0, 16) : $bodyParamHash;
            $finalHashString = $tknPramHash32 . $nanoPramHash32 . $urlPramHash32 . $bodyParamHash32;
            $nonce_key = $options['public_key'];
            $nonce = $this->encrypt($finalHashString, $nonce_key);
            // echo $nonce;
            return $nonce;
        }
        else
        {
            return $nonce;
        }
    }
    function sumAscVal($jsonString)
    {
        $sum = 0;
        for ($i = 0; $i < strlen($jsonString); $i++) {
            $sum += ord($jsonString[$i]);
        }
        return $sum;
    }

    function encrypt($encryptText, $publicKey)
    {
        include_once(__DIR__.'/../phpseclib/Crypt/RSA.php');
        $rsa = new Crypt_RSA();
        $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
        $rsa->loadKey($publicKey);


        $ciphertext = $rsa->encrypt($encryptText);

        return base64_encode($ciphertext);
    }

    function decrypt($encryptedText, $privateKey)
    {
        include_once(__DIR__.'/../phpseclib/Crypt/RSA.php');
        $rsa = new Crypt_RSA();
        $rsa->loadKey($privateKey);


        $ciphertext = base64_decode($encryptedText);


        $decryptedText = $rsa->decrypt($ciphertext);


        return $decryptedText;
    }
}
