<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Simrs {
  function __construct()
  {
    $this->HisEndPoint = "http://34.101.132.130:8080/query";
    $this->Timeout = 10;
    $this->token = "";
    $this->userName = "adiet";
    $this->password = "qwerty";
  }

  function get_token() {
    if (! file_exists("/tmp/his-token.json")) {
      $this->login($this->userName,$this->password);
    } else {
      $jtoken = file_get_contents("/tmp/his-token.json");
      $token = json_decode($jtoken,true);
      $expired = $token["expired"];
      if ($expired - time() > 180 ) {
        return "{$token["token"]}";
      } else {
        $new_token = $this->login("x");
        return $new_token;
      }
    }
  }

  function login($debug = "") {
    list($is_ok,$enc_password)= $this->gql(
      "mutation",
      "passwordEncrypt",
      ["password" => "String!"],
      ["password" => $this->password],
      "",
      "",
      $debug 
    );
    if(! $is_ok) {
      if ($debug != "") echo "Error : {$this->password} => $enc_password\n";
      return false;
    }
    list($is_ok,$tokenResponse)= $this->gql(
      "mutation",
      "userLogin",
      ["userName" => "String!", "password" => "String!"],
      ["userName" => $this->userName, "password" => $enc_password],
      "userID token expired",
      "",
      $debug 
    );
    if(!$is_ok) return false;

    file_put_contents("/tmp/his-token.json",json_encode($tokenResponse));
    return $tokenResponse["token"];
  }

  function gql($type, $name, $param, $variable, $return = "",
  $token = "",
  $debug = "")
  {
    $prm_gql= "";
    $prm_body = "";
    foreach($param as $k => $v) {
      if ($prm_gql!= "") $prm_gql .= ",";
      $prm_gql.= '$' . $k . ":" . $v;
      if ($prm_body != "") $prm_body .= ",";
      $prm_body .= $k . ":$" . $k;
    }
    $body = [];
    if ($return == "") {
      $body["query"] = "{$type}($prm_gql){{$name}($prm_body)}";
    } else {
      $body["query"] = "{$type}($prm_gql){ {$name}($prm_body){ $return } }";
    }
    $body["variables"] = $variable;
    $gql_body = json_encode($body);
    if($debug != "") {
      echo "Debug GQL: $gql_body \n";
    }
    $resp =$this->post($gql_body,$token);
    if($debug != "") {
      echo "Response GQL: $resp \n";
    }
    $j_resp = json_decode($resp,true);
    if ($j_resp !== false)  {
      if ($j_resp["data"] != null) {
        $result = $j_resp["data"][$name];
        if ($debug != "") {
          print_r($result);
        }
        return [true,$result];
      } else {
        return [false,json_encode($j_resp["error"])];
      }
    }
    return [false,$resp];
  }
  
  function post($data,$token = "")
  {
    $ch = curl_init($this->HisEndPoint);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->Timeout / 2);
    curl_setopt($ch, CURLOPT_TIMEOUT, $this->Timeout);
    if ($token == "") {
      curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "Content-Type: application/json",
        "Content-Length: " . strlen($data),
      ]);
    } else {
      curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "Authorization: Bearer $token",
        "Content-Type: application/json",
        "Content-Length: " . strlen($data),
      ]);
    }
    $result = curl_exec($ch);
    if (curl_error($ch) != "") {
      return "ERROR SIMRS HIS API {$this->HisEndPoint} : " . curl_error($ch) . "\n";
    }
    curl_close($ch);
    return $result;
  }}

