sys_input["data"]; $ids = array(); foreach($prm as $p) { $status = $p["status"]; $message_id = $p["message_id"]; if ($status == "sent") { $sql = "update tx_whatsappdetail set Tx_WhatsappDetailSend = now(), Tx_WhatsappDetailIsSend = 'Y' where Tx_WhatsappDetailUuid = ?"; $this->db->query($sql,array($message_id)); if ($this->db->affected_rows() > 0 ) { $ids[] = $p["id"]; } } else if($status == "received" ) { $sql = "update tx_whatsappdetail set Tx_WhatsappDetailReceive = now(), Tx_WhatsappDetailIsReceive= 'Y' where Tx_WhatsappDetailUuid = ?"; $this->db->query($sql,array($message_id)); if ($this->db->affected_rows() > 0 ) { $ids[] = $p["id"]; } } else if($status == "read") { $sql = "update tx_whatsappdetail set Tx_WhatsappDetailRead= now(), Tx_WhatsappDetailIsRead= 'Y' where Tx_WhatsappDetailUuid = ?"; $this->db->query($sql,array($message_id)); if ($this->db->affected_rows() > 0 ) { $ids[] = $p["id"]; } } } echo json_encode(array("status" => "OK" , "rows" => $ids)); } function create_wa_detail($txid, $text) { $param = json_decode($text,true); $sql = "insert into tx_whatsappdetail(Tx_WhatsappDetailTx_WhatsappID,Tx_WhatsappDetailUuid, Tx_WhatsappDetailCreated,Tx_WhatsappDetailMessage) values(?,?,now(),?)"; foreach($param as $p) { if(isset($p["data"]) && isset($p["data"]["uuid"]) ){ $uuid = $p["data"]["uuid"]; $message= $p["data"]["message"]; $this->db->query($sql, array($txid,$uuid,$message)); } } } function update_wa() { $prm = $this->sys_input; $headerID = $prm["headerID"]; $groupResultID = $prm["groupResultID"]; $deliveryID= $prm["deliveryID"]; $jsonText= $prm["jsonTxt"]; $note= $prm["note"]; $destination= $prm["destination"]; $sql = "insert into tx_whatsapp(Tx_WhatsappT_OrderHeaderID, Tx_WhatsappGroup_ResultID, Tx_WhatsappM_DeliveryID, Tx_WhatsappSentDate, Tx_WhatsappJson, Tx_WhatsappNote,Tx_WhatsappIsSent,Tx_WhatsappDestination) values (?, ?, ?, now(), ?, ?,'Y',?) "; $qry = $this->db->query($sql, array($headerID, $groupResultID, $deliveryID, $jsonText, $note,$destination)); if ($qry) { $txId = $this->db->insert_id(); $this->create_wa_detail($txId,$jsonText); $sql = "update t_orderdelivery set T_OrderDeliveryIsDone = 'Y' where T_OrderDeliveryT_OrderHeaderID =? and T_OrderDeliveryM_DeliveryID = ? "; $this->db->query($sql, array($headerID,$deliveryID)); $result = array("status" => "OK", "message" => ""); } else { $result = array("status" => "ERR", "message" => print_r($this->db->error(),true) ); } echo json_encode($result); } function get_pengantar_wa($deliverySource) { $sql = "select * from m_emailconfig where M_EmailConfigIsActive = 'Y' limit 0,1"; $query = $this->db->query($sql); $result = ""; $pengantar = array(); if ($query) { $rows = $query->result_array(); if(count($rows) > 0 ) { $r = $rows[0]; $pengantar["PATIENT"] = trim($r["M_EmailConfigResultFormatAPS"]); $pengantar["DOCTOR"] = trim($r["M_EmailConfigResultFormatAPD"]); $pengantar["COMPANY"] = trim($r["M_EmailConfigResultFormatRK"]); $pengantar["SERVICE"] = trim($r["M_EmailConfigHomeServiceFormat"]); $pengantar["PATIENT"] .= "\n" . trim($r["M_EmailConfigWaAPS"]); } if (isset($pengantar[$deliverySource])) { $result = $pengantar[$deliverySource]; } } return $result; } function get_laporan_wa($id) { $sql = "select distinct Group_ResultID, Group_ResultName, IF(T_EmailNonLabUrl IS NULL AND Group_ResultFlagNonLab = 'Y','N','Y') IsFormatChoosen 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'),'%')"; $query = $this->db->query($sql,array($id)); $result = array(); if ($query) { $rows = $query->result_array(); return $rows; } return $result; } function list_wa($date) { echo "
";
      $sql = "select group_concat(distinct T_OrderHeaderID) xids
         from 
         t_orderheader 
         join t_orderheaderaddon on T_OrderHeaderID = T_OrderHeaderAddOnT_OrderHeaderID and T_OrderHeaderAddOnIsActive = 'Y'
            -- and T_OrderHeaderAddOnReadyPrint <> 'N'
         join t_orderdelivery on T_OrderHeaderID = T_OrderDeliveryT_OrderHeaderID
	 and T_OrderHeaderIsActive = 'Y' 
	 and ( date(T_OrderHeaderDate) = ? 
       or date(T_OrderHeaderDate + interval 1 day ) = ? 
       or date(T_OrderDeliveryCreated) = ? 
       or date(T_OrderDeliveryCreated + interval 1 day ) = ? )
	 and T_OrderHeaderDate   > '2020-09-27'
         and T_OrderDeliveryIsActive = 'Y'
         and T_OrderDeliveryM_DeliveryTypeID in ( 4 )
         ";
      $ids = "";
      $query = $this->db->query($sql,array($date,$date,$date,$date));
      if ($query) {
         $rows = $query->result_array();
         if (count($rows) > 0 ) $ids = $rows[0]["xids"];
      }
      if ($ids == "") {
         $result = array( "status" => "OK", "rows" => array() );
         echo json_encode($result);
         exit;
      }
      // populate tx_whatsapp status 
      $sql = "select * from tx_whatsapp where Tx_WhatsappT_OrderHeaderID in ( $ids )
         and Tx_WhatsappIsActive = 'Y' and Tx_WhatsappIsSent = 'Y'";
      $query = $this->db->query($sql);
      $tx_whatsapp = array();
      if ($query) {
         $rows = $query->result_array();
         foreach($rows as $r) {
            $headerID = $r["Tx_WhatsappT_OrderHeaderID"];
            $groupResultID = $r["Tx_WhatsappGroup_ResultID"];
            $deliveryID  = $r["Tx_WhatsappM_DeliveryID"];
            $idx = "$headerID-$deliveryID-$groupResultID";
            $tx_whatsapp[$idx] = "Y";
         }
      } else {
         echo json_encode( array("status"=> "ERR" ,
            "message" =>  print_r($this->db->error(),true)
         ));
      }
      $sql = "select distinct T_OrderHeaderID, T_OrderHeaderLabNumber, T_OrderHeaderLabNumberExt, 
         M_DeliveryID, M_DeliveryName, M_DeliverySource, T_OrderDeliveryDestination,
         T_OrderHeaderDate, fn_get_patient_atribute(T_OrderHeaderM_PatientID) PatientName, 
         fn_global_doctor_name(T_OrderHeaderSenderM_DoctorID) DoctorName, 
         IF(M_MouIsBill = 'Y','Y',ifnull(Last_StatusPaymentIsLunas,'N')) IsLunas,
         date_format(T_OrderHeaderDate,'%d %M %Y') xdate,
         fn_global_doctor_name(T_OrderHeaderSenderM_DoctorID) DoctorName,
         M_DoctorHP,
         T_OrderHeaderAddOnReadyPrint, Result_ProcessToOfficeStatus
         from t_orderheader
         join t_orderheaderaddon on T_OrderHeaderID = T_OrderHeaderAddOnT_OrderHeaderID
         join m_doctor on T_OrderHeaderSenderM_DoctorID = M_DoctorID
         JOIN m_mou ON T_OrderHeaderM_MouID = M_MouID
         join t_orderdelivery on T_OrderHeaderID = T_OrderDeliveryT_OrderHeaderID and T_OrderDeliveryIsActive = 'Y'
         and T_OrderDeliveryM_DeliveryTypeID in ( 4 ) 
         join result_processtooffice on Result_ProcessToOfficeT_OrderHeaderID= T_OrderHeaderID
            and Result_ProcessToOfficeT_OrderDeliveryID = T_OrderDeliveryID  
            and Result_ProcessToOfficeStatus = 'S' and Result_ProcessToOfficeIsActive ='Y'
         join m_delivery on T_OrderDeliveryM_DeliveryID = M_DeliveryID
         left join last_statuspayment ON Last_StatusPaymentT_OrderHeaderID = T_OrderHeaderID AND Last_StatusPaymentIsActive = 'Y'
         where T_OrderHeaderID in ( $ids ) 
         order by T_OrderHeaderID 
         limit 0,2000";
      $query = $this->db->query($sql);
      if ($query) {
         $rows = $query->result_array();
         $list_result = array();
         $counter_list = 0;
         foreach($rows as $idx => $r) {
            $headerID = $r["T_OrderHeaderID"];
            $deliveryID = $r["M_DeliveryID"];

            $j_pasien = json_decode($r["PatientName"],true);
            $xname = $j_pasien["patient_fullname"];
            $x_reports = $this->get_pdf($r["T_OrderHeaderID"], $r["T_OrderHeaderLabNumber"], $xname); 
            $reports = array();
            foreach($x_reports as $xr) {
               $groupResultID = $xr["groupID"];
               $wa_idx = "$headerID-$deliveryID-$groupResultID";
               if (isset($tx_whatsapp[$wa_idx])) {
                  echo $r["T_OrderHeaderLabNumber"] . " groupID : $groupResultID , deliveryID : $deliveryID sudah ada\n";
                  continue;
               }
               if ($r["Result_ProcessToOfficeStatus"] != "S" ) continue;
               // lab must be kirim to adm 
               if ($groupResultID == 1 && $r["T_OrderHeaderAddOnReadyPrint"] == "N" ) {
                  echo $r["T_OrderHeaderLabNumber"] . " ReadyPrint : {$r['T_OrderHeaderAddOnReadyPrint']}\n";
                  continue;
               }
               $xr["Result_ProcessToOfficeStatus"] = $r["Result_ProcessToOfficeStatus"];
               $reports[] = $xr;
            }
            if ( count($reports) == 0 ) {
               unset($rows[$idx]);
               continue;
            }
            $rows[$idx]["reports"] = $reports;
            $pengantar  = $this->get_pengantar_wa($r["M_DeliverySource"]);
            $pengantar = str_replace("{DOKTER}",$r["DoctorName"],$pengantar);
            $pengantar = str_replace("{PASIEN}",$xname,$pengantar);
            $pengantar = str_replace("{TANGGAL}",$r["xdate"],$pengantar);
            $rows[$idx]["pengantar"] = $pengantar;
            $list_result[] = $rows[$idx];
            $counter_list++;
            if ($counter_list > 39 ) {
               break;
            }
         }
         foreach($list_result as $r) {
            echo $r["T_OrderHeaderLabNumber"] . " : " . $r["IsLunas"] ;
            echo "\n";
         }
         //$result = array( "status" => "OK", "rows" => $list_result);
         //echo json_encode($result);
         exit;
      } else {
         $result = array( "status" => "ERR", "rows" => array() , "message" => print_r($this->db->error(),true));
         echo json_encode($result);
      }
   }
   function get_pdf($id,$noreg,$pname) {
      $pname = str_replace(" ","-",$pname);
      $pname = str_replace(".","_",$pname);

      $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'),'%')";
      $query = $this->db->query($sql,array($id));
      if ($query) {
         $rows = $query->result_array();
         $ts = "&ts=" . date("Ymdhis");
         foreach($rows as $r) {
            $name = $r["Group_ResultName"];
            $gid = $r["Group_ResultID"];
            $temail = $r["temail"];
            $isnonlab = $r["Group_ResultFlagNonLab"];
            $emailnonlaburl = str_replace(" ", "", $r['EmailNonLabUrl']);
            if ( strpos($emailnonlaburl,"fisik") > 0) continue;
            $report = "";
            switch($gid) {
            case 1 :
               $report = "/birt/frameset?__report=report/one/lab/rpt_test_email.rptdesign&__format=pdf&username=admin&PID=" . $id . $ts;
               break;
            case 2 :
               $report = "/birt/frameset?__report=report/one/lab/rpt_hasil_papsmear_email.rptdesign&__format=pdf&username=admin&PID=" . $id . $ts;
               break;
            case 3 :
               $report = "/birt/frameset?__report=report/one/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/one/lab/rpt_hasil_lcprep_email.rptdesign&__format=pdf&username=admin&PID=" . $id . $ts;
               break;
            case 13 :
               $report = "/birt/frameset?__report=report/one/lab/rpt_test_mikro_email.rptdesign&__format=pdf&username=admin&PID=" . $id . $ts;
               break;
            case 14 :
               $report = "/birt/frameset?__report=report/one/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;
            }
            if ($report != "-") {
               $result[] = array(
                  "name" => $name,
                  "groupID" => $gid,
                  "fname" => $noreg . "-" . $pname . "-" . $name . ".pdf",
                  "url" => $report);   
            }else{
               $result[] = array(
                  "name" => $name . "*". $temail ."*",
                  "fname" => "File tidak ditemukan",
                  "url" => "");
            }

         }
      }
      return $result;
   }
   function download() {
      $noreg = $this->sys_input["noreg"];
      $sql = "select group_concat(distinct T_OrderHeaderID) xids
         from 
         t_orderheader 
         where T_OrderHeaderIsActive = 'Y' and (
            T_OrderHeaderLabNumber =? or T_OrderHeaderLabNumberExt = ? )";
      $ids = "";
      $query = $this->db->query($sql,array($noreg, $noreg));
      if ($query) {
         $rows = $query->result_array();
         if (count($rows) > 0 ) $ids = $rows[0]["xids"];
      }
      if ($ids == "") {
         echo json_encode( array("status" => "ERR" , "msg" => "Tidak ada hasil dengan Noreg $noreg"));
         exit;
      }
      $sql = "select * from m_emailconfig where M_EmailConfigIsActive = 'Y' limit 0,1";
      $query = $this->db->query($sql);
      $pengantar = array();
      if ($query) {
         $rows = $query->result_array();
         if(count($rows) > 0 ) {
            $r = $rows[0];
            $pengantar["PATIENT"] = trim($r["M_EmailConfigResultFormatAPS"]);
            $pengantar["DOCTOR"] = trim($r["M_EmailConfigResultFormatAPD"]);
            $pengantar["COMPANY"] = trim($r["M_EmailConfigResultFormatRK"]);
            $pengantar["SERVICE"] = trim($r["M_EmailConfigHomeServiceFormat"]);
         }
      } 
      $sql = "select distinct  T_OrderHeaderID, T_OrderHeaderLabNumber, T_OrderHeaderLabNumberExt, 
         T_OrderHeaderDate, fn_get_patient_atribute(T_OrderHeaderM_PatientID) PatientName, 
         fn_global_doctor_name(T_OrderHeaderSenderM_DoctorID) DoctorName,
         M_DeliverySource, T_OrderDeliveryDestination , date_format(T_OrderHeaderDate,'%d %M %Y') xdate,
         IF(Last_StatusPaymentIsLunas = 'N','Belum Lunas','Sudah Lunas') lunas 
         from t_orderheader
         join t_orderdelivery on T_OrderHeaderID = T_OrderDeliveryT_OrderHeaderID
         and T_OrderHeaderID in ( $ids )
         and T_OrderDeliveryIsActive = 'Y' and T_OrderDeliveryM_DeliveryTypeID in ( 4,5 )
         join m_delivery on T_OrderDeliveryM_DeliveryID = M_DeliveryID
         left join last_statuspayment ON Last_StatusPaymentT_OrderHeaderID = T_OrderHeaderID AND Last_StatusPaymentIsActive = 'Y'";
      $query = $this->db->query($sql,array($date));
      if ($query) {
         $rows = $query->result_array();
         $msg = "";
         if( count($rows) > 0 ) {
            $msg = "";
            $x_pengantar = "";
            $pre_word = "";
            foreach($rows as $idx => $r) {
               if ($idx == 0 ) {
                  $j_pasien = json_decode($r["PatientName"],true);
                  $xname = $j_pasien["patient_fullname"];
                  $reports = $this->get_pdf($r["T_OrderHeaderID"],$r["T_OrderHeaderLabNumberExt"],$xname);
                  $x_pengantar .= "|" . $r["M_DeliverySource"];
                  $xhp = $r["T_OrderDeliveryDestination"];
                  $msg .= "No Reg\t : " . $r["T_OrderHeaderLabNumberExt"] . "\n";
                  $msg .= "Pasien\t : " . $xname . "\n";
                  $msg .= "Doctor\t : " . $r["DoctorName"] . "\n";
                  $msg .= "*". $r["lunas"] ."*"."\n\n";
               }
               $msg .= "Permintaan " . $r["M_DeliverySource"] . " HP\t : " . $xhp . "\n";
               $pre_word .= "\n--- pengantar " . $r["M_DeliverySource"] . " ---\n" . $pengantar[$r["M_DeliverySource"]];
               $pre_word = str_replace("{DOKTER}",$r["DoctorName"],$pre_word);
               $pre_word = str_replace("{PASIEN}",$xname,$pre_word);
               $pre_word = str_replace("{TANGGAL}",$r["xdate"],$pre_word);
            }
            echo json_encode( array("status" => "OK" ,
               "reports" => $reports,"msg" => $msg, "pengantar" => $pre_word ));
         } else {
            echo json_encode( array("status" => "ERR" , "msg" => "Tidak ada hasil dengan Noreg $noreg"));
         }
      } else {
         echo json_encode( array("status" => "ERR" , "msg" => "Tidak ada hasil dengan Noreg $noreg"));
      }
   }
   function get_laporan($id) {
      /* $sql = "select distinct Group_ResultName
         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'
         and Group_ResultID in ( 1,2,3, 12, 13, 14)";
       */
      $sql = "select distinct Group_ResultName, 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'),'%')";
      $query = $this->db->query($sql,array($id));

      $result = "";
      if ($query) {
         $rows = $query->result_array();
         foreach($rows as $r) {
            if ($result != "" ) $result .= "  ";
            $result .= "[" . $r["Group_ResultName"] ."*".  $r["temail"] ."*". "]";
         }
      }
      return $result;
   }
   function list_json() {
      $date = $this->sys_input["date"];
      $sql = "select group_concat(distinct T_OrderHeaderID) xids
         from 
         t_orderheader 
         join t_orderdelivery on T_OrderHeaderID = T_OrderDeliveryT_OrderHeaderID
         and T_OrderHeaderIsActive = 'Y' and date(T_OrderHeaderDate) = ?
         and T_OrderDeliveryIsActive = 'Y'
         and T_OrderDeliveryM_DeliveryTypeID in ( 4,5 )";
      $ids = "";
      $query = $this->db->query($sql,array($date));
      if ($query) {
         $rows = $query->result_array();
         if (count($rows) > 0 ) $ids = $rows[0]["xids"];
      }
      if ($ids == "") {
         echo "Tidak ada permintaan dikirim Whatsapp / Telegram";
         exit;
      }
      $sql = "select T_OrderHeaderID, T_OrderHeaderLabNumber, T_OrderHeaderLabNumberExt, 
         T_OrderHeaderDate, fn_get_patient_atribute(T_OrderHeaderM_PatientID) PatientName, 
         fn_global_doctor_name(T_OrderHeaderSenderM_DoctorID) DoctorName, IF(Last_StatusPaymentIsLunas = 'N','Belum Lunas','Sudah Lunas') lunas
         from t_orderheader
         left join last_statuspayment ON Last_StatusPaymentT_OrderHeaderID = T_OrderHeaderID AND Last_StatusPaymentIsActive = 'Y'
         where T_OrderHeaderID in ( $ids )";
      $query = $this->db->query($sql,array($date));
      if ($query) {
         $rows = $query->result_array();
         echo json_encode( array( "status" => "OK" , "rows" => $rows ));
      } else {
         echo json_encode( array( "status" => "ERR" , "message" => print_r($this->db->error(),true)));
      }
   }
   function list() {
      $date = $this->sys_input["date"];
      $sql = "select group_concat(distinct T_OrderHeaderID) xids
         from 
         t_orderheader 
         join t_orderdelivery on T_OrderHeaderID = T_OrderDeliveryT_OrderHeaderID
         and T_OrderHeaderIsActive = 'Y' and date(T_OrderHeaderDate) = ?
         and T_OrderDeliveryIsActive = 'Y'
         and T_OrderDeliveryM_DeliveryTypeID in ( 4,5 )";
      $ids = "";
      $query = $this->db->query($sql,array($date));
      if ($query) {
         $rows = $query->result_array();
         if (count($rows) > 0 ) $ids = $rows[0]["xids"];
      }
      if ($ids == "") {
         echo "Tidak ada permintaan dikirim Whatsapp / Telegram";
         exit;
      }
      $sql = "select T_OrderHeaderID, T_OrderHeaderLabNumber, T_OrderHeaderLabNumberExt, 
         T_OrderHeaderDate, fn_get_patient_atribute(T_OrderHeaderM_PatientID) PatientName, 
         fn_global_doctor_name(T_OrderHeaderSenderM_DoctorID) DoctorName, IF(Last_StatusPaymentIsLunas = 'N','Belum Lunas','Sudah Lunas') lunas
         from t_orderheader
         left join last_statuspayment ON Last_StatusPaymentT_OrderHeaderID = T_OrderHeaderID AND Last_StatusPaymentIsActive = 'Y'
         where T_OrderHeaderID in ( $ids )";
      $query = $this->db->query($sql,array($date));
      if ($query) {
         $rows = $query->result_array();
         $msg = "";
         if(count($rows) > 0 ) {
            $msg .= "Total Permintaan  " . count($rows) . "\n\n";
         }
         $no = 1;
         foreach($rows as $r) {
            $s_no = sprintf("% 3d",$no);
            $j_pasien = json_decode($r["PatientName"],true);
            $xname = $j_pasien["patient_fullname"];
            $xhp = $j_pasien["M_PatientHP"];
            $msg .= "$s_no No Reg\t : " . $r["T_OrderHeaderLabNumberExt"] . "\n";
            $msg .= "    Pasien\t : " . $xname . "\n";
            $msg .= "    HP\t : " . $xhp . "\n";
            $msg .= "    Doctor\t : " . $r["DoctorName"] . "\n";
            $msg .= "    Laporan\t : " . $this->get_laporan($r["T_OrderHeaderID"]) . "\n";
            $msg .= "    " . "*". $r["lunas"] ."*"."\n\n";
            $no++;
         }
         if ($msg == "" ) {
            echo "Tidak ada permintaan dikirim Whatsapp / Telegram";
         } else {
            echo $msg;
         }
      } else {
         echo "Tidak ada permintaan dikirim Whatsapp / Telegram";
      }
   }
   function dl_report($prm, $name) {
      $url = "http://localhost/birt/frameset?" ;
      $qry  =  "";
      foreach($prm as $k => $v) {
         if ($qry != "" ) $qry .= "&";
         $qry .= $k . "=" . urlencode($v);
      } 
      $url .= $qry ;
      $data  = file_get_contents($url);
      header('Content-Type: application/octet-stream');
      header('Content-Disposition: attachment; filename=' . $name); 
      header('Content-Transfer-Encoding: binary');
      header('Connection: Keep-Alive');
      header('Expires: 0');
      header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
      header('Pragma: public');
      //header('Content-Length: ' . $size);
      echo $data;
   }
   function download_wa() {
      $noreg = $this->sys_input["noreg"];
      $sql = "select group_concat(distinct T_OrderHeaderID) xids
         from 
         t_orderheader 
         where T_OrderHeaderIsActive = 'Y' and (
            T_OrderHeaderLabNumber =? or T_OrderHeaderLabNumberExt = ? )";
      $ids = "";
      $query = $this->db->query($sql,array($noreg, $noreg));
      if ($query) {
         $rows = $query->result_array();
         if (count($rows) > 0 ) $ids = $rows[0]["xids"];
      }
      if ($ids == "") {
         echo json_encode( array("status" => "ERR" , "msg" => "Tidak ada hasil dengan Noreg $noreg"));
         exit;
      }
      $sql = "select * from m_emailconfig where M_EmailConfigIsActive = 'Y' limit 0,1";
      $query = $this->db->query($sql);
      $pengantar = array();
      if ($query) {
         $rows = $query->result_array();
         if(count($rows) > 0 ) {
            $r = $rows[0];
            $pengantar["PATIENT"] = trim($r["M_EmailConfigResultFormatAPS"]);
            $pengantar["DOCTOR"] = trim($r["M_EmailConfigResultFormatAPD"]);
            $pengantar["COMPANY"] = trim($r["M_EmailConfigResultFormatRK"]);
            $pengantar["SERVICE"] = trim($r["M_EmailConfigHomeServiceFormat"]);
         }
      } 
      $sql = "select distinct  T_OrderHeaderID, T_OrderHeaderLabNumber, T_OrderHeaderLabNumberExt, 
         T_OrderHeaderDate, fn_get_patient_atribute(T_OrderHeaderM_PatientID) PatientName, 
         fn_global_doctor_name(T_OrderHeaderSenderM_DoctorID) DoctorName,
         M_DeliverySource, T_OrderDeliveryDestination , date_format(T_OrderHeaderDate,'%d %M %Y') xdate,
         IF(Last_StatusPaymentIsLunas = 'N','Belum Lunas','Sudah Lunas') lunas 
         from t_orderheader
         join t_orderdelivery on T_OrderHeaderID = T_OrderDeliveryT_OrderHeaderID
         and T_OrderHeaderID in ( $ids )
         and T_OrderDeliveryIsActive = 'Y' and T_OrderDeliveryM_DeliveryTypeID in ( 4,5 )
         join m_delivery on T_OrderDeliveryM_DeliveryID = M_DeliveryID
         left join last_statuspayment ON Last_StatusPaymentT_OrderHeaderID = T_OrderHeaderID AND Last_StatusPaymentIsActive = 'Y'";
      $query = $this->db->query($sql,array($date));
      if ($query) {
         $rows = $query->result_array();
         $msg = "";
         if( count($rows) > 0 ) {
            $msg = "";
            $x_pengantar = "";
            $pre_word = "";
            foreach($rows as $idx => $r) {
               if ($idx == 0 ) {
                  $j_pasien = json_decode($r["PatientName"],true);
                  $xname = $j_pasien["patient_fullname"];
                  $reports = $this->get_pdf($r["T_OrderHeaderID"],$r["T_OrderHeaderLabNumberExt"],$xname);
                  $x_pengantar .= "|" . $r["M_DeliverySource"];
                  $xhp = $r["T_OrderDeliveryDestination"];
                  $msg .= "No Reg\t : " . $r["T_OrderHeaderLabNumberExt"] . "\n";
                  $msg .= "Pasien\t : " . $xname . "\n";
                  $msg .= "Doctor\t : " . $r["DoctorName"] . "\n";
                  $msg .= "*". $r["lunas"] ."*"."\n\n";
               }
               $msg .= "Permintaan " . $r["M_DeliverySource"] . " HP\t : " . $xhp . "\n";
               $pre_word = $pengantar[$r["M_DeliverySource"]];
               $pre_word = str_replace("{DOKTER}",$r["DoctorName"],$pre_word);
               $pre_word = str_replace("{PASIEN}",$xname,$pre_word);
               $pre_word = str_replace("{TANGGAL}",$r["xdate"],$pre_word);
            }
            echo json_encode( array("status" => "OK" ,
               "reports" => $reports,"hp" => $xhp, "pengantar" => $pre_word ));
         } else {
            echo json_encode( array("status" => "ERR" , "msg" => "Tidak ada hasil dengan Noreg $noreg"));
         }
      } else {
         echo json_encode( array("status" => "ERR" , "msg" => "Tidak ada hasil dengan Noreg $noreg"));
      }
   }
}