<?php
defined("BASEPATH") or exit("No direct script access allowed");
class NatPatientLib
{

  //dev
  var $NAT_PATIENT_API = "http://10.9.8.249/one-api/nat_patient/r_api/";
  //prod
  //var $NAT_PATIENT_API = "http://192.168.50.250/one-api/nat_patient/r_api/";
  function __construct()
  {
    $CI = &get_instance();
    $this->db = $CI->load->database("default", true);
  }

  //remote => status : Y|N Y confirm N, not confirm.
  /*
    create table m_patient_nat_validation(
      M_PatientNatValidationID int not null auto_increment primary key,
      M_PatientNatValidationM_PatientID int, 
      M_PatientNatValidationM_UserID int,
      M_PatientNatValidationM_UserUsername varchar(100),
      M_PatientNatValidationIsActive char(1) default 'Y', 
      M_PatientNatValidationCreated datetime default current_timestamp(),
      M_PatientNatValidationLastUpdated datetime default current_timestamp() on update current_timestamp(),
      key(M_PatientNatValidationM_PatientID),
      key(M_PatientNatValidationIsActive),
    );
    create table m_patient_nat_log (
      M_PatientNatLogID int not null auto_increment primary key,
      M_PatientNatLogDate datetime default current_timestamp(),
      M_PatientNatLogStatus enum('New','Retry','Sent'),
      M_PatientNatLogLastUpdated datetime default current_timestamp() on update current_timestamp(),
      M_PatientNatLogJson text, 
      key(M_PatientNatLogDate),
      key(M_PatientNatLogStatus)
    );
   */
  function save_nasional($userName,$patient) {
    $resp = $this->get_branch();
    if ($resp["status"] != "OK") {
      return $resp;
    }
    $param = ["M_BranchID" => $resp["branchID"],
      "M_BranchCode" => $resp["branchCode"],
      "Username" => $userName,
      "patient" => $patient ];
    $z_param = gzcompress(json_encode($param));
    $url = $this->NAT_PATIENT_API . "/update_from_local";
    $zresp = $this->post($url, $z_param);
    $jresp = gzuncompress($zresp);
    $resp = json_decode($jresp, true);
    if (!isset($resp["status"])) {
      $resp["status"] = "ERR";
      $resp["message"] = $zresp;
    }
    return $resp;
  }

  function confirm($localM_PatientID, $arr_remote, $userID, $userName)
  {
    $payload = [
      "userID" => $userID,
      "userName" => $userName,
      "lokalM_PatientID" => $localM_PatientID,
      "remote" => $arr_remote,
    ];
    $jsonPayload = json_encode($payload);
    $sql = "insert into m_patient_nat_log(M_PatientNatLogStatus,M_PatientNatLogJson)
          values('New',?)";
    $qry = $this->db->query($sql, [$jsonPayload]);
    if (!$qry) {
      return [
        "status" => "ERR",
        "message" => $this->db->error()["message"],
      ];
    }
    return ["status" => "OK"];
  }
  function check_connection()
  {
    $start = date("Y-m-d H:i:s");
    $url = $this->NAT_PATIENT_API . "/check_connection";
    $zresp = $this->post($url, ["dummy" => "load"]);
    $jresp = gzuncompress($zresp);
    $resp = json_decode($jresp, true);
    if (!isset($resp["status"])) {
      $resp["status"] = "ERR";
      $resp["message"] = $zresp;
    }
    $stop = date("Y-m-d H:i:s");
    $resp["start"] = $start;
    $resp["stop"] = $stop;
    return $resp;
  }
  function get_branch()
  {
    $sql =
      "select M_BranchID, M_BranchCode from m_branch where M_BranchIsActive = 'Y' and M_BranchIsDefault='Y'";
    $qry = $this->db->query($sql);
    if (!$qry) {
      return [
        "status" => "ERR",
        "message" =>
        $this->db->error()["message"] .
          "|\n" .
          $this->db->last_query(),
      ];
    }
    $rows = $qry->result_array();
    if (count($rows) == 0) {
      return ["status" => "ERR", "message" => "No Default Branch"];
    }
    return [
      "status" => "OK",
      "branchID" => $rows[0]["M_BranchID"],
      "branchCode" => $rows[0]["M_BranchCode"],
    ];
  }
  function search($query)
  {
    $start = date("Y-m-d H:i:s");
    $url = $this->NAT_PATIENT_API . "/search_bizone";
    $jparam = json_encode(["search" => $query]);
    $zresp = $this->post($url, $jparam);
    $jresp = gzuncompress($zresp);
    $resp = json_decode($jresp, true);
    if (!isset($resp["status"])) {
      $resp["status"] = "ERR";
      $resp["message"] = $zresp;
    }
    $stop = date("Y-m-d H:i:s");
    $resp["start"] = $start;
    $resp["stop"] = $stop;
    return $resp;
  }
  // param array ->
  function search_by_nik($param)
  {
    $start = date("Y-m-d H:i:s");
    $url = $this->NAT_PATIENT_API . "/search_by_nik";
    $resp = $this->get_branch();

    if ($resp["status"] != "OK") {
      return $resp;
    }
    $jparam = json_encode($param);
    $zresp = $this->post($url, $jparam);
    $jresp = gzuncompress($zresp);
    $resp = json_decode($jresp, true);
    if (!isset($resp["status"])) {
      $resp["status"] = "ERR";
      $resp["message"] = $zresp;
    }
    $stop = date("Y-m-d H:i:s");
    $resp["start"] = $start;
    $resp["stop"] = $stop;
    return $resp;
  }
  public function post($url, $data)
  {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
      "Content-Type: application/text",
      "Content-Length: " . strlen($data),
    ]);
    $result = curl_exec($ch);
    if (curl_error($ch) != "") {
      echo json_encode([
        "status" => "ERR",
        "message" => "Http Error : " . curl_error($ch),
      ]);
      curl_close($ch);
      exit();
    }
    curl_close($ch);
    return $result;
  }
}
