<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Libhttprequest
{

    // SET SUPER GLOBAL
    var $CI = NULL;
    public function __construct()
    {
        $this->CI = &get_instance();
        $this->CI->load->model('data_menu');
    }

    public function wsbpjs($method, $endPoint, $params, $contentType)
    {
        // PRODUCTION
        $access = array(
            'consId' => "12770",
            'consSecret' => "5wP6C23921",
            'userKey' => 'cbec17b0d6dcae01d40435ed589c3e50',
            'urlBase' => 'https://apijkn.bpjs-kesehatan.go.id/antreanrs/',
        );

        echo $this->Hit($access, $method, $endPoint, $params, $contentType);
    }

    public function vclaim($method, $endPoint, $params, $contentType)
    {
        // PRODUCTION
        $access = array(
            'consId' => "12770",
            'consSecret' => "5wP6C23921",
            'userKey' => '7057f715c0b800bed2faed440b8d36df',
            'urlBase' => 'https://apijkn.bpjs-kesehatan.go.id/vclaim-rest/'
        );
        echo $this->Hit($access, $method, $endPoint, $params, $contentType);
    }
    

    public function Hit($access, $method, $endPoint, $params, $contentType)
    {
        $consId = $access['consId'];
        $consSecret = $access['consSecret'];
        $userKey = $access['userKey'];
        $urlBase = $access['urlBase'];

        //url dari db contain space / new line harus d replace dulu
        $url      = trim(preg_replace('/\s+/', ' ', $urlBase)) . $endPoint;

        // Computes the timestamp
        date_default_timezone_set('UTC');
        $tStamp = strval(time() - strtotime('1970-01-01 00:00:00'));
        // Computes the signature by hashing the salt with the secret key as the key
        $signature = hash_hmac('sha256', $consId . '&' . $tStamp, $consSecret, true);

        // base64 encode�
        $encodedSignature = base64_encode($signature);

        $params_string = json_encode($params);

        //print_r($params_string);exit();
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt(
            $ch,
            CURLOPT_HTTPHEADER,
            array(
                'Content-Type: ' . $contentType,
                'Content-Length: ' . strlen($params_string),
                'x-cons-id:' . $consId,
                'x-timestamp:' . $tStamp,
                'x-signature:' . $encodedSignature,
                'user_key:' . $userKey
            )
        );

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

        //execute post
        $request = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        if ($httpCode != 200) {
            http_response_code(400);
            return $request;
            exit();
        }

        $result = json_decode($request, true);

        $metadata = 'metadata';
        if (!isset($result[$metadata])) {
            $metadata = 'metaData';
        }

        //sukses
        if ($result[$metadata]['code'] == 1 || $result[$metadata]['code'] == 200) {
            try {

                //check request is not exist
                if (!isset($result['response'])) {
                    return $request;
                    exit();
                }

                $key = $consId . $consSecret . $tStamp;
                //ambil text descript aes cbc 256
                $message = $result['response'];
                //descript
                $decript = $this->stringDecrypt($key, $message);
                //decompress lz string hasil decript
                $decriptLazyString = $this->decompress($decript);
                //create response
                $response =   json_decode($decriptLazyString, true);
                $result = array(
                    'message' => 'OK',
                    'code' => 200
                );
                $list = array(
                    'list' => $response
                );
                $metadata = array($metadata => $result, 'response' => $list);
                return json_encode($metadata);
                exit();
            } catch (Exception $e) {

                if ($result[$metadata]['code'] == 200) {
                    return $request;
                    exit();
                }

                $result = array(
                    'message' => $e->getMessage(),
                    'code' => 500
                );
                $metadata = array($metadata => $result);
                return json_encode($metadata);
                exit();
            }
        }

        return $request;
        exit();
    }

    public function HitPostJson($params, $endPoint)
    {
        $url      = AUTHORIZATION::URL_BPJS_PURWA() . $endPoint;

        $params_string = json_encode($params);

        //print_r($url);
        //print_r($params_string);exit();
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt(
            $ch,
            CURLOPT_HTTPHEADER,
            array(
                'Content-Type: ' . 'application/json',
                'Content-Length: ' . strlen($params_string),
            )
        );
        
        //execute post
        $request = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        //echo  $url . $params_string. $request;exit();
        if ($httpCode != 200) {
            http_response_code(400);
            return $request;
        }

        return $request;
    }


    // function decrypt
    function stringDecrypt($key, $string)
    {

        $encrypt_method = 'AES-256-CBC';

        // hash
        $key_hash = hex2bin(hash('sha256', $key));

        // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
        $iv = substr(hex2bin(hash('sha256', $key)), 0, 16);

        $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key_hash, OPENSSL_RAW_DATA, $iv);

        return $output;
    }

    // function lzstring decompress 
    // download libraries lzstring : https://github.com/nullpunkt/lz-string-php
    function decompress($string)
    {

        return \LZCompressor\LZString::decompressFromEncodedURIComponent($string);
    }

    function GetJsonObject($obj)
    {
        return isset($obj) ? $obj : "";
    }
}
