<?php
defined("BASEPATH") or exit("No direct script access allowed");
class Satusehat
{
   //var $xbase_url = "https://api-satusehat-dev.dto.kemkes.go.id/fhir-r4/v1"; 
  function __construct()
  {
    $CI = &get_instance();
    $this->db_onedev = $CI->load->database("default", true);
    
  }

  function clean_mysqli_connection( $dbc )
{
    while( mysqli_more_results($dbc) )
    {
        if(mysqli_next_result($dbc))
        {
            $result = mysqli_use_result($dbc);
            
            if( get_class($result) == 'mysqli_stmt' )
            {
                mysqli_stmt_free_result($result);
            }
            else
            {
                unset($result);
            }
        }
    }
}

/*function get_token(){
    $sql = "SELECT COUNT(*) as xcount, tokenValue
            FROM one_health.token 
            WHERE tokenIsActive = 'Y' AND NOW() < tokenExpired AND tokenValue IS NOT NULL
            ";
    $qry = $this->db_onedev->query($sql);
    if (!$qry) {
        echo "select token error";
        exit;
    }

    $data_token = $qry->row_array();
    //print_r($data_token);
    if($data_token['xcount'] > 0){
        return $data_token['tokenValue'];
    }else{
        return $this->putx_token();
    }


}*/

function get_new_token(){
 

    $curl = curl_init();

    curl_setopt_array($curl, array(
    CURLOPT_URL => 'https://api-satusehat-dev.dto.kemkes.go.id/oauth2/v1/accesstoken?grant_type=client_credentials',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POSTFIELDS => 'client_id=6PukKqO0RQqu0cKBOC8EKGcXQySfPR4aVkiVmuTgkx5xvva4&client_secret=89ZqsmY3z5W7rVscHTp9gJoAWWiAZG4A2unS3maTw3DxBFxTdaRsSeTUbD8mRN3p',
    ));

    $response = curl_exec($curl);

    curl_close($curl);
    echo $response;

}

function put_token(){
    $auth_url = "https://api-satusehat-dev.dto.kemkes.go.id/oauth2/v1"; 
    //API URL
    $url = $auth_url."/accesstoken?grant_type=client_credentials";
    //echo $url;

    $data = [
        "client_id" => "6PukKqO0RQqu0cKBOC8EKGcXQySfPR4aVkiVmuTgkx5xvva4",
        "client_secret" => "89ZqsmY3z5W7rVscHTp9gJoAWWiAZG4A2unS3maTw3DxBFxTdaRsSeTUbD8mRN3p"
    ];
                
            
    $ch = curl_init($url);
    # Setup request to send json via POST.

    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch,CURLOPT_HTTPHEADER,
        array(
            'Content-Type: application/x-www-form-urlencoded'
        )
    );
    # Return response instead of printing.
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    # Send request.
    $result = curl_exec($ch);
    curl_close($ch);
    # Print response.
    print_r($result);
    //echo $token_rst->access_token;
    if($result){
        $token_rst = json_decode($result);
        
        $sql = "SELECT COUNT(*) as xcount, tokenID
                FROM one_health.token
                WHERE
                tokenIsActive = 'Y'
                ";
        $qry = $this->db_onedev->query($sql);
        if (!$qry) {
            echo "get count token error";
            exit;
        }

        $rst_count = $qry->row_array();

        if($rst_count['xcount'] > 0){
            $sql = "UPDATE one_health.token SET tokenValue = ?, tokenExpired = DATE_ADD(NOW(), INTERVAL 50 MINUTE)
                    WHERE tokenID = ?";
            $qry = $this->db_onedev->query($sql, [$token_rst->access_token,$rst_count['tokenID']]);
            if (!$qry) {
                $this->sys_error_db("refresh token error", $this->db_onedev->last_query());
                exit;
            }
        }else{
            $sql = "UPDATE one_health.token SET tokenIsActive = 'N' WHERE tokenIsActive = 'Y'";
            $qry = $this->db_onedev->query($sql);
            if (!$qry) {
                echo "nonactive token error";
                exit;
            }
    
            $sql = "INSERT INTO one_health.token(tokenValue,tokenExpired) VALUES(?,DATE_ADD(NOW(), INTERVAL 50 MINUTE))";
            $qry = $this->db_onedev->query($sql, [$token_rst->access_token]);
            if (!$qry) {
                echo "insert token error";
                exit;
            }
        }
    
        $sql = "SELECT tokenValue
                FROM one_health.token
                WHERE
                tokenIsActive = 'Y' LIMIT 1
                ";
        $qry = $this->db_onedev->query($sql);
        if (!$qry) {
            echo "get token error";
            exit;
        }
    
        return $qry->row()->tokenValue;
    }
   
    
}

/*function search_practicioner_by_nik($nik){
    $sql = "SELECT tokenValue
            FROM one_health.token
            WHERE
            tokenIsActive = 'Y' LIMIT 1
            ";
    $qry = $this->db_onedev->query($sql);
    if (!$qry) {
        echo "get token error";
        exit;
    }

    $token = $qry->row()->tokenValue;

    $authorization = "Authorization: Bearer ".$token;
    //API URL
    $url = $this->xbase_url."/Practitioner?identifier=https://fhir.kemkes.go.id/id/nik|".$nik;
    //echo $url;
        
            
    $ch = curl_init($url);
    # Setup request to send json via POST.
    //$payload = json_encode($data);

    //curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization ));
    # Return response instead of printing.
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    # Send request.
    $result = curl_exec($ch);
    curl_close($ch);
    # Print response.
    $data_rst = json_decode($result);
    print_r($result);

    return $data_rst;
}*/

function gen_uuid() {
    return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
        // 32 bits for "time_low"
        mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),

        // 16 bits for "time_mid"
        mt_rand( 0, 0xffff ),

        // 16 bits for "time_hi_and_version",
        // four most significant bits holds version number 4
        mt_rand( 0, 0x0fff ) | 0x4000,

        // 16 bits, 8 bits for "clk_seq_hi_res",
        // 8 bits for "clk_seq_low",
        // two most significant bits holds zero and one for variant DCE1.1
        mt_rand( 0, 0x3fff ) | 0x8000,

        // 48 bits for "node"
        mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
    );
}

protected function objToArray($obj)
    {
        // Not an object or array
        if (!is_object($obj) && !is_array($obj)) {
            return $obj;
        }

        // Parse array
        foreach ($obj as $key => $value) {
            $arr[$key] = $this->objToArray($value);
        }

        // Return parsed array
        return $arr;
    }
}


