debug = false; $this->ONLINE_USER_ID = 1500; $this->SENDER_DOCTOR_ID = 0; $this->SENDER_ADDRESS_ID = 0; $this->PJ_DOCTOR_ID = 0; $this->KASIR_ONLINE_USER = 1500; $this->url = "https://sasmobile.aplikasi.web.id/one_api_coba/tools/regonline/r_download/"; } public function now() { return Date("Y-m-d H:i:s"); } public function get_branch_default() { $sql = "select * from m_branch where M_BranchIsDefault = 'Y' and M_BranchIsActive = 'Y'"; $qry = $this->db->query($sql); if (!$qry) { echo "{$this->now()} ERR : {$this->db->error()["message"]}\n"; exit(); } $rows = $qry->result_array(); if (count($rows) == 0) { echo "{$this->now()} ERR Get Default Branch: {$this->db->error()["message"]}\n"; exit(); } $branchKelurahanID = $rows[0]["M_BranchM_KelurahanID"]; $this->SENDER_DOCTOR_ID = $rows[0]["M_BranchM_DoctorID"]; $this->SENDER_ADDRESS_ID = $rows[0]["M_BranchM_DoctorAddressID"]; $sql = "select * from m_doctorpj where M_DoctorPjIsActive = 'Y' and M_DoctorPjIsDefaultPJ='Y'"; $qry = $this->db->query($sql); if (!$qry) { echo "{$this->now()} ERR : {$this->db->error()["message"]}\n"; exit(); } $rows = $qry->result_array(); if (count($rows) == 0) { echo "{$this->now()} ERR Get Default PJ: {$this->db->error()["message"]}\n"; exit(); } $this->PJ_DOCTOR_ID = $rows[0]["M_DoctorPjM_DoctorID"]; return [$branchKelurahanID]; } public function get_promise_by_px($pxID, $headerDate) { $sql = "select date( case when M_ScheduleFlagAtTime = 'Y' then concat( date( ? + interval M_ScheduleMonth * 4 day + interval 7 * M_ScheduleWeek day + interval M_ScheduleDay day) , ' ', M_ScheduleAtTime , ':00') else ? + interval M_ScheduleMonth * 4 day + interval 7 * M_ScheduleWeek day + interval M_ScheduleDay day + interval M_ScheduleHour Hour + interval M_ScheduleMinute minute end ) promiseDate, max( case when M_ScheduleFlagAtTime = 'Y' then concat( date( ? + interval M_ScheduleMonth * 4 day + interval 7 * M_ScheduleWeek day + interval M_ScheduleDay day) , ' ', M_ScheduleAtTime , ':00') else ? + interval M_ScheduleMonth * 4 day + interval 7 * M_ScheduleWeek day + interval M_ScheduleDay day + interval M_ScheduleHour Hour + interval M_ScheduleMinute minute end ) promiseDateTime from t_test join m_schedulegrouptest on T_TestNat_TestID = M_ScheduleGroupTestNat_TestID and M_ScheduleGroupTestIsActive = 'Y' join m_schedule on M_ScheduleM_ScheduleGroupID = M_ScheduleGroupTestM_ScheduleGroupID and M_ScheduleIsActive = 'Y' and M_ScheduleDayOfWeek = dayofweek(?) and date_format(?, '%H:%i') >= M_ScheduleStartHourMinute and date_format(?, '%H:%i') <= M_ScheduleEndHourMinute and T_TestID in ( $pxID ) group by promiseDate"; $qry = $this->db->query($sql, [ $headerDate, $headerDate, $headerDate, $headerDate, $headerDate, $headerDate, $headerDate, ]); if (!$qry) { //echo "{$this->now()} ERR Promise Reguler : {$this->db->error()['message']} | {$this->db->last_query()}\n"; return ["", ""]; } $rows = $qry->result_array(); if (count($rows) == 0) { //echo "{$this->now()} ERR Promise Reguler : Not Found \n"; return ["", ""]; } //ambil yg pertama $promiseDate = $rows[0]["promiseDate"]; $promiseDateTime = $rows[0]["promiseDateTime"]; return [$promiseDate, $promiseDateTime]; } public function status_order() { echo "{$this->now()} Start Order Create Status\n"; list($branchKelurahanID) = $this->get_branch_default(); $db_msg = ""; $this->db->trans_begin(); //1. Get Branch $sql = "select M_BranchName, M_BranchAddress from m_branch where M_BranchIsActive = 'Y' and M_BranchIsDefault = 'Y'"; $qry = $this->db->query($sql); if (!$qry) { echo "{$this->now()} ERR : {$this->db->error()["message"]}\n"; exit(); } $rows = $qry->result_array(); if (count($rows) == 0) { echo "{$this->now()} ERR Update Status - Branch : {$this->db->error()["message"]}\n"; exit(); } $branchName = $rows[0]["M_BranchName"]; $branchAddress = $rows[0]["M_BranchAddress"]; //1. Order Creation $sql = "select T_OnlineTxOrgID, T_OnlineOrderT_OrderID, T_OnlineOrderID, T_OrderHeaderLabNumberExt, T_OrderHeaderDate, T_OrderHeaderID from t_onlineorder join t_onlinetx on T_OnlineOrderT_OnlineTxID = T_OnlineTxID join t_orderheader on T_OrderHeaderID = T_OnlineOrderT_OrderHeaderID where T_OnlineOrderUploaded is null"; $qry = $this->db->query($sql); if (!$qry) { echo "{$this->now()} ERR : {$this->db->error()["message"]}\n"; exit(); } $rows = $qry->result_array(); $counter = 0; $status = []; $headerDate = date("Y-m-d H:i:s"); foreach ($rows as $r) { $msg = "Nomor Registrasi\t: " . $r["T_OrderHeaderLabNumberExt"] . "\n"; $msg .= "Lab. Sima $branchName\n$branchAddress\n"; $msg .= "Jadwal\t: " . $this->get_hari_id($r["T_OrderHeaderDate"]); $resp = $this->get_promise_by_px( $r["T_OrderHeaderID"], $r["T_OrderHeaderDate"] ); if ($resp["status"] != "OK") { $db_msg .= "|Err Promise Info : {$resp["message"]}"; } else { $msg .= "\n" . $resp["message"]; } $status[] = [ "T_TxMessageT_TransactionID" => $r["T_OnlineTxOrgID"], "T_TxMessageT_OrderID" => $r["T_OnlineOrderT_OrderID"], "T_TxMessageNote" => $msg, "T_TxMessageCode" => "ORDER", ]; $counter++; $headerDate = $r["T_OrderHeaderDate"]; $sql = "update t_onlineorder set T_OnlineOrderUploaded=? where T_OnlineOrderID = ?"; $qry = $this->db->query($sql, [$headerDate, $r["T_OnlineOrderID"]]); if (!$qry) { echo "{$this->now()} ERR Update Uploaded: {$this->db->error()["message"]}\n"; exit(); } } if (count($status) > 0) { //upload $url = $this->url . "status"; $param = ["status" => $status]; $z_param = gzdeflate(json_encode($param), 9); $resp = $this->post($url, $z_param); if ($resp["status"] == "OK") { $this->db->trans_commit(); echo "{$this->now()} Upload Status Creation : $counter\n"; } else { $this->db->trans_rollback(); echo "{$this->now()} ERR {$resp["message"]}\n"; } } else { echo "{$this->now()} Upload Status Creation : $counter | 0 Status \n"; $this->db->trans_commit(); } } public function status_validasi() { echo "{$this->now()} Start Validasi Status\n"; $this->db->trans_begin(); $sql = "select T_OrderHeaderID, T_OrderHeaderLabNumberExt, T_OnlineOrderID, T_OnlineOrderT_OrderID, T_OnlineTxOrgID, max(T_OrderDetailValDate) maxDate from t_onlineorder join t_onlinetx on T_OnlineOrderT_OnlineTxID = T_OnlineTxID and T_OnlineOrderIsActive = 'Y' and T_OnlineTxIsActive = 'Y' join t_orderheader on T_OnlineOrderT_OrderHeaderID = T_OrderHeaderID and T_OnlineOrderUploaded is not null join pb_upload on pbUploadCode = 'VALIDASI' join t_orderheaderaddon on T_OrderHeaderID = T_OrderHeaderAddOnT_OrderHeaderID and T_OrderHeaderAddOnIsActive = 'Y' and T_OrderHeaderAddOnValidationDone <> 'N' and T_OrderHeaderAddOnLastUpdated > pbUploadExecuted join t_orderdetail on T_OrderDetailT_OrderHeaderID = T_OrderHeaderID and T_OrderDetailIsActive = 'Y' and T_OrderDetailValidation = 'Y' group by T_OrderHeaderID"; $qry = $this->db->query($sql); if (!$qry) { echo "{$this->now()} ERR Status Validasi : {$this->db->error()["message"]}\n"; return; } $rows = $qry->result_array(); if (count($rows) == 0) { echo "{$this->now()} No Status Validation\n"; return; } $sql = "update pb_upload set pbUploadExecuted=now() where pbUploadCode = 'VALIDASI'"; $qry = $this->db->query($sql); if (!$qry) { echo "{$this->now()} ERR Update Uploaded: {$this->db->error()["message"]}\n"; return; } $status = []; $counter = 0; foreach ($rows as $r) { $headerID = $r["T_OrderHeaderID"]; $maxDate = $r["maxDate"]; $staffName = $this->get_validation_staff($headerID, $maxDate); $msg = "Nomor Registrasi : " . $r["T_OrderHeaderLabNumberExt"] . "\n"; $msg .= "Sudah di validasi oleh $staffName pada " . $this->get_hari_id($maxDate); $status[] = [ "T_TxMessageT_TransactionID" => $r["T_OnlineTxOrgID"], "T_TxMessageT_OrderID" => $r["T_OnlineOrderT_OrderID"], "T_TxMessageNote" => $msg, "T_TxMessageCode" => "VALIDATION", ]; $counter++; } if (count($status) > 0) { //upload $url = $this->url . "status"; $param = ["status" => $status]; $z_param = gzdeflate(json_encode($param), 9); $resp = $this->post($url, $z_param); if ($resp["status"] == "OK") { $this->db->trans_commit(); echo "{$this->now()} Upload Status Validation : $counter\n"; } else { $this->db->trans_rollback(); echo "{$this->now()} ERR {$resp["message"]}\n"; } } else { echo "{$this->now()} Upload Status Validasi : $counter\n"; $this->db->trans_commit(); } } public function get_validation_staff($headerID, $maxDate) { $sql = "select M_StaffName from t_orderdetail join m_user on T_OrderDetailT_OrderHeaderID = ? and T_OrderDetailIsActive = 'Y' and T_OrderDetailValidation = 'Y' and T_OrderDetailValDate = ? and T_OrderDetailValUserID = M_UserID join m_staff on M_UserM_StaffID = M_StaffID"; $qry = $this->db->query($sql, [$headerID, $maxDate]); if (!$qry) { echo "{$this->now()} ERR Status Validasi : {$this->db->error()["message"]}\n"; return ""; } $rows = $qry->result_array(); if (count($rows) == 0) { return ""; } return $rows[0]["M_StaffName"]; } public function status_report($debug = "N") { echo "{$this->now()} Start Report Status\n"; $this->db->trans_begin(); $sql = "select M_BranchCode from m_branch where M_BranchIsActive = 'Y' and M_BranchIsDefault = 'Y'"; $qry = $this->db->query($sql); if (!$qry) { echo "{$this->now()} ERR : {$this->db->error()["message"]}\n"; exit(); } $rows = $qry->result_array(); if (count($rows) == 0) { echo "{$this->now()} ERR Update Status - Branch : {$this->db->error()["message"]}\n"; exit(); } $branchCode = $rows[0]["M_BranchCode"]; $or_debug = ""; /* if ($debug == "Y") { $or_debug = " or date(Result_ProcessToOfficeLastUpdated) >= date(now()) "; } */ $sql = "select T_OrderHeaderLabNumber, T_OrderHeaderLabNumberExt, T_OrderHeaderID, T_OnlineOrderID, T_OnlineOrderT_OrderID, T_OnlineTxOrgID, max(Result_ProcessToOfficeLastUpdated) maxDate , max(T_OrderHeaderAddonReadyPrintDate) maxPrintDate, T_OrderHeaderM_PatientID from t_onlineorder join t_onlinetx on T_OnlineOrderT_OnlineTxID = T_OnlineTxID and T_OnlineOrderIsActive = 'Y' and T_OnlineTxIsActive = 'Y' and T_OnlineOrderUploaded is not null join t_orderheader on T_OnlineOrderT_OrderHeaderID = T_OrderHeaderID and date(T_OrderHeaderDate) >= '2021-12-13' join t_orderheaderaddon on T_OrderHeaderID = T_OrderHeaderAddOnT_OrderHeaderID join pb_upload on pbUploadCode = 'RESULT' join result_processtooffice on Result_ProcessToOfficeT_OrderHeaderID = T_OrderHeaderID and Result_ProcessToOfficeIsActive = 'Y' and ( Result_ProcessToOfficeLastUpdated > pbUploadExecuted -- or -- T_OrderHeaderAddonReadyPrintDate > pbUploadExecuted ) group by T_OrderHeaderID "; $qry = $this->db->query($sql); if (!$qry) { echo "{$this->now()} ERR Status Report : {$this->db->error()["message"]} | {$this->db->last_query()}\n"; exit(); } $rows = $qry->result_array(); $tot_row = count($rows); if ($tot_row == 0) { echo "{$this->now()} No Status Report : $tot_row \n"; $sql = "update pb_upload set pbUploadExecuted=now() where pbUploadCode='RESULT'"; $qry = $this->db->query($sql); $this->db->trans_commit(); return; } $s_patientID = "0"; foreach ($rows as $r) { $s_patientID .= "," . $r["T_OrderHeaderM_PatientID"]; } //get patient $sql = " select M_PatientName, M_PatientDOB, M_PatientNoreg, M_PatientM_SexID, M_PatientJob, M_PatientM_IdTypeID, M_PatientIDNumber, T_OnlineOrderT_OrderID from m_patient join t_onlineorder on M_PatientID in ($s_patientID) and T_OnlineOrderM_PatientID = M_PatientID and T_OnlineOrderIsActive = 'Y'"; $qry = $this->db->query($sql); if (!$qry) { echo "{$this->now()} ERR Report : Patient : {$this->db->error()["message"]} | {$this->db->last_query()}\n"; exit(); } $patients = $qry->result_array(); $status = []; $counter = 0; echo "{$this->now()} Upload Status Report : \n"; foreach ($rows as $r) { $headerID = $r["T_OrderHeaderID"]; $reports = $this->get_report($headerID); if ($reports == []) { echo "\t\t" . $r["T_OrderHeaderLabNumber"] . " No Report Found\n"; continue; } $arr_reports = []; $idx = 1; foreach ($reports as $xr) { if (trim($xr["url_rpt"]) == "-") { echo "\t {$r['T_OrderHeaderLabNumber']} : {$xr['Group_ResultName']} => Kosong \n"; continue; } $rpt_url = "http://localhost/" . $xr["url_rpt"]; $fname = $r["T_OnlineTxOrgID"] . "_" . $r["T_OnlineOrderT_OrderID"] . "_" . $xr["Group_ResultName"] . "_" . $r["T_OrderHeaderLabNumberExt"] . ".pdf"; $arr_reports[] = [ "name" => $xr["Group_ResultName"], "branchCode" => $branchCode, "fname" => $fname, "content" => base64_encode(file_get_contents($rpt_url)), ]; $idx++; echo "\t {$r['T_OrderHeaderLabNumber']} => $fname : $rpt_url\n"; } $msg = "Nomor Registrasi : " . $r["T_OrderHeaderLabNumberExt"] . "\n"; $msg .= "Sudah selesai."; $status[] = [ "T_TxMessageT_TransactionID" => $r["T_OnlineTxOrgID"], "T_TxMessageT_OrderID" => $r["T_OnlineOrderT_OrderID"], "T_TxMessageNote" => $msg, "reports" => $arr_reports, "T_TxMessageCode" => "RESULT", ]; $counter++; } if (count($status) > 0) { $url = $this->url . "status"; $param = ["status" => $status, "patients" => $patients]; $z_param = gzdeflate(json_encode($param), 9); $resp = $this->post($url, $z_param); if ($resp["status"] == "OK") { $this->db->trans_commit(); echo "{$this->now()} Upload Status Report : $counter\n{$resp["message"]}\n"; foreach ($status["report"] as $r) { echo "{$this->now()} => $fname \n"; } } else { $this->db->trans_rollback(); echo "{$this->now()} ERR {$resp["message"]}\n"; } } else { echo "{$this->now()} Upload Status Report : $counter\n"; $this->db->trans_commit(); } $this->status_report_hs(); //update pb_upload $sql = "update pb_upload set pbUploadExecuted=now() where pbUploadCode='RESULT'"; $qry = $this->db->query($sql); if (!$qry) { echo "{$this->now()} ERR Update Uploaded: {$this->db->error()["message"]}\n"; exit(); } } public function status_report_hs($debug = "N") { echo "{$this->now()} Start Report Status HS\n"; $sql = "select M_BranchCode from m_branch where M_BranchIsActive = 'Y' and M_BranchIsDefault = 'Y'"; $qry = $this->db->query($sql); if (!$qry) { echo "{$this->now()} ERR : {$this->db->error()["message"]}\n"; exit(); } $rows = $qry->result_array(); if (count($rows) == 0) { echo "{$this->now()} ERR Update Status - Branch : {$this->db->error()["message"]}\n"; exit(); } $branchCode = $rows[0]["M_BranchCode"]; $or_debug = ""; $sql = "select T_OrderHeaderLabNumber, T_OrderHeaderLabNumberExt, T_OrderHeaderID, T_OrderOldID T_OnlineOrderT_OrderID, T_OrderT_TransactionOldID T_OnlineTxOrgID, max(Result_ProcessToOfficeLastUpdated) maxDate , max(T_OrderHeaderAddonReadyPrintDate) maxPrintDate, T_OrderHeaderM_PatientID from one_hs.t_order join t_orderheader on T_OrderT_OrderHeaderID = T_OrderHeaderID and date(T_OrderHeaderDate) >= '2021-12-13' join t_orderheaderaddon on T_OrderHeaderID = T_OrderHeaderAddOnT_OrderHeaderID join pb_upload on pbUploadCode = 'RESULT' join result_processtooffice on Result_ProcessToOfficeT_OrderHeaderID = T_OrderHeaderID and Result_ProcessToOfficeIsActive = 'Y' and ( Result_ProcessToOfficeLastUpdated > pbUploadExecuted -- or -- T_OrderHeaderAddonReadyPrintDate > pbUploadExecuted ) group by T_OrderHeaderID "; $qry = $this->db->query($sql); if (!$qry) { echo "{$this->now()} ERR Status Report : {$this->db->error()["message"]} | {$this->db->last_query()}\n"; exit(); } $rows = $qry->result_array(); $tot_row = count($rows); if ($tot_row == 0) { echo "{$this->now()} No Status Report HS : $tot_row \n"; return; } $s_patientID = "0"; foreach ($rows as $r) { $s_patientID .= "," . $r["T_OrderHeaderM_PatientID"]; } //get patient $sql = " select M_PatientName, M_PatientDOB, M_PatientNoreg, M_PatientM_SexID, M_PatientJob, M_PatientM_IdTypeID, M_PatientIDNumber, T_OnlineOrderT_OrderID from m_patient join t_onlineorder on M_PatientID in ($s_patientID) and T_OnlineOrderM_PatientID = M_PatientID and T_OnlineOrderIsActive = 'Y'"; $qry = $this->db->query($sql); if (!$qry) { echo "{$this->now()} ERR Report : Patient HS : {$this->db->error()["message"]} | {$this->db->last_query()}\n"; exit(); } $patients = $qry->result_array(); $status = []; $counter = 0; echo "{$this->now()} Upload Status Report HS : \n"; foreach ($rows as $r) { $headerID = $r["T_OrderHeaderID"]; $reports = $this->get_report($headerID); if ($reports == []) { echo "\t\t" . $r["T_OrderHeaderLabNumber"] . " No Report Found\n"; continue; } $arr_reports = []; $idx = 1; foreach ($reports as $xr) { if (trim($xr["url_rpt"]) == "-") { echo "\t {$r['T_OrderHeaderLabNumber']} : {$xr['Group_ResultName']} => Kosong \n"; continue; } $rpt_url = "http://localhost/" . $xr["url_rpt"]; $fname = $r["T_OnlineTxOrgID"] . "_" . $r["T_OnlineOrderT_OrderID"] . "_" . $xr["Group_ResultName"] . "_" . $r["T_OrderHeaderLabNumberExt"] . ".pdf"; $arr_reports[] = [ "name" => $xr["Group_ResultName"], "branchCode" => $branchCode, "fname" => $fname, "content" => base64_encode(file_get_contents($rpt_url)), ]; $idx++; echo "\t {$r['T_OrderHeaderLabNumber']} => $fname : $rpt_url\n"; } $msg = "Nomor Registrasi : " . $r["T_OrderHeaderLabNumberExt"] . "\n"; $msg .= "Sudah selesai."; $status[] = [ "T_TxMessageT_TransactionID" => $r["T_OnlineTxOrgID"], "T_TxMessageT_OrderID" => $r["T_OnlineOrderT_OrderID"], "T_TxMessageNote" => $msg, "reports" => $arr_reports, "T_TxMessageCode" => "RESULT", ]; $counter++; } if (count($status) > 0) { $url = $this->url . "status"; $param = ["status" => $status, "patients" => $patients]; $z_param = gzdeflate(json_encode($param), 9); $resp = $this->post($url, $z_param); if ($resp["status"] == "OK") { echo "{$this->now()} Upload Status Report : $counter\n{$resp["message"]}\n"; foreach ($status["report"] as $r) { echo "{$this->now()} => $fname \n"; } } else { echo "{$this->now()} ERR {$resp["message"]}\n"; } } else { echo "{$this->now()} Upload Status Report : $counter\n"; } //update pb_upload } function force_report_hs($headerID) { echo "
{$this->now()} Start Force HS Report Status\n";
    $sql = "select 
        M_BranchCode
        from m_branch
        where M_BranchIsActive = 'Y' and M_BranchIsDefault = 'Y'";
    $qry = $this->db->query($sql);
    if (!$qry) {
      echo "{$this->now()} ERR : {$this->db->error()["message"]}\n";
      exit();
    }
    $rows = $qry->result_array();
    if (count($rows) == 0) {
      echo "{$this->now()} ERR Update Status - Branch : {$this->db->error()["message"]}\n";
      exit();
    }
    $branchCode = $rows[0]["M_BranchCode"];

    //patients

    $sql = "select T_OrderHeaderLabNumber,
        T_OrderHeaderLabNumberExt, T_OrderHeaderID,
        T_OrderOldID T_OnlineOrderT_OrderID, 
        T_OrderT_TransactionOldID T_OnlineTxOrgID, 
        max(Result_ProcessToOfficeLastUpdated) maxDate ,
        max(T_OrderHeaderAddonReadyPrintDate) maxPrintDate,
        T_OrderHeaderM_PatientID
        from one_hs.t_order
        join t_orderheader 
            on T_OrderT_OrderHeaderID = T_OrderHeaderID
    and date(T_OrderHeaderDate) >= '2021-12-13'
            and T_OrderHeaderID = ?
        join t_orderheaderaddon on T_OrderHeaderID = T_OrderHeaderAddOnT_OrderHeaderID 
        join pb_upload
            on pbUploadCode = 'RESULT'
        join result_processtooffice on 
            Result_ProcessToOfficeT_OrderHeaderID = T_OrderHeaderID
            and Result_ProcessToOfficeIsActive = 'Y'
        group by T_OrderHeaderID
        ";
    $qry = $this->db->query($sql, [$headerID]);
    if (!$qry) {
      echo "{$this->now()} ERR Status Report : {$this->db->error()["message"]} | {$this->db->last_query()}\n";
      exit();
    }
    $rows = $qry->result_array();
    if (count($rows) == 0) {
      echo "Report not ready";
      return;
    }
    $r = $rows[0];

    $reports = $this->get_report($headerID);
    if ($reports == []) {
      echo "\t\t" . $headerID . " No Report Found\n";
      return;
    }
    print_r($reports); exit;
    $arr_reports = [];
    $idx = 1;
    foreach ($reports as $xr) {
      if (trim($xr["url_rpt"]) == "-") {
        echo "\t {$xr['Group_ResultName']}  =>  Kosong \n";
        continue;
      }
      $rpt_url = "http://localhost/" . $xr["url_rpt"];
      $fname =
        $r["T_OnlineTxOrgID"] .
        "_" .
        $r["T_OnlineOrderT_OrderID"] .
        "_" .
        $xr["Group_ResultName"] .
        "_" .
        $r["T_OrderHeaderLabNumberExt"] .
        ".pdf";
      $arr_reports[] = [
        "name" => $xr["Group_ResultName"],
        "branchCode" => $branchCode,
        "fname" => $fname,
        "content" => base64_encode(file_get_contents($rpt_url)),
      ];
      $idx++;
      echo "\t {$r['T_OrderHeaderLabNumber']} =>  $fname : $rpt_url\n";
    }
    $msg =
      "Nomor Registrasi : " . $r["T_OrderHeaderLabNumberExt"] . "\n";
    $msg .= "Sudah selesai.";
    $status[] = [
      "T_TxMessageT_TransactionID" => $r["T_OnlineTxOrgID"],
      "T_TxMessageT_OrderID" => $r["T_OnlineOrderT_OrderID"],
      "T_TxMessageNote" => $msg,
      "reports" => $arr_reports,
      "T_TxMessageCode" => "RESULT",
    ];

    if (count($status) > 0) {
      //upload
      $url = $this->url . "status";
      $param = ["status" => $status];
      $z_param = gzdeflate(json_encode($param), 9);
      $resp = $this->post($url, $z_param);
      if ($resp["status"] == "OK") {
        echo "{$this->now()} Upload Status Creation \n";
      } else {
        echo "{$this->now()} ERR {$resp["message"]}\n";
      }
    } else {
      echo "{$this->now()} Upload Status Creation \n";
    }
  }

  function force_report($headerID)
  {
    echo "
{$this->now()} Start Force Report Status\n";
    $sql = "select 
        M_BranchCode
        from m_branch
        where M_BranchIsActive = 'Y' and M_BranchIsDefault = 'Y'";
    $qry = $this->db->query($sql);
    if (!$qry) {
      echo "{$this->now()} ERR : {$this->db->error()["message"]}\n";
      exit();
    }
    $rows = $qry->result_array();
    if (count($rows) == 0) {
      echo "{$this->now()} ERR Update Status - Branch : {$this->db->error()["message"]}\n";
      exit();
    }
    $branchCode = $rows[0]["M_BranchCode"];

    //patients

    $sql = "select T_OrderHeaderLabNumber,
        T_OrderHeaderLabNumberExt, T_OrderHeaderID,
        T_OnlineOrderID, T_OnlineOrderT_OrderID,
        T_OnlineTxOrgID, max(Result_ProcessToOfficeLastUpdated) maxDate ,
        max(T_OrderHeaderAddonReadyPrintDate) maxPrintDate,
        T_OrderHeaderM_PatientID
        from t_onlineorder
        join t_onlinetx on T_OnlineOrderT_OnlineTxID = T_OnlineTxID
            and T_OnlineOrderIsActive = 'Y'
            and T_OnlineTxIsActive = 'Y'
            and T_OnlineOrderUploaded is not null
        join t_orderheader 
            on T_OnlineOrderT_OrderHeaderID = T_OrderHeaderID
    and date(T_OrderHeaderDate) >= '2021-12-13'
            and T_OrderHeaderID = ?
        join t_orderheaderaddon on T_OrderHeaderID = T_OrderHeaderAddOnT_OrderHeaderID 
        join pb_upload
            on pbUploadCode = 'RESULT'
        join result_processtooffice on 
            Result_ProcessToOfficeT_OrderHeaderID = T_OrderHeaderID
            and Result_ProcessToOfficeIsActive = 'Y'
        group by T_OrderHeaderID
        ";
    $qry = $this->db->query($sql, [$headerID]);
    if (!$qry) {
      echo "{$this->now()} ERR Status Report : {$this->db->error()["message"]} | {$this->db->last_query()}\n";
      exit();
    }
    $rows = $qry->result_array();
    if (count($rows) == 0) {
      echo "Report not ready";
      return;
    }
    $r = $rows[0];

    $reports = $this->get_report($headerID);
    if ($reports == []) {
      echo "\t\t" . $headerID . " No Report Found\n";
      return;
    }
    $arr_reports = [];
    $idx = 1;
    foreach ($reports as $xr) {
      if (trim($xr["url_rpt"]) == "-") {
        echo "\t {$xr['Group_ResultName']}  =>  Kosong \n";
        continue;
      }
      $rpt_url = "http://localhost/" . $xr["url_rpt"];
      $fname =
        $r["T_OnlineTxOrgID"] .
        "_" .
        $r["T_OnlineOrderT_OrderID"] .
        "_" .
        $xr["Group_ResultName"] .
        "_" .
        $r["T_OrderHeaderLabNumberExt"] .
        ".pdf";
      $arr_reports[] = [
        "name" => $xr["Group_ResultName"],
        "branchCode" => $branchCode,
        "fname" => $fname,
        "content" => base64_encode(file_get_contents($rpt_url)),
      ];
      $idx++;
      echo "\t {$r['T_OrderHeaderLabNumber']} =>  $fname : $rpt_url\n";
    }
    $msg =
      "Nomor Registrasi : " . $r["T_OrderHeaderLabNumberExt"] . "\n";
    $msg .= "Sudah selesai.";
    $status[] = [
      "T_TxMessageT_TransactionID" => $r["T_OnlineTxOrgID"],
      "T_TxMessageT_OrderID" => $r["T_OnlineOrderT_OrderID"],
      "T_TxMessageNote" => $msg,
      "reports" => $arr_reports,
      "T_TxMessageCode" => "RESULT",
    ];

    if (count($status) > 0) {
      //upload
      $url = $this->url . "status";
      $param = ["status" => $status];
      $z_param = gzdeflate(json_encode($param), 9);
      $resp = $this->post($url, $z_param);
      if ($resp["status"] == "OK") {
        echo "{$this->now()} Upload Status Creation \n";
      } else {
        echo "{$this->now()} ERR {$resp["message"]}\n";
      }
    } else {
      echo "{$this->now()} Upload Status Creation \n";
    }
  }

  function get_report($headerID, $debug = "")
  {
    $sql = "select distinct 
        Group_ResultID,Group_ResultName,
        Group_ResultFlagNonLab,IFNULL(T_EmailNonLabUrl,'-') EmailNonLabUrl, 
        IF(T_EmailNonLabUrl IS NULL AND Group_ResultFlagNonLab = 'Y',' [Belum Pilih Format Hasil]','') temail
         from 
         t_orderdetail 
         join group_resultdetail 
            on Group_ResultDetailT_TestID = T_OrderDetailT_TestID
            and T_OrderDetailIsActive = 'Y' and Group_ResultDetailIsActive = 'Y'
            and T_OrderDetailT_OrderHeaderID = ?
         join group_result 
            on Group_ResultDetailGroup_ResultID = Group_ResultID
            and Group_ResultIsActive = 'Y'
         LEFT JOIN t_email_nonlab ON T_EmailNonLabT_OrderHeaderID = T_OrderDetailT_OrderHeaderID  AND
         T_EmailNonLabType LIKE CONCAT('%',REPLACE(Group_ResultName, 'Elektromedik', 'electromedis'),'%')
         group by Group_ResultID";
    $qry = $this->db->query($sql, [$headerID]);
    if (!$qry) {
      echo "{$this->now()} Error Ger Report : " .
        $this->db->error()["message"] .
        "|\n" .
        $this->db->last_query() .
        " \n";
      return [];
    }
    $rows = $qry->result_array();
    $ts = "&ts=" . date("Ymdhis");
    $id = $headerID;
    $result = [];

    foreach ($rows as $r) {
      $xname = $r["Group_ResultName"];
      $name = $this->escape_fname($xname);
      $gid = $r["Group_ResultID"];
      $temail = $r["temail"];
      $isnonlab = $r["Group_ResultFlagNonLab"];
      $emailnonlaburl = str_replace(" ", "", $r["EmailNonLabUrl"]);
      if (strpos($emailnonlaburl, "fisik") > 0) {
        echo "Hasil Fisik : $name - $xname $emailnonlaburl \n";
        continue;
      }
      $report = "";
      switch ($gid) {
        case 1:
          $report =
            "/birt/frameset?__report=report/onelab/lab/rpt_test_email.rptdesign&__format=pdf&username=admin&PID=" .
            $id .
            $ts;
          break;
        case 2:
          $report =
            "/birt/frameset?__report=report/onelab/lab/rpt_hasil_papsmear_email.rptdesign&__format=pdf&username=admin&PID=" .
            $id .
            $ts;
          break;
        case 3:
          $report =
            "/birt/frameset?__report=report/onelab/lab/rpt_hasil_fna_email.rptdesign&__format=pdf&username=admin&PID=" .
            $id .
            $ts;
          break;
        case 4:
          $report = $emailnonlaburl;
          break;
        case 5:
          $report = $emailnonlaburl;
          break;
        case 6:
          $report = $emailnonlaburl;
          break;
        case 7:
          $report = $emailnonlaburl;
          break;
        case 8:
          $report = $emailnonlaburl;
          break;
        case 9:
          $report = $emailnonlaburl;
          break;
        case 10:
          $report = $emailnonlaburl;
          break;
        case 11:
          $report = $emailnonlaburl;
          break;
        case 12:
          $report =
            "/birt/frameset?__report=report/onelab/lab/rpt_hasil_lcprep_email.rptdesign&__format=pdf&username=admin&PID=" .
            $id .
            $ts;
          break;
        case 13:
          $report =
            "/birt/frameset?__report=report/onelab/lab/rpt_test_mikro_email.rptdesign&__format=pdf&username=admin&PID=" .
            $id .
            $ts;
          break;
        case 14:
          $report =
            "/birt/frameset?__report=report/onelab/lab/rpt_hasil_cytologi_email.rptdesign&__format=pdf&username=admin&PID=" .
            $id .
            $ts;
          break;
        case 15:
          $report = $emailnonlaburl;
          break;
        case 16:
          $report = $emailnonlaburl;
          break;
        case 17:
          $report = $emailnonlaburl;
          break;
      }
      $result[] = ["Group_ResultName" => $xname, "url_rpt" => $report];
    }
    if ($debug != "") {
      echo "
";
      print_r($result);
    }
    return $result;
  }
  public function get_report_v1($headerID)
  {
    $sql = "SELECT 
        distinct
        Group_ResultName,
        CASE
        WHEN Group_ResultID    = 1 THEN 
            CONCAT('/birt/frameset?__report=report/onelab/lab/rpt_test_email.rptdesign&__format=pdf&username=','regonline','&PID=',T_OrderHeaderID,'&ts=',UNIX_TIMESTAMP())
        WHEN Group_ResultID    = 2 THEN 
            CONCAT('/birt/frameset?__report=report/onelab/lab/rpt_hasil_papsmear_email.rptdesign&__format=pdf&username=','regonline','&PID=',T_OrderHeaderID,'&ts=',UNIX_TIMESTAMP())
        WHEN Group_ResultID    = 3 THEN 
            CONCAT('/birt/frameset?__report=report/onelab/lab/rpt_hasil_fna_email.rptdesign&__format=pdf&username=','regonline','&PID=',T_OrderHeaderID,'&ts=',UNIX_TIMESTAMP())
        WHEN Group_ResultID    = 12 THEN 
            CONCAT('/birt/frameset?__report=report/onelab/lab/rpt_hasil_lcprep_email.rptdesign&__format=pdf&username=','regonline','&PID=',T_OrderHeaderID,'&ts=',UNIX_TIMESTAMP())
        WHEN Group_ResultID    = 13 THEN 
            CONCAT('/birt/frameset?__report=report/onelab/lab/rpt_test_mikro_email.rptdesign&__format=pdf&username=','regonline','&PID=',T_OrderHeaderID,'&ts=',UNIX_TIMESTAMP())
        WHEN Group_ResultID    = 14 THEN 
            CONCAT('/birt/frameset?__report=report/onelab/lab/rpt_hasil_cytologi_email.rptdesign&__format=pdf&username=','regonline','&PID=',T_OrderHeaderID,'&ts=',UNIX_TIMESTAMP())
        END as url_rpt
        FROM t_orderheader 
        JOIN t_orderdetail 
            ON T_OrderHeaderID = ?
            AND T_OrderDetailT_OrderHeaderID = T_OrderHeaderID 
            AND T_OrderDetailIsActive = 'Y'
        JOIN t_test 
            ON T_OrderDetailT_TestID = T_TestID
        JOIN group_resultdetail 
            ON Group_ResultDetailT_TestID = T_TestID
        JOIN group_result 
            ON Group_ResultDetailGroup_ResultID = Group_ResultID 
            AND Group_ResultFlagNonLab = 'N'
        ";
    $qry = $this->db->query($sql, [$headerID]);
    if (!$qry) {
      echo "{$this->now()} ERR Get Report : {$this->db->error()["message"]}\n";
      exit();
    }
    $rows = $qry->result_array();
    if (count($rows) == 0) {
      return [];
    }
    return $rows;
  }

  public function status_patient()
  {
    $sql = "select
        T_OnlineOrderT_OrderID,
        M_PatientID, 
        M_PatientName
        M_PatientDOB,
        M_PatientM_SexID,
        M_PatientJob,
        M_PatientM_IdTypeID,
        M_PatientIDNumber,
        M_PatientUserID
        from t_onlineorder
        join pb_upload
            on pbUploadCode = 'PATIENT'
            join m_patient on T_OnlineOrderM_PatientID = M_PatientID
            and M_PatientIsActive = 'Y'
            and M_PatientLastUpdated > pbUploadExecuted
        ";
    $qry = $this->db->query($sql);
    if (!$qry) {
      echo "{$this->now()} ERR Status Report : {$this->db->error()["message"]} | {$this->db->last_query()}\n";
      exit();
    }
    $rows = $qry->result_array();
    if (count($rows) == 0) {
      echo "{$this->now()} No Status Report\n";
      $sql = "update pb_upload set pbUploadExecuted=now()
            where pbUploadCode='RESULT'";
      $qry = $this->db->query($sql);
      $this->db->trans_commit();
      return;
    }
    //update pb_upload
    $sql = "update pb_upload set pbUploadExecuted=now()
        where pbUploadCode = 'PASIEN'";
    $qry = $this->db->query($sql);
    if (!$qry) {
      echo "{$this->now()} ERR Update Uploaded: {$this->db->error()["message"]}\n";
      exit();
    }

    $status = [];
    $counter = 0;
  }

  public function get_hari_id($orderDate)
  {
    $bulan = [
      1 => "Januari",
      "Februari",
      "Maret",
      "April",
      "Mei",
      "Juni",
      "Juli",
      "Agustus",
      "September",
      "Oktober",
      "November",
      "Desember",
    ];
    $tanggal = date("Y-m-d", strtotime($orderDate));
    $split = explode("-", $tanggal);
    $hari = $split[2] . " " . $bulan[(int) $split[1]] . " " . $split[0];
    $dow = date("l", strtotime($orderDate));
    switch ($dow) {
      case "Sunday":
        $dow = "Minggu";
        break;
      case "Monday":
        $dow = "Senin";
        break;
      case "Tuesday":
        $dow = "Selasa";
        break;
      case "Wednesday":
        $dow = "Rabu";
        break;
      case "Thursday":
        $dow = "Kamis";
        break;
      case "Friday":
        $dow = "Jumat";
        break;
      case "Saturday":
        $dow = "Sabtu";
        break;
    }
    $result = "";
    if ($dow != "") {
      $result .= $dow . ", ";
    }
    $result .= $hari . " jam " . date("H:i", strtotime($orderDate));
    return $result;
  }

  public function strip_unicode($inp)
  {
    $result = mb_convert_encoding($inp, "US-ASCII", "UTF-8");
    return $result;
  }

  public function index()
  {
    $this->status_order();
    sleep(5);
    $this->status_validasi();
    sleep(5);
    $this->status_report();
    sleep(5);
    $this->status_lunas();
  }
  function status_lunas()
  {
    echo "{$this->now()} Start Pelunasan Bayar di Tempat\n";
    $sql = "select pbUploadExecuted from pb_upload where pbUploadCode = 'LUNAS'";
    $qry = $this->db->query($sql);
    if (!$qry) {
      echo "{$this->now()} ERR : {$this->db->error()["message"]}\n";
      exit();
    }
    $rows = $qry->result_array();
    if (count($rows) == 0) {
      $sql = "insert into pb_upload(pbUploadCode,pbUploadExecuted) values('LUNAS',now())";
      $qry = $this->db->query($sql);
      if (!$qry) {
        echo "{$this->now()} ERR Init pb Upload Pelunasan bayar di tempat: {$this->db->error()["message"]}\n";
        exit();
      }
      $last_updated = "2021-11-01 00:00:01";
    } else {
      $last_updated = $rows[0]["pbUploadExecuted"];
    }
    echo "\t\tLast Updated : $last_updated\n";
    $sql = "select distinct T_OnlineTxOrgID, T_OnlineTxNumbering, T_OnlineTxBookingName 
            from t_onlinetx 
            join t_onlineorder on T_OnlineTxID = T_OnlineOrderT_OnlineTxID
            and T_OnlineTxIsLunas = 'Y'
            and T_OnlineTxLastUpdated > ? 
            join t_orderheader on T_OrderHeaderID = T_OnlineOrderT_OrderHeaderID 
            join f_payment on F_PaymentT_OrderHeaderID = T_OrderHeaderID 
            join f_payment_orderheader on F_PaymentID = F_Payment_OrderHeaderF_PaymentID
                and F_Payment_OrderHeaderIsLunas = 'Y'
            join f_paymentdetail on F_PaymentID = F_PaymentDetailF_PaymentID
                and F_PaymentDetailM_PaymentTypeID <> 1000
            ";
    $qry = $this->db->query($sql, [$last_updated]);
    if (!$qry) {
      echo "{$this->now()} ERR Get TxOnineID: {$this->db->error()["message"]}\n";
      exit();
    }
    $rows = $qry->result_array();
    if (count($rows) == 0) {
      echo "\t No Upload data\n";
      exit;
    }
    $url = $this->url . "status_lunas";
    $param = ["data" => $rows];
    $z_param = gzdeflate(json_encode($param), 9);
    $resp = $this->post($url, $z_param);
    if ($resp["status"] == "OK") {
      $counter = count($rows);
      $sql = "update pb_upload set pbUploadExecuted = now() where pbUploadCode = 'LUNAS'";
      $qry = $this->db->query($sql);
      if (!$qry) {
        echo "Error update pb_upload : " . $this->db->error()["message"] . "\n";
        return;
      } else {
        $this->db->trans_commit();
      }
      echo "{$this->now()} Upload Pelunasan bayar di tempat : $counter\n";
    } else {
      echo "{$this->now()} ERR Upload Pelunasan bayar di tempat : {$resp["message"]}\n";
    }
    $this->status_lunas_hs($last_updated);
  }

  function status_lunas_hs($last_updated = "")
  {
    if ($last_updated = "") {
      $last_updated = date("Y-m-d 00:00:00");
    }
    echo "{$this->now()} Start Pelunasan HS Bayar di Tempat\n";
    $sql = "select distinct 
      T_TransactionOldID T_OnlineTxOrgID, 
      T_TransactionNumbering T_OnlineTxNumbering, 
      '' T_OnlineTxBookingName 
            from one_hs.t_transaction
    where T_TransactionLastUpdated > ? 
    and T_TransactionTotalPaid = 0
    and T_TransactionOldID > 0
            ";
    $qry = $this->db->query($sql, [$last_updated]);
    if (!$qry) {
      echo "{$this->now()} ERR Get TxOnineID: {$this->db->error()["message"]}\n";
      exit();
    }
    $rows = $qry->result_array();
    $url = $this->url . "status_lunas";
    if (count($rows) == 0) {
      echo "\t No Upload data\n";
      exit;
    }
    $url = $this->url . "status_lunas";
    $param = ["data" => $rows];
    $z_param = gzdeflate(json_encode($param), 9);
    $resp = $this->post($url, $z_param);
    if ($resp["status"] == "OK") {
      $counter = count($rows);
      echo "{$this->now()} Upload Pelunasan HS bayar di tempat : $counter\n";
    } else {
      echo "{$this->now()} ERR Upload Pelunasan HS bayar di tempat : {$resp["message"]}\n";
    }
  }
  public function post($url, $data)
  {
    echo "{$this->now()} DEBUG : $url\n";
    $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, 5);
    curl_setopt($ch, CURLOPT_TIMEOUT, 120);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
      "Content-Type: application/json",
      "Content-Length: " . strlen($data),
    ]);
    $z_result = curl_exec($ch);
    if (curl_errno($ch) > 0) {
      return [
        "status" => "ERR",
        "message" => curl_error($ch),
      ];
    }
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if ($httpCode != 200) {
      return [
        "status" => "ERR",
        "message" => "Http Response : $httpCode | $z_result",
      ];
    }

    $result = gzinflate($z_result);
    $j_result = json_decode($result, true);
    if (!$j_result) {
      return [
        "status" => "ERR",
        "message" => "JSON invalid: $z_result",
      ];
    }
    return $j_result;
  }

  function escape_fname($xname)
  {
    $find = [" ", "&", '\r\n', '\n', "+", ","];
    $xname = str_replace($find, "-", $xname);

    //delete and replace rest of special chars
    $find = ["/[^a-zA-Z0-9\-<>]/", "/[\-]+/", "/<[^>]*>/"];
    $repl = ["", "-", ""];
    $xname = preg_replace($find, $repl, $xname);
    return $xname;
  }
}