<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Log;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use App\Logbook;
use App\User;
use App\Periksa;
use App\Pasien;
use App\Riwayat;
use App\Rekaplogbook;
use App\PeriksaTest;

use Fawno\PhpSerial\SerialDio;
use Fawno\PhpSerial\SerialConfig;
use DateTime;
use Carbon\Carbon;
use Aranyasen\HL7\Message;
use Aranyasen\HL7\Connection;
use Aranyasen\HL7\Segment;
use Aranyasen\HL7\Segments\MSH;
use Aranyasen\HL7\Segments\PV1;
use Aranyasen\HL7\Segments\OBR;
use Aranyasen\HL7\Segments\ORC;
use Aranyasen\HL7\Segments\PID;
use Aranyasen\HL7\Segments\OBX;
use Aranyasen\HL7\Segments\NTE;
use Aranyasen\HL7\Segments\EVN;
use Session;

class Controller extends BaseController
{
    use AuthorizesRequests, ValidatesRequests;
    protected function getStyledValue($value, $color, $strong = false) {
        return $strong ? "<strong><font color=\"$color\">$value</font></strong>" : "<font color=\"$color\">$value</font>";
    }
    protected function setStatusStyles($status, $nofoto, $noregister, $nama, $telpon, $jk, $usia, $urgensi, $reques, $ruangan, $daftar, $asalpasien) {
        $color 		= 'grey';
        $strong 	= false;
        $statusText = $status;
    
        if (empty($status)) {
            if (!empty($foto) || !empty($baca)) {
                $color 		= !empty($baca) ? 'green' : 'blue';
                $statusText = !empty($baca) ? 'Telah di Baca' : 'Telah di kirim ke worklist/modalitas';
            } else {
                $color 		= 'red';
                $statusText = 'NEW';
            }
        } else {
            $katapertama = explode(" ", $status)[0];
            switch ($katapertama) {
                case 'Telah':
                case 'Diperiksa':
                case 'Draft':
                case 'Expertise':
                    $color = 'blue';
                    $strong = false;
                    break;
                case 'Decliend':
                    $color = 'danger';
                    $strong = false;
                    break;
                case 'Selesai':
                    $color = 'success';
                    $strong = false;
                    break;
                case 'Arsip':
                    $color = 'primary';
                    $strong = false;
                    break;
                default:
                    $color = 'grey';
                    break;
            }
            if (in_array($katapertama, ['Diperiksa', 'Draft', 'Expertise'])) {
                $strong = true;
            }
        }
    
        return [
            'nofoto' 		=> $this->getStyledValue($nofoto, $color, $strong),
            'noregister' 	=> $this->getStyledValue($noregister, $color, $strong),
            'nama' 			=> $this->getStyledValue($nama, $color, $strong),
            'telpon' 		=> $this->getStyledValue($telpon, $color, $strong),
            'jk' 			=> $this->getStyledValue($jk, $color, $strong),
            'usia' 			=> $this->getStyledValue($usia, $color, $strong),
            'urgensi' 		=> $this->getStyledValue($urgensi, $color, $strong),
            'reques' 		=> $this->getStyledValue($reques, $color, $strong),
            'ruangan' 		=> $this->getStyledValue($ruangan, $color, $strong),
            'daftar' 		=> $this->getStyledValue($daftar, $color, $strong),
            'status' 		=> $this->getStyledValue($statusText, $color, $strong),
            'asalpasien' 	=> $this->getStyledValue($asalpasien, $color, $strong),
        ];
    }
    protected function getDataBasedOnMaster($master, $jenis, $mulai, $akhir, $valcari) {
        $data = match ($master) {
            'logbook'           => $this->getLogbookData($jenis, $mulai, $akhir, $valcari),
            'pengambilan'       => $this->getPengambilanData($jenis, $mulai, $akhir, $valcari),
            'verificationppds'  => $this->getPemeriksaanData($jenis, $mulai, $akhir, $valcari),
            default             => $this->getDefaultData($jenis, $master, $mulai, $akhir, $valcari),
        };
        return $data;
    }
    protected function getLogbookData($jenis, $mulai, $akhir, $valcari) {
        [$mulai, $akhir] = $this->prepareDateRange($mulai, $akhir);
        $query = Periksa::whereBetween('daftar', [$mulai, $akhir]);
        if ($jenis === 'junior') {
            return $query->where('ppdsjunior', $valcari)->orWhere('ppdsjunior2', $valcari);
        } elseif ($jenis === 'middle') {
            return $query->where('middleppds', $valcari)->orWhere('ppdsmiddle2', $valcari);
        } elseif ($jenis === 'senior') {
            return $query->where('ppdssenior', $valcari);
        }
        return $query;
    }
    protected function getPengambilanData($jenis, $mulai, $akhir, $valcari) {
        $query = Periksa::whereNotNull('periksa.verifikasi')->where('periksa.status', '!=', 'Arsip');
        if ($jenis == 'ThisDay') {
            return $query->whereDate('daftar', Carbon::today());
        } else if ($jenis == 'mundur2') {
            return $query->whereDate('daftar', '>=', Carbon::today()->subDays(2));
        } else if ($jenis == 'mundur3') {
            return $query->whereDate('daftar', '>=', Carbon::today()->subDays(3));
        } else if ($jenis === 'searchbydate') {
            $mulai = $mulai ?: date("Y-m-d");
            $akhir = $akhir ?: date("Y-m-d");
            if ($mulai >= $akhir) {
                $akhir = date('Y-m-d', strtotime($akhir . ' +1 day'));
            }
            return $query->whereBetween('daftar', [$mulai, $akhir]);
        } else {
            switch ($jenis) {
                case 'norm':
                    return $query->where('noregister', 'LIKE', '%'.$valcari.'%');
                case 'nofoto':
                    return $query->where('nofoto', 'LIKE', '%'.$valcari.'%');
                case 'rekues':
                    return $query->where('reques', 'LIKE', '%'.$valcari.'%');
                case 'keterangan':
                    return $query->where('keterangan', 'LIKE', '%'.$valcari.'%');
                case 'kesimpulan':
                    return $query->where('keterangan', 'LIKE', '%'.$valcari.'%');
                default:
                    return $query->orderBy('id', 'DESC');
            }
        }
        return $query;
    }
    protected function getPemeriksaanData($jenis, $mulai, $akhir, $valcari) {
        if ($valcari == 'allspv'){
            $query = Periksa::where('status', 'LIKE', 'Expertise Saved (Un Verified)')->whereNull('periksa.verifikasi');
        } else {
            $query = Periksa::where('status', 'LIKE', 'Expertise Saved (Un Verified)')->whereNull('periksa.verifikasi')->where('periksa.dokter_id', Session('id'));
        }
        return $query;
    }
    protected function handleOtherPengambilanQueries($query, $jenis, $valcari) {
        switch ($jenis) {
            case 'norm':
                return $query->where('noregister', 'LIKE', '%'.$valcari.'%');
            case 'nofoto':
                return $query->where('nofoto', 'LIKE', '%'.$valcari.'%');
            case 'rekues':
                return $query->where('reques', 'LIKE', '%'.$valcari.'%');
            case 'keterangan':
                return $query->where('keterangan', 'LIKE', '%'.$valcari.'%');
            case 'kesimpulan':
                return $this->handleKesimpulanQuery($query, $valcari);
            default:
                return $query;
        }
    }
    protected function handleKesimpulanQuery($query, $valcari) {
        return $query->where('keterangan', 'LIKE', '%'.$valcari.'%');
    }
    protected function getDefaultData($jenis, $master, $mulai, $akhir, $valcari) {
        $query = Periksa::whereNotNull('nofoto');
        if ($jenis == 'ThisDay') {
            return $query->where(function($q) {
                            $q->where(function($sub) {
                                $sub->where('status', '!=', 'Selesai')
                                    ->where('status', 'not like', 'Dibatalkan%');
                            })->orWhereNull('status');
                        });
        } else if ($jenis == 'ThisDayPendaftaran') {
            return $query->whereDate('daftar', Carbon::today());
        } else if ($jenis == 'mundur2') {
            return $query->whereDate('daftar', '>=', Carbon::today()->subDays(2));
        } else if ($jenis == 'mundur3') {
            return $query->whereDate('daftar', '>=', Carbon::today()->subDays(3));
        } else if ($jenis === 'searchbydate') {
            $mulai = $mulai ?: date("Y-m-d");
            $akhir = $akhir ?: date("Y-m-d");
            if ($mulai >= $akhir) {
                $akhir = date('Y-m-d', strtotime($akhir . ' +1 day'));
            }
            return $query->whereBetween('daftar', [$mulai, $akhir]);
        } else if ($jenis === 'searchbydatemanual') {
            $mulai = $mulai ?: date("Y-m-d");
            $akhir = $akhir ?: date("Y-m-d");
            if ($mulai >= $akhir) {
                $akhir = date('Y-m-d', strtotime($akhir . ' +1 day'));
            }
            return $query->whereBetween('daftar', [$mulai, $akhir])->whereNotIn('pendaftar', ['supervisor', 'admin', 'analis', 'ppds', 'developer']);
        } else {
            switch ($jenis) {
                case 'norm':
                    return $query->where('noregister', 'LIKE', '%'.$valcari.'%');
                case 'nofoto':
                    return $query->where('nofoto', 'LIKE', '%'.$valcari.'%');
                case 'rekues':
                    return $query->where('reques', 'LIKE', '%'.$valcari.'%');
                case 'keterangan':
                    return $query->where('keterangan', 'LIKE', '%'.$valcari.'%');
                case 'kesimpulan':
                    return $query->where('keterangan', 'LIKE', '%'.$valcari.'%');
                default:
                    return $query->orderBy('id', 'DESC');
            }
        }
        return $query;
    }
    protected function applyFilters($request, $data, $filterscount) {
        for ($i = 0; $i < $filterscount; $i++) {
            $filtervalue = $request->input('filtervalue'.$i);
            $filterdatafield = $request->input('filterdatafield'.$i);
    
            $filterdatafield = match ($filterdatafield) {
                'tlsnoregister' => 'noregister',
                'tlsnofoto'     => 'nofoto',
                'tlsnama'       => 'nmpasien', 
                'nama'          => 'nmpasien',
                'daftartgl'     => 'daftar', 
                'daftarjam'     => 'daftar',
                'tlsurgensi'    => 'urgensi',
                'tlsreques'     => 'reques',
                'tlsruangan'    => 'ruangan',
                'tlsstatus'     => 'status',
                default         => $filterdatafield,
            };
    
            $data = $this->applyFilterCondition($data, $filterdatafield, $filtervalue);
        }
    }
    protected function applyFilterCondition($data, $filterdatafield, $filtervalue) {
        if ($filtervalue === '<span style="background-color: red;">IGD</span>') {
            return $data->whereNull('noloket');
        } elseif ($filtervalue === '<span style="background-color: green;">SENTRAL</span>') {
            return $data->whereNotNull('noloket');
        }
        return $data->where($filterdatafield, 'LIKE', '%'.$filtervalue.'%');
    }
    protected function prepareDateRange($mulai, $akhir) {
        $cektanggal = explode(" - ", $mulai);
        if (isset($cektanggal[1])) {
            return [\Carbon\Carbon::parse($cektanggal[0])->format('Y-m-d'), \Carbon\Carbon::parse($cektanggal[1])->format('Y-m-d')];
        }
        return [$mulai, $akhir];
    }
    protected function Hl7Register($id, $kirimke){
        $panggilan  = '';
        $sukses     = 0;
		$error		= '';
		$emailbody 	= '';
        $pesan      = '';
        $periksa 	= Periksa::where('id', $id)->first();
        $idperiksa  = $periksa->id;
		$idpasien	= $periksa->pasien_id;
        $keterangan	= $periksa->keterangan;
        $daftar 	= $periksa->daftar;
        $idruang 	= $periksa->ruangan_id;
        $kamar 		= $periksa->ruangan ?? 'Kamar Periksa';
        $urgensi	= $periksa->urgensi;
        $idpoli 	= $periksa->poli_id;
        $statuse 	= $periksa->status;
        $noregister	= $periksa->noregister;
        $asalpasien	= $periksa->asalpasien;
        $reques		= $periksa->reques;
        $asuransi	= $periksa->asuransi;
        $foto		= $periksa->foto;
        $analis     = $periksa->analis;
        $nofoto		= $periksa->nofoto;
        $jk 		= $periksa->jkpasien;
        $tgllahir	= $periksa->tgllahirpasien;
        $kota 		= '';
        $alamat 	= $periksa->alamatpasien;
        $nama 		= $periksa->nmpasien;
        $norm 		= $periksa->noregister;
        $poli		= $periksa->getPoli->poli ?? 'EMI Primary';
        $iddokter   = $periksa->dokter_id;
        if (is_null($analis)){
            Periksa::where('id', $idperiksa)->update([
                'analis'	=> Session('id'),
                'nmanalis'	=> Session('nama'),
                'foto'			=> date("Y-m-d H:i:s")
            ]);
        }
        $today 		= date("YmdHi");
        $tanggal 	= date("Y-m-d H:i");
        $dokter 	= Session('nama');
        $arrayttl 	= explode("-", $nofoto);
        $jenis 		= $arrayttl[0];
        $tengah 	= '';
        $blakang	= '';
        $tgllahir 	= str_replace('-', '', $tgllahir);
        $arrayttl 	= explode(" ", $nama);
        $fname 		= iconv("UTF-8", "tis-620", $arrayttl[0]);
        if (isset($arrayttl[1])){
            $tengah = iconv("UTF-8", "tis-620", $arrayttl[1]);
        }
        if (isset($arrayttl[2])){
            $blakang = iconv("UTF-8", "tis-620", $arrayttl[2]);
        } else {
            $blakang 	= $tengah;
            $tengah 	= '';
        }
        $daftar 	= str_replace(':', '', $daftar);
        $tanggal	= str_replace('-', '', $daftar);
        $tanggal	= str_replace(' ', '', $tanggal);
        $berita 	= '';
        if ($urgensi == 'Elective'){ $urgensi = 'INPATIENT'; $prioritas = 'Routine'; }
        else if ($urgensi == 'CITO'){ $urgensi = 'EMERGENCY'; $prioritas = 'Cito'; }
        else { $urgensi = 'OUTPATIENT'; $prioritas = 'Routine'; }
        
        if ($jk == 'L'){ $panggilan = 'TN'; $jk = 'M'; }
        else if ($jk == 'P') { $panggilan = 'NY'; $jk = 'F'; }
        else { $panggilan = 'UNK'; $jk = 'O'; }
        $panggilan = '';
        if ($blakang == ''){ $blakang = $fname; }
        
        $msg = new Message();
        $msh = new MSH();
        $msh->setField(3, 'LIS');
        $msh->setField(4, 'RSSA MALANG');
        $msh->setField(5, 'OESEND_PROD');
        $msh->setField(6, 'EMR');
        $msh->setField(7, $today);
        $msh->setField(9, ['ORM', 'O01']);
        $msg->addSegment($msh);
        
        $pid = new PID();
        $pid->setField(2, [$norm, '', '11', $poli]);
        $pid->setField(3, [$norm, 'C', '11', $jenis]);
        $pid->setPatientName([$blakang, $fname, $tengah, $panggilan]);
        $pid->setField(7, $tgllahir);
        $pid->setField(8, $jk);
        $pid->setField(10, 'IN');
        $pid->setField(18, [$idperiksa, '', 'M11', 'Visit']);
        $pid->setField(19, 'IN');
        $msg->addSegment($pid);
        
        $pv1 = new PV1();
        $pv1->setField(2, $urgensi);
        $pv1->setField(3, [$jenis,'','', $kamar]);
        $pv1->setField(10, $poli);
        $pv1->setField(18, $asuransi);
        $pv1->setField(19, [$idperiksa, '', 'M11', 'Visit']);
        $pv1->setField(44, $today);
        $msg->addSegment($pv1);
        
        $orc = new ORC();
        $orc->setField(1, 'NW');
        $orc->setField(2, [$nofoto, $poli]);
        $orc->setField(3, [$nofoto, $poli]);
        $orc->setField(5, 'SC');
        $orc->setField(7, ['', '', '', '', '', $prioritas]);
        $orc->setField(15, $today);
        $orc->setField(17, 'Mikrobiologi RSSA');
        $msg->addSegment($orc);
        
        $obr = new OBR();
        $obr->setField(2, [$nofoto, $poli]);
        $obr->setField(3, [$nofoto, $poli]);
        $obr->setField(5, $prioritas);
        $obr->setField(6, $today);
        $obr->setField(16, [$iddokter, $dokter]);
        $obr->setField(18, $nofoto);
        $obr->setField(27, ['1', 'once', $tanggal, $prioritas]);
        $obr->setField(36, $today);
        $msg->addSegment($obr);
        $config     = new SerialConfig();
        $config->setBaudRate(9600);
        $config->setParity(0);
        $config->setDataBits(8);
        $config->setStopBits(1);
        $config->setFlowControl(0);
        try {
            $hl7Message = $msg->toString();
            
            if ($kirimke == 'vitek01'){
                $serial     = new SerialDio("COM1", $config);
                $serial->open('r+b');
                $serial->setBlocking(0);
                $serial->setTimeout(0, 0);
                $serial->send($hl7Message);
                $pesan      = $serial->read();
                $serial->close();
            } else if ($kirimke == 'vitek02'){
                $serial     = new SerialDio("COM2", $config);
                $serial->open('r+b');
                $serial->setBlocking(0);
                $serial->setTimeout(0, 0);
                $serial->send($hl7Message);
                $pesan      = $serial->read();
                $serial->close();
            } else if ($kirimke == 'genexpert01'){
                $serial     = new SerialDio("COM3", $config);
                $serial->open('r+b');
                $serial->setBlocking(0);
                $serial->setTimeout(0, 0);
                $serial->send($hl7Message);
                $pesan      = $serial->read();
                $serial->close();
            } else if ($kirimke == 'genexpert02'){
                $serial     = new SerialDio("COM4", $config);
                $serial->open('r+b');
                $serial->setBlocking(0);
                $serial->setTimeout(0, 0);
                $serial->send($hl7Message);
                $pesan      = $serial->read();
                $serial->close();
            } else if ($kirimke == 'genexpert03'){
                $serial     = new SerialDio("COM4", $config);
                $serial->open('r+b');
                $serial->setBlocking(0);
                $serial->setTimeout(0, 0);
                $serial->send($hl7Message);
                $pesan      = $serial->read();
                $serial->close();
            } else if ($kirimke == 'abbotm2000'){
                $serial     = new SerialDio("COM4", $config);
                $serial->open('r+b');
                $serial->setBlocking(0);
                $serial->setTimeout(0, 0);
                $serial->send($hl7Message);
                $pesan      = $serial->read();
                $serial->close();
            } else if ($kirimke == 'bd01'){
                $serial     = new SerialDio("COM4", $config);
                $serial->open('r+b');
                $serial->setBlocking(0);
                $serial->setTimeout(0, 0);
                $serial->send($hl7Message);
                $pesan      = $serial->read();
                $serial->close();
            } else if ($kirimke == 'bd02'){
                $pacsaddr   = '172.16.29.224';
                $port       = '8088';
                $connection = new Connection($pacsaddr, $port);
                if ($connection) {
                    $ack        = $connection->send($msg);
                    $hasilkrm   = $ack->toString(true);
                    $pesan      = "Full Response: " . $hasilkrm;
                    $msa = $ack->getSegmentsByName('MSA');
                    if (isset($msa[0])) {
                        $ackCode = $msa[0]->getAcknowledgementCode();
                        $pesan  = $pesan." ACK Code: " . $ackCode;
                        if ($ackCode[1] === 'A') {
                            $pesan  = $pesan.' Pasien atas nama ' . $nama . ' Dengan Order Pemeriksaan ' . $rekuese . ' Dari ' . $asalpasien . ' Terkirim ke Modality';
                        } else {
                            $pesan  = $pesan."E rror text: " . $msa[0]->getTextMessage();
                        }
                    } else {
                        $pesan  = $pesan." No MSA segment found in the response.";
                    }
                } else {
                    $pesan  = $pesan.' Tidak Dapat Terhubung';
                }
            } else {
                $serial     = new SerialDio("COM1", $config);
                $serial->open('r+b');
                $serial->setBlocking(0);
                $serial->setTimeout(0, 0);
                $serial->send($hl7Message);
                $pesan      = $serial->read();
                $serial->close();
            }
           
        }catch (Exception $e) {
            $pesan = $e->getMessage();
        }
        return $pesan;
    }
    protected function Hl7GetResult($id, $kirimke){
        $panggilan  = '';
        $sukses     = 0;
		$error		= '';
		$emailbody 	= '';
        $periksa 	= Periksa::where('id', $id)->first();
        $idperiksa  = $periksa->id;
		$idpasien	= $periksa->pasien_id;
        $keterangan	= $periksa->keterangan;
        $daftar 	= $periksa->daftar;
        $idruang 	= $periksa->ruangan_id;
        $kamar 		= $periksa->ruangan ?? 'Kamar Periksa';
        $urgensi	= $periksa->urgensi;
        $idpoli 	= $periksa->poli_id;
        $statuse 	= $periksa->status;
        $noregister	= $periksa->noregister;
        $asalpasien	= $periksa->asalpasien;
        $reques		= $periksa->reques;
        $asuransi	= $periksa->asuransi;
        $foto		= $periksa->foto;
        $analis= $periksa->analis;
        $nofoto		= $periksa->nofoto;
        $jk 		= $periksa->jkpasien;
        $tgllahir	= $periksa->tgllahirpasien;
        $kota 		= '';
        $alamat 	= $periksa->alamatpasien;
        $nama 		= $periksa->nmpasien;
        $norm 		= $periksa->noregister;
        $poli		= $periksa->getPoli->poli ?? 'EMI Primary';
        $iddokter   = $periksa->dokter_id;
        $today 		= date("YmdHi");
        $tanggal 	= date("Y-m-d H:i");
        $dokter 	= Session('nama');
        $arrayttl 	= explode("-", $nofoto);
        $jenis 		= $arrayttl[0];
        $tengah 	= '';
        $blakang	= '';
        $tgllahir 	= str_replace('-', '', $tgllahir);
        $arrayttl 	= explode(" ", $nama);
        $fname 		= iconv("UTF-8", "tis-620", $arrayttl[0]);
        if (isset($arrayttl[1])){
            $tengah = iconv("UTF-8", "tis-620", $arrayttl[1]);
        }
        if (isset($arrayttl[2])){
            $blakang = iconv("UTF-8", "tis-620", $arrayttl[2]);
        } else {
            $blakang 	= $tengah;
            $tengah 	= '';
        }
        $daftar 	= str_replace(':', '', $daftar);
        $tanggal	= str_replace('-', '', $daftar);
        $tanggal	= str_replace(' ', '', $tanggal);
        $berita 	= '';
        if ($urgensi == 'Elective'){ $urgensi = 'INPATIENT'; $prioritas = 'Routine'; }
        else if ($urgensi == 'CITO'){ $urgensi = 'EMERGENCY'; $prioritas = 'Cito'; }
        else { $urgensi = 'OUTPATIENT'; $prioritas = 'Routine'; }
        
        if ($jk == 'L'){ $panggilan = 'TN'; $jk = 'M'; }
        else if ($jk == 'P') { $panggilan = 'NY'; $jk = 'F'; }
        else { $panggilan = 'UNK'; $jk = 'O'; }
        $panggilan = '';
        if ($blakang == ''){ $blakang = $fname; }
        $recievingfas	= 'OESEND_PROD';
				
        $msg = new Message();
        $msh = new MSH();
        $msh->setField(3, 'LIS');
        $msh->setField(4, 'RSSA MALANG');
        $msh->setField(5, 'OESEND_PROD');
        $msh->setField(6, 'EMR');
        $msh->setField(7, $today);
        $msh->setField(9, ['ADT', 'A08']);
        $msg->addSegment($msh);
        
        $evn = new EVN();
        $evn->setField(1, 'A01');					
        $evn->setField(2, $tanggal);
        $evn->setField(5, 'QAO_AE_TL');
        $evn->setField(6, 'NV44I0');
        $msg->addSegment($evn);
        $pid = new PID();
        $pid->setField(2, [$norm, '', '11', $poli]);
        $pid->setField(3, [$norm, 'C', '11', $jenis]);
        $pid->setPatientName([$blakang, $fname, $tengah, $panggilan]);
        $pid->setField(7, $tgllahir);
        $pid->setField(8, $jk);
        $pid->setField(10, 'IN');
        $pid->setField(18, [$idperiksa, '', 'M11', 'Visit']);
        $pid->setField(19, 'IN');
        $msg->addSegment($pid);
        $pv1 = new PV1();
        $pv1->setField(2, $urgensi);
        $pv1->setField(3, [$jenis,'','', $kamar]);
        $pv1->setField(10, $poli);
        $pv1->setField(18, $asuransi);
        $pv1->setField(19, [$idperiksa, '', 'M11', 'Visit']);
        $pv1->setField(44, $today);
        $msg->addSegment($pv1);
        try {
            $hl7Message = $msg->toString();
            $config     = new SerialConfig();
            $config->setBaudRate(9600);
            $config->setParity(0);
            $config->setDataBits(8);
            $config->setStopBits(1);
            $config->setFlowControl(0);
            if ($kirimke == 'vitek01'){
                $serial     = new SerialDio("COM1", $config);
            } else if ($kirimke == 'vitek02'){
                $serial     = new SerialDio("COM2", $config);
            } else if ($kirimke == 'genexpert01'){
                $serial     = new SerialDio("COM3", $config);
            } else if ($kirimke == 'genexpert02'){
                $serial     = new SerialDio("COM4", $config);
            } else if ($kirimke == 'genexpert03'){
                $serial     = new SerialDio("COM4", $config);
            } else if ($kirimke == 'abbotm2000'){
                $serial     = new SerialDio("COM4", $config);
            } else if ($kirimke == 'bd01'){
                $serial     = new SerialDio("COM4", $config);
            } else if ($kirimke == 'bd02'){
                $serial     = new SerialDio("COM4", $config);
            } else {
                $serial     = new SerialDio("COM1", $config);
            }
            $serial->open('r+b');
            $serial->setBlocking(0);
            $serial->setTimeout(0, 0);
            $serial->send($hl7Message);
            $pesan      = $serial->read();
            $serial->close();
        }catch (Exception $e) {
            $pesan = $e->getMessage();
        }
        return $pesan;
    }
    protected function Hl7Send($id, $pacsaddr){
        $port		= '10020';
        $panggilan  = '';
        $sukses     = 0;
		$error		= '';
		$emailbody 	= '';
        $periksa 	= Periksa::where('id', $id)->first();
        $idperiksa  = $periksa->id;
		$idpasien	= $periksa->pasien_id;
        $keterangan	= $periksa->keterangan;
        $daftar 	= $periksa->daftar;
        $idruang 	= $periksa->ruangan_id;
        $kamar 		= $periksa->ruangan ?? 'Kamar Periksa';
        $urgensi	= $periksa->urgensi;
        $idpoli 	= $periksa->poli_id;
        $statuse 	= $periksa->status;
        $noregister	= $periksa->noregister;
        $asalpasien	= $periksa->asalpasien;
        $reques		= $periksa->reques;
        $asuransi	= $periksa->asuransi;
        $foto		= $periksa->foto;
        $analis     = $periksa->analis;
        $nofoto		= $periksa->nofoto;
        $jk 		= $periksa->jkpasien;
        $tgllahir	= $periksa->tgllahirpasien;
        $kota 		= '';
        $alamat 	= $periksa->alamatpasien;
        $nama 		= $periksa->nmpasien;
        $norm 		= $periksa->noregister;
        $poli		= $periksa->getPoli->poli ?? 'EMI Primary';
        $iddokter   = $periksa->dokter_id;
        $today 		= date("YmdHi");
        $tanggal 	= date("Y-m-d H:i");
        $dokter 	= Session('nama');
        $arrayttl 	= explode("-", $nofoto);
        $jenis 		= $arrayttl[0];
        $tengah 	= '';
        $blakang	= '';
        $tgllahir 	= str_replace('-', '', $tgllahir);
        $arrayttl 	= explode(" ", $nama);
        $fname 		= iconv("UTF-8", "tis-620", $arrayttl[0]);
        if (isset($arrayttl[1])){
            $tengah = iconv("UTF-8", "tis-620", $arrayttl[1]);
        }
        if (isset($arrayttl[2])){
            $blakang = iconv("UTF-8", "tis-620", $arrayttl[2]);
        } else {
            $blakang 	= $tengah;
            $tengah 	= '';
        }
        $daftar 	= str_replace(':', '', $daftar);
        $tanggal	= str_replace('-', '', $daftar);
        $tanggal	= str_replace(' ', '', $tanggal);
        $berita 	= '';
        if ($urgensi == 'Elective'){ $urgensi = 'INPATIENT'; $prioritas = 'Routine'; }
        else if ($urgensi == 'CITO'){ $urgensi = 'EMERGENCY'; $prioritas = 'Cito'; }
        else { $urgensi = 'OUTPATIENT'; $prioritas = 'Routine'; }
        
        if ($jk == 'L'){ $panggilan = 'TN'; $jk = 'M'; }
        else if ($jk == 'P') { $panggilan = 'NY'; $jk = 'F'; }
        else { $panggilan = 'UNK'; $jk = 'O'; }
        $panggilan = '';
        if ($blakang == ''){ $blakang = $fname; }
        $recievingfas	= 'OESEND_PROD';
				
        $msg 		= new Message();
        $msh 		= new MSH();
        //$msh->setField(1, '|');
        //$msh->setField(2, '^~\&');
        $msh->setField(3, 'LIS');
        $msh->setField(4, 'RSSA MALANG');
        $msh->setField(5, 'OESEND_PROD');
        $msh->setField(6, 'EMR');
        $msh->setField(7, $today);
        $msh->setField(9, ['ORU', 'R01']);
        //$msh->setField(10, '23063601579');
        //$msh->setField(11, 'P');
        //$msh->setField(12, '2.3');
        $msg->addSegment($msh);
        
        $pid = new PID();
        $pid->setField(2, [$norm, '', '11', $poli]);
        $pid->setField(3, [$norm, 'C', '11', $jenis]);
        $pid->setPatientName([$blakang, $fname, $tengah, $panggilan]);
        $pid->setField(7, $tgllahir);
        $pid->setField(8, $jk);
        $pid->setField(10, 'IN');
        $pid->setField(11, [$alamat, '', $kota, '', 'ID']);
        $pid->setField(18, [$idperiksa, '', 'M11', 'Visit']);
        $msg->addSegment($pid);
        
        $pv1 		= new PV1();
        $pv1->setField(2, $urgensi);
        $pv1->setField(3, [$poli, $kamar]);
        $pv1->setField(7, [$iddokter, $dokter]);
        $pv1->setField(9, [$iddokter, $dokter]);
        $pv1->setField(10, $jenis);
        $pv1->setField(17, [$iddokter, $dokter]);
        $pv1->setField(18, $asalpasien);
        $pid->setField(19, [$idperiksa, '', 'M11', 'Visit']);
        $pv1->setField(44, $today);
        $msg->addSegment($pv1);
        
        $orc 		= new ORC();
        $orc->setField(1, 'NW');
        $orc->setField(2, [$nofoto,$jenis]);
        $orc->setField(3, [$nofoto,$poli]);
        $orc->setField(5, 'CM');
        $orc->setField(7, $prioritas);
        $orc->setField(12, [$iddokter, $dokter]);
        $orc->setField(15, $today);
        $orc->setField(16, '');
        $msg->addSegment($orc);
        
        $obr 		= new OBR();
        $obr->setField(1, $idperiksa);
        $obr->setField(2, [$nofoto,$jenis]);
        $obr->setField(3, [$nofoto,$poli]);
        $obr->setField(4, [$modality, $jenis, $poli]);
        $obr->setField(7, $tanggal);
        $obr->setField(16, [$iddokter, $dokter]);
        $obr->setField(18, [$nofoto,$poli]);
        $obr->setField(22, 'F');
        $obr->setField(24, $modality);
        $obr->setField(25, 'F');
        $obr->setField(27, ['1','','0','', '', $prioritas]);
        $obr->setField(32, [$iddokter, $dokter]);
        $obr->setField(36, $tanggal);
        $msg->addSegment($obr);
        
        $obx 		= new OBX();
        $obx->setField(1, '1');
        $obx->setField(2, 'FT');
        $obx->setField(3, [$modality, $jenis, $poli]);
        $obx->setField(5, $keterangan);
        //$obx->setField(5, 'TS yang terhormat,');
        $obx->setField(8, 'A');
        $obx->setField(11, 'F');
        $obx->setField(14, $today);
        
        $msg->addSegment($obx);
        $obx 		= new OBX();
        $obx->setField(1, '2');
        $obx->setField(2, 'ST');
        $msg->addSegment($obx);
        $obx 		= new OBX();
        $obx->setField(1, '3');
        $obx->setField(2, 'ST');
        $msg->addSegment($obx);
        $i 			= 4;
        $arrayketerangan= explode("<br />", $keterangan);
        foreach ($arrayketerangan as $v) {
        	if ($v != ''){
        		$text = str_replace('<p>', '', $v);
        		$text = str_replace('<br />', '', $text);
        		$text = str_replace('&nbsp;', '', $text);
        		$text = str_replace('<tr>', '', $text);
        		$text = str_replace('</tr>', '', $text);
        		$text = str_replace('<td>', '', $text);
        		$text = str_replace('</td>', ' ', $text);
        		$text = trim(preg_replace('/\s+/', ' ', $text));
        		$cekbaris = strlen($text);
        		if ($cekbaris < 126){
        			$obx = new OBX();
        			$obx->setField(1, $i);
        			$obx->setField(2, 'ST');
        			$obx->setField(5, $text);
        			$msg->addSegment($obx);
        			$i++;
        		}else {
        			$baris1 = substr($text,0,125);
        			$obx 	= new OBX();
        			$obx->setField(1, $i);
        			$obx->setField(2, 'ST');
        			$obx->setField(5, $baris1);
        			$msg->addSegment($obx);
        			$cekbaris = $cekbaris - 125;
        			$i++;
        			if ($cekbaris >= 1){
        				$baris2 = substr($text,126,125);
        				$obx 	= new OBX();
        				$obx->setField(1, $i);
        				$obx->setField(2, 'ST');
        				$obx->setField(5, $baris2);
        				$msg->addSegment($obx);
        				$cekbaris = $cekbaris - 125;
        				$i++;
        				if ($cekbaris >= 1){
        					$baris3 = substr($text,250,125);
        					$obx 	= new OBX();
        					$obx->setField(1, $i);
        					$obx->setField(2, 'ST');
        					$obx->setField(5, $baris3);
        					$msg->addSegment($obx);
        					$cekbaris = $cekbaris - 125;
        					$i++;
        					if ($cekbaris >= 1){
        						$baris4 = substr($text,375,125);
        						$obx 	= new OBX();
        						$obx->setField(1, $i);
        						$obx->setField(2, 'ST');
        						$obx->setField(5, $baris4);
        						$msg->addSegment($obx);
        						$i++;
        					}else {$i++;}
        				}else {$i++;}
        			}else {$i++;}
        		}
        	}
        	else {
        		$obx = new OBX();
        		$obx->setField(1, $i);
        		$obx->setField(2, 'ST');
        		$msg->addSegment($obx);
        		$i++;
        	}
        }
        $obx = new OBX();
        $obx->setField(1, $i);
        $obx->setField(2, 'ST');
        $msg->addSegment($obx);
        $i++;
        $cekid 				= $i - 1;
        $arraykesimpulan 	= explode("<br />", $kesimpulan);
        foreach ($arraykesimpulan as $v) {
        	if ($v != ''){
        		$text = str_replace('<p>', '', $v);
        		$text = str_replace('<br />', '', $text);
        		$text = str_replace('&nbsp;', '', $text);
        		$text = trim(preg_replace('/\s+/', ' ', $text));
        		$cekbaris = strlen($text);
        		if ($cekbaris < 126){
        			$cekid++;
        			$selisih = $cekid - $i;
        			if ($selisih != 1){
        			$obx = new OBX();
        			$obx->setField(1, $i);
        			$obx->setField(2, 'ST');
        			$obx->setField(5, $text);
        			$msg->addSegment($obx);
        			$i++;
        			}
        		}else {
        			$baris1 = substr($text,0,125);
        			$cekid++;
        			$selisih = $cekid - $i;
        			if ($selisih != 1){
        			$obx = new OBX();
        			$obx->setField(1, $i);
        			$obx->setField(2, 'ST');
        			$obx->setField(5, $baris1);
        			$msg->addSegment($obx);
        			$i++;
        			}
        			$cekbaris = $cekbaris - 125;
        			if ($cekbaris >= 1){
        				$baris2 = substr($text,126,125);
        				$cekid++;
        				$selisih = $cekid - $i;
        				if ($selisih != 1){
        				$obx = new OBX();
        				$obx->setField(1, $i);
        				$obx->setField(2, 'ST');
        				$obx->setField(5, $baris2);
        				$msg->addSegment($obx);
        				$cekbaris = $cekbaris - 125;
        				$i++;
        				}
        				if ($cekbaris >= 1){
        					$baris3 = substr($text,250,125);
        					$cekid++;
        					$selisih = $cekid - $i;
        					if ($selisih != 1){
        					$obx = new OBX();
        					$obx->setField(1, $i);
        					$obx->setField(2, 'ST');
        					$obx->setField(5, $baris3);
        					$msg->addSegment($obx);
        					$cekbaris = $cekbaris - 125;
        					$i++;
        					}
        					if ($cekbaris >= 1){
        						$baris4 = substr($text,375,125);
        						$cekid++;
        						$selisih = $cekid - $i;
        						if ($selisih != 1){
        						$obx = new OBX();
        						$obx->setField(1, $i);
        						$obx->setField(2, 'ST');
        						$obx->setField(5, $baris4);
        						$msg->addSegment($obx);
        						$i++;
        						}
        					}else {$i++;}
        				}else {$i++;}
        			}else {$i++;}
        		}
        	}
        	else {
        		$obx = new OBX();
        		$obx->setField(1, $i);
        		$obx->setField(2, 'ST');
        		$msg->addSegment($obx);
        		$i++;
        	}
        }
        $msg->addSegment($obx);
        $result 	= null;
        $tes 		= 'tcp:'.$pacsaddr.':'.$port;
        try {
            $fp 	= stream_socket_client($tes, $errno, $errstr, 1);
        }catch (Exception $e) {
            $result = $e->getMessage();
        }
        if (strpos($result, 'unable to connect') !== false) {
            $pesan = 'Saved to RIS Only';
        } else {
            $pesan = 'Expertise Saved to RIS only';
            $connection = new Connection($pacsaddr, $port);
            $ack 		= $connection->send($msg);
            $hasilkrm 	= $ack->toString(true);
            if (strpos($hasilkrm, 'MSH') === false) {
            	$pesan = 'Failed to send Expertise to "PACS IP" => '.$pacsaddr.', "Port" => '.$port;
            }
            $msa 		= $ack->getSegmentsByName('MSA')[0];
            $ackCode 	= $msa->getAcknowledgementCode();
            if ($ackCode[1] === 'A') {
            	$pesan = "Expertise Saved to PACS\n";
            }
            else {
            	$pesan = "Error text: " . $msa->getTextMessage();
            }
        }
        return $pesan;
    }
    protected function Hl7SendCancel($id, $pacsaddr){
        $port		= '10020';
        $panggilan  = '';
        $sukses     = 0;
		$error		= '';
		$emailbody 	= '';
        $periksa 	= Periksa::where('id', $id)->first();
        $idperiksa  = $periksa->id;
		$idpasien	= $periksa->pasien_id;
        $keterangan	= $periksa->keterangan;
        $daftar 	= $periksa->daftar;
        $idruang 	= $periksa->ruangan_id;
        $kamar 		= $periksa->ruangan ?? 'Kamar Periksa';
        $urgensi	= $periksa->urgensi;
        $idpoli 	= $periksa->poli_id;
        $statuse 	= $periksa->status;
        $noregister	= $periksa->noregister;
        $asalpasien	= $periksa->asalpasien;
        $reques		= $periksa->reques;
        $asuransi	= $periksa->asuransi;
        $foto		= $periksa->foto;
        $analis     = $periksa->analis;
        $nofoto		= $periksa->nofoto;
        $jk 		= $periksa->jkpasien;
        $tgllahir	= $periksa->tgllahirpasien;
        $kota 		= '';
        $alamat 	= $periksa->alamatpasien;
        $nama 		= $periksa->nmpasien;
        $norm 		= $periksa->noregister;
        $poli		= $periksa->getPoli->poli ?? 'EMI Primary';
        $iddokter   = $periksa->dokter_id;
        $today 		= date("YmdHi");
        $tanggal 	= date("Y-m-d H:i");
        $dokter 	= Session('nama');
        $arrayttl 	= explode("-", $nofoto);
        $jenis 		= $arrayttl[0];
        $tengah 	= '';
        $blakang	= '';
        $tgllahir 	= str_replace('-', '', $tgllahir);
        $arrayttl 	= explode(" ", $nama);
        $fname 		= iconv("UTF-8", "tis-620", $arrayttl[0]);
        if (isset($arrayttl[1])){
            $tengah = iconv("UTF-8", "tis-620", $arrayttl[1]);
        }
        if (isset($arrayttl[2])){
            $blakang = iconv("UTF-8", "tis-620", $arrayttl[2]);
        } else {
            $blakang 	= $tengah;
            $tengah 	= '';
        }
        $daftar 	= str_replace(':', '', $daftar);
        $tanggal	= str_replace('-', '', $daftar);
        $tanggal	= str_replace(' ', '', $tanggal);
        $berita 	= '';
        if ($urgensi == 'Elective'){ $urgensi = 'INPATIENT'; $prioritas = 'Routine'; }
        else if ($urgensi == 'CITO'){ $urgensi = 'EMERGENCY'; $prioritas = 'Cito'; }
        else { $urgensi = 'OUTPATIENT'; $prioritas = 'Routine'; }
        
        if ($jk == 'L'){ $panggilan = 'TN'; $jk = 'M'; }
        else if ($jk == 'P') { $panggilan = 'NY'; $jk = 'F'; }
        else { $panggilan = 'UNK'; $jk = 'O'; }
        $panggilan = '';
        if ($blakang == ''){ $blakang = $fname; }
        $recievingfas	= 'OESEND_PROD';
			
        $daftar 	= str_replace(':', '', $daftar);
        $jk 		= $periksa->jkpasien;
        $tgllahir	= $periksa->tgllahirpasien;
        $kota 		= '';
        $alamat 	= $periksa->alamatpasien;
        $nama 		= $periksa->nmpasien;
        $norm 		= $periksa->noregister;
        $tgllahir 	= str_replace('-', '', $tgllahir);
        $tengah 	= '';
        $blakang	= '';
        $arrayttl 	= explode(" ", $nama);
        $fname 		= iconv("UTF-8", "tis-620", $arrayttl[0]);
        if (isset($arrayttl[1])){
            $tengah = iconv("UTF-8", "tis-620", $arrayttl[1]);
        }
        if (isset($arrayttl[2])){
            $blakang= iconv("UTF-8", "tis-620", $arrayttl[2]);
        }else {
            $blakang= $tengah;
            $tengah = '';
        }
        
        $today 		= date("YmdHi");
        $tanggal	= date("Ymd");
        $tanggal	= $tanggal.$daftar;
        $berita 	= '';
        if ($jk == 'L'){ $panggilan = 'TN'; $jk = 'M'; }
        else if ($jk == 'P') { $panggilan = 'NY'; $jk = 'F'; }
        else { $panggilan = 'UNK'; $jk = 'O'; }
        $panggilan = '';
        $port = '10030';
        $msg = new Message();
        $msh = new MSH();
        //$msh->setField(1, '|');
        //$msh->setField(2, '^~\&');
        $msh->setField(3, 'LIS');
        $msh->setField(4, 'RSSA MALANG');
        $msh->setField(5, 'OESEND_PROD');
        $msh->setField(6, 'EMR');
        $msh->setField(7, $today);
        $msh->setField(9, ['ORM', 'O01']);
        //$msh->setField(10, '23063601579');
        //$msh->setField(11, 'P');
        //$msh->setField(12, '2.3');
        $msg->addSegment($msh);
        
        $pid = new PID();
        $pid->setField(2, [$norm, '', '11', $poli]);
        $pid->setField(3, [$norm, 'C', '11', $jenis]);
        $pid->setPatientName([$blakang, $fname, $tengah, $panggilan]);
        $pid->setField(7, $tgllahir);
        $pid->setField(8, $jk);
        $pid->setField(10, 'IN');
        $pid->setField(18, [$idperiksa, '', 'M11', 'Visit']);
        $msg->addSegment($pid);
        
        $pv1 = new PV1();
        $pv1->setField(2, $urgensi);
        $pv1->setField(3, [$jenis,'','', $kamar]);
        $pv1->setField(10, 'END');
        $pv1->setField(18, 'NA');
        $pv1->setField(19, [$idperiksa, '', 'M11', 'Visit']);
        $pv1->setField(44, $today);
        $msg->addSegment($pv1);
        
        $orc = new ORC();
        $orc->setField(1, 'OC');
        $orc->setField(2, [$nofoto, $jenis]);
        $orc->setField(3, [$nofoto, $poli]);
        $orc->setField(5, 'CA');
        $orc->setField(7, ['', '', '', '', '', $prioritas]);
        $orc->setField(15, $today);
        $orc->setField(16, '', 'Administrative');
        $msg->addSegment($orc);
        $nofotobaru = 'HPUS'.$nofoto;
        $obr = new OBR();
        $obr->setField(2, ['', $jenis]);
        $obr->setField(3, [$nofotobaru, $poli]);
        $obr->setField(4, [$modality, $rekuese, $poli]);
        $obr->setField(5, $prioritas);
        $obr->setField(6, $tanggal);
        $obr->setField(16, [$iddokter, $dokter]);
        $obr->setField(19, $nofoto);
        $obr->setField(21, $jenis);
        $obr->setField(24, $modality);
        $obr->setField(27, ['1', 'once', $tanggal, $prioritas]);
        $obr->setField(36, $tanggal);
        $msg->addSegment($obr);
        
        $nte = new NTE();
        $nte->setField(3, 'Cancelled - Administrative');
        $msg->addSegment($nte);
        $connection = new Connection($pacsaddr, $port);
        $ack 		= $connection->send($msg);
        $hasilkrm 	= $ack->toString(true);
        $result 	= null;
        $tes 		= 'tcp://'.$pacsaddr.':'.$port;
        try {
            $fp 	= stream_socket_client($tes, $errno, $errstr, 1);
            if (strpos($result, 'unable to connect') !== false) {
                $pesan = 'Cannot Connet to PACS System';
            } else {
                $connection = new Connection($pacsaddr, $port);
                $ack 		= $connection->send($msg);
                $hasilkrm 	= $ack->toString(true);
                if (strpos($hasilkrm, 'MSH') === false) {
                    $pesan = 'Failed to send Cancel Order to "PACS IP" => '.$pacsaddr.', "Port" => '.$port;
                } 
                $msa 		= $ack->getSegmentsByName('MSA')[0];
                $ackCode 	= $msa->getAcknowledgementCode();
                if ($ackCode[1] === 'A') {
                    $pesan = "Send Cancel Order Success";
                }
                else {
                    $pesan = "Error text: " . $msa->getTextMessage();
                }
            }
        }catch (Exception $e) {
            $pesan = $e->getMessage();
        }
        
        return $pesan;
    }
}
