<?php

namespace App\Http\Controllers; 
use Illuminate\Http\Request; 
use Illuminate\Support\Facades\DB; 
use Illuminate\Support\Facades\Mail;
use App\Http\Controllers\SendMail;
use App\Services\AstmMessageService;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

use App\Poli; 
use App\Periksa; 
use App\DataListiner;
use App\Dokter;
use App\Pasien;
use App\Ruangan;
use App\Jawaban;
use App\Subjawaban;
use App\Setting;
use App\Logbook;
use App\Filefoto;
use App\Riwayat;
use App\Worklist;
use App\PeriksaSYNC;
use App\XFiles;
use App\User;
use App\PatientSample;
use App\ResultSample;
use App\KomponenJawaban;
use App\SiraB;
use App\Organisms;
use App\RekapAntibiotik;
use App\PendaftaranOnListiner;
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 DateTime; 
use Validator;
use File;
use Session;
use QrCode;
use Exception;
use PDFCREATOR;

define( 'API_ACCESS_KEY', 'AAAA6YBXh1k:APA91bFL0q7QAXQGohXMpTwHco79f13C8PFk1Oo8kKhg1JerOulT9-37dxyP8X5ibABI0NuQ4ZsVxKQKCt7HuR7lUdJJuB-hTVnBmOUIBYfBlHb-Lcp6aGkj4erfF7J__A5hufXjF8Vt' );

class DokterController extends Controller
{
	protected $lisServiceUrl;
    public function __construct() {
        $this->lisServiceUrl = env('LIS_SERVICE_URL', 'http://localhost:5000');
    }
	protected static function genSurat($id, $tabel){
		if ($tabel == 'dengan kop' OR $tabel == 'PDF'){
			$kopsurat = url('/kopsurat.png');
		} else {
			$kopsurat = '';
		}
		$data			= 	[];
		$homebase 		= 	url("/");
		$kalender 		= 	array('wulan','Januari','Februari','Maret','April','Mei','Juni','Juli','Agustus','September','Oktober','November','Desember');
		$periksa        =   Periksa::where('id', $id)->first();
		$nofoto     	= 	$periksa->nofoto;
		$dlp     		= 	$periksa->dlp;
		$keterangan     = 	$periksa->keterangan;
		$verifikasi     = 	$periksa->verifikasi;
		$analis     	= 	$periksa->analis;
		$nmppdssenior	= 	$periksa->nmppdssenior ?? '';
		$nmmiddleppds	= 	$periksa->nmmiddleppds ?? '';
		$nmppdsjunior	= 	$periksa->nmppdsjunior ?? '';
		$nmppdsmiddle2	= 	$periksa->nmppdsmiddle2 ?? '';
		$nmppdsjunior2	= 	$periksa->nmppdsjunior2 ?? '';
		$dokter			= 	$periksa->nmdokter ?? '';
		$statuse		= 	$periksa->status ?? '';
		$nik			= 	$periksa->getPasien->nik ?? $id;
		$bpjs			= 	$periksa->getPasien->bpjs ?? $id;
		$urlsurat 		= 	url('/').'/hasil/'.$periksa->nofoto;
		if ($verifikasi == '' OR is_null($verifikasi)){
			$tanggal 	= '';
		} else {
			$gettanggal = explode('-', $verifikasi);
			$yy 		= $gettanggal[0];
			$mm 		= (int)$gettanggal[1];
			$dd 		= $gettanggal[2];
			$mm 		= $kalender[$mm];
			$tanggal	= $dd.' '.$mm.' '.$yy;
		}
		$ppds			= '';
		if ($nmppdssenior != ''){
			$ppds		= $ppds.$nmppdssenior;
		}
		if ($nmmiddleppds != ''){
			$ppds		= $ppds.'<br />'.$nmmiddleppds;
		}
		if ($nmppdsjunior != ''){
			$ppds		= $ppds.'<br />'.$nmppdsjunior;
		}
		if ($nmppdsmiddle2 != ''){
			$ppds		= $ppds.'<br />'.$nmppdsmiddle2;
		}
		if ($nmppdsjunior2 != ''){
			$ppds		= $ppds.'<br />'.$nmppdsjunior2;
		}
		$tandatangananalis		= '';
		if ($analis){
			$getttd 			= Xfiles::where('xmarking', 'LIKE', '%-Photo-'.$analis)->where('xjenis', 'Tandatangan')->first();
			$tandatangananalis	= $getttd->xfile ?? '';
			if ($tandatangananalis == ''){
				$tandatangananalis 	= 'Surat '.$urlsurat.' Proses secara elektronik oleh '.$periksa->nmanalis.' pada tanggal '.$periksa->baca;
				try {
					$tandatangananalis = 'data:image/png;base64,'.base64_encode(
						QrCode::format('png')->size(100)->generate($tandatangananalis)
					);
				} catch (\Exception $e) {
					$tandatangananalis = url('/').'/boxed-bg.png';
				}
			}
		}
		$tandatangan			= $periksa->getTandatangan->xfile ?? '';
		if ($statuse == 'Selesai' OR $statuse == 'Arsip'){
			if ($tandatangan == ''){
				$tandatangan 	= 'Surat '.$urlsurat.' ditandatangani secara elektronik oleh '.$periksa->nmdokter.' pada tanggal '.$periksa->verifikasi;
				try {
					$tandatangan = 'data:image/png;base64,'.base64_encode(
						QrCode::format('png')->size(100)->generate($tandatangan)
					);
				} catch (\Exception $e) {
					$tandatangan = url('/').'/boxed-bg.png';
				}
			}
			
			$getjriwayat = Riwayat::where('nofoto', $nofoto)->where('keterangan', 'Adendum')->where('verifikasi', 'Accepted')->orderBy('created_at', 'ASC')->get();
			if (!empty($getjriwayat)){
				foreach($getjriwayat as $rriwayat){
					$tanggal 	= $rriwayat->created_at;
					$jawaban	= $rriwayat->jawaban;
					$keterangan	= $jawaban.'<br />'.$keterangan;
				}
			}
		} else {
			Periksa::where('id', $id)->update([
				'export'  =>  date('Y-m-d H:i:s')
			]);
			$tandatangan 			= url('/').'/boxed-bg.png';
		}
		$tandatangan				= '<img src="'.$tandatangan.'" width="120" height="100">';
		$tandatangananalis			= '<img src="'.$tandatangananalis.'" width="120" height="100">';
        $data                   	= [];
		$data['komponens']			= KomponenJawaban::where('accnumber', $periksa->nofoto)->get();
		$data['antibiotiks']		= RekapAntibiotik::where('orderid', $periksa->id)->get();
        $data['tanggal']   			= $tanggal;
		$data['periksa']   			= $periksa;
		$data['keterangan']   		= $keterangan;
		$data['tandatangananalis']  = $tandatangananalis;
		$data['ttdanalis']  		= $tandatangananalis;
		$data['tandatangan']   		= $tandatangan;
		$data['ppds']     			= $ppds;
		$data['kopsurat']     		= $kopsurat;
		$data['nik']     			= $nik;
		$data['bpjs']     			= $bpjs;
		if ($dlp == 'TBC'){
			$cekjenis = KomponenJawaban::where('accnumber', $periksa->nofoto)->where('komponen', 'id_jenispemeriksaantb')->first();
			$template 				= $cekjenis->isidata ?? '';
			$data['template']		= $template;
			if ($template == 'TCM MTB Rif (Xpert)' OR $template == 'TCM MTB Rif (Truenat)' OR $template == 'TCM MTB Rif INH (BDMAX)'){
				$generatesurat = view('cetak.ekspertisetbtcmmtb', $data)->render();
			} else if ($template == 'TCM XDR (Xpert)'){
				$generatesurat = view('cetak.ekspertisetbtcmxdr', $data)->render();
			} else if ($template == 'Biakan'){
				$generatesurat = view('cetak.ekspertisetbbiakan', $data)->render();
			} else {
				$generatesurat = view('cetak.ekspertisetbmikroskopis', $data)->render();
			}
		} else if ($dlp == 'CCI'){
			$generatesurat = view('cetak.ekspertisecci', $data)->render();
		} else if ($dlp == 'Kultur'){
			$generatesurat = view('cetak.ekspertisekultur', $data)->render();
		} else if ($dlp == 'Pewarna Langsung'){
			$generatesurat = view('cetak.ekspertisepl', $data)->render();
		} else if ($dlp == 'Viral Load'){
			$generatesurat = view('cetak.ekspertisevl', $data)->render();
		} else {
			$generatesurat = view('cetak.ekspertisedefault', $data)->render();
		}
		if ($tabel == 'dengan kop'){
			return $generatesurat;
		} else if ($tabel == 'PDF'){
			try {
				$info 			= array(
					'Name' 			=> 'Radiology Information System',
					'Location' 		=> 'Rumah Sakit Dr Saiful Anwar Malang',
					'Reason' 		=> 'Dokumen '.url('/').'/hasil/'.$periksa->nofoto.' ditandatangani secara elektronik pada '.$periksa->verifikasi,
					'ContactInfo'	=> $periksa->nmdokter,
				);
				$page_format 		= array(
					'MediaBox' 	=> array ('llx' => 0, 'lly' => 0, 'urx' => 210, 'ury' => 330),
					'Dur' 		=> 3,
					'PZ' 		=> 1,
				);
				PDFCREATOR::SetProtection(array('modify', 'copy'), '', null, 0, null);
				PDFCREATOR::SetCreator($periksa->nmdokter);
				PDFCREATOR::SetAuthor($periksa->nmdokter);
				PDFCREATOR::SetTitle('Hasil Pemeriksaan '.$periksa->nofoto);
				PDFCREATOR::SetSubject($periksa->reques);
				PDFCREATOR::SetKeywords($periksa->reques);
				PDFCREATOR::setPrintHeader(false);
				PDFCREATOR::setPrintFooter(false);
				PDFCREATOR::SetMargins(5, 0, 5);
				PDFCREATOR::setFontSubsetting(true);
				PDFCREATOR::setImageScale(PDF_IMAGE_SCALE_RATIO);
				PDFCREATOR::AddPage('P', $page_format, false, false);
				$bMargin = PDFCREATOR::getBreakMargin();
				$auto_page_break = PDFCREATOR::getAutoPageBreak();
				PDFCREATOR::SetAutoPageBreak(false, 0);
				PDFCREATOR::setPageMark();
				PDFCREATOR::writeHTML($generatesurat, true, 0, true, 0);
				PDFCREATOR::setCellHeightRatio(2);
				PDFCREATOR::setFooterMargin(0);
				$pdfdoc = PDFCREATOR::Output('', 'S');
				PDFCREATOR::reset();
				$ttePath = public_path('hasilpdf');
				if (!File::exists($ttePath)) {
					File::makeDirectory($ttePath, 0755, true);
				}
				Storage::disk('langsungpublic')->put('/hasilpdf/'.$periksa->nofoto.'.pdf', $pdfdoc);
				$file = public_path('hasilpdf/'.$periksa->nofoto.'.pdf');
				return response(file_get_contents($file),200)->header('Content-Type','application/pdf');
			} catch (\Exception $e) {
				Log::error('Error Generate PDF '.$periksa->id.': '.$e->getMessage());
				return $generatesurat;
			}
		} else {
			return $generatesurat;
		}
		
		
    }
    public function index() {
		if (Session::get('previlage') == ''){
			return redirect('/login');
		} else {
			$dokters    		= Dokter::all();
			$data 				= [];
			$data['dokters']   	= $dokters;
			return view('admin.dokter', $data);
		}
    }
	public function reportppds() {
		$previlage 			= Session('previlage');
		if ($previlage == 'developer' OR $previlage == 'supervisor') {
			$data = [
				'dokters' 		=> User::where('previlage', 'supervisor')->get(),
				'allppds' 		=> User::where('previlage', 'ppds')->get(),
				'allanalis' 	=> User::where('previlage', 'analis')->get(),
				'lokasi' 		=> 'Lab Mikrobiologi',
				'master' 		=> 'mikro',
				'antrkrmsitu' 	=> 0,
			];
			$allOrganisms 	= Organisms::orderBy('name', 'ASC')->get();
			$groupOrganisms = function ($kelompok) use ($allOrganisms) {
				$organisms 	= $allOrganisms->where('kelompok', $kelompok);
				if ($organisms->isEmpty()) {
					return [
						'organismes' => [[['id' => 0, 'name' => 'No Data']]],
						'categories' => ['No Data'],
					];
				}
				$grouped = $organisms->groupBy('category');
				$organismes = [];
				$categories = [];
				$i 			= 0;
				foreach ($grouped as $category => $items) {
					$categories[] = $category;
					$j = 0;
					foreach ($items as $item) {
						$organismes[$i][$j] = ['id' => $item->id, 'name' => $item->name];
						$j++;
					}
					$i++;
				}
				return [
					'organismes' => $organismes,
					'categories' => $categories,
				];
			};
			$biakankulturData = $groupOrganisms('biakankultur');
			$mikroorganismeData = $groupOrganisms('mikroorganisme');
		
			// Gabungkan data
			$data = array_merge($data, [
				'organismes' 			=> $biakankulturData['organismes'],
				'bacterycateggories' 	=> $biakankulturData['categories'],
				'mikroorganismes' 		=> $mikroorganismeData['organismes'],
				'mikroorganismestlist' 	=> $mikroorganismeData['categories'],
			]);
			$kelompokMapping = [
				'jsonsputum' 				=> 'Sputum',
				'jsonswabtenggorok' 		=> 'Swab Tenggorok',
				'jsonurine' 				=> 'Urine',
				'jsonswabperineum' 			=> 'Swab perineum',
				'jsonselepitel' 			=> 'Sel Epitel',
				'jsonselradang' 			=> 'Sel Radang',
				'jsonmikroorganisme' 		=> 'Q Mikroorganisme',
				'jsonjumlahlactobacillus' 	=> 'Lactobacillus',
				'jsonjumlahgardnerella' 	=> 'Gardnerella',
				'jsonjumlahmobiluncus' 		=> 'Mobiluncus',
				'jsonpewarnaanziehlnielsen' => 'Pewarnaan Ziehl Nielsen',
				'jsonpewarnaanneisser' 		=> 'Pewarnaan Neisser',
				'jsonpewarnaannegatif' 		=> 'Pewarnaan Negatif',
				'jsonpewarnaanspora' 		=> 'Pewarnaan Spora',
				'jsonmediabap' 				=> 'Media BAP',
				'jsonmediacap' 				=> 'Media CAP',
				'jsonmediamcconkey' 		=> 'Media Mc Conkey',
				'jsonpemeriksaantl' 		=> 'Pemeriksaan Tambahan Lainnya',
				'jsonbiakankultur'	 		=> 'Biakan Kultur',
			];
			foreach ($kelompokMapping as $key => $kelompok) {
				$data[$key] = $allOrganisms->where('kelompok', $kelompok)->values();
			}
			return view('dokter.pemeriksaan', $data);
		} else {
        	$data                       = [];
            $data['kalimatheader']  	= 'Access Denied';
            $data['kalimatbody']  		= 'Laman khusus SPV';
            return view('errors.error', $data);
		}
    }
	public function getListadendum(Request $request) {
		$arraylist 	= [];
		$dokterid 	= Session('id');
		$lists		= DB::table('riwayatjawaban')
							->select('periksa.*', 'riwayatjawaban.id as idriwayat', 'riwayatjawaban.jawaban', 'riwayatjawaban.inputor as inputoradendum',  'riwayatjawaban.created_at as createdadendum')
							->leftJoin('periksa', 'riwayatjawaban.nofoto', 'periksa.nofoto')
							->whereNull('riwayatjawaban.verifikasi')
							->get();
		echo json_encode($lists);
    }
    public function store(Request $request) {
        $old_date 	= 	$request->input('tgl_lahir');
		$nama 		= 	$request->input('nama');
		$jk 		= 	$request->input('jk');
		$tgl_lahir 	= 	$request->input('tgl_lahir');
		$kota 		= 	$request->input('kota');
		$alamat 	= 	$request->input('alamat');
        $date 		= 	date("Y-m-d", strtotime($old_date));
		Session::flash('message', 'Insert New Data Only On User Management, This Page Limited to Update Only'); 
		Session::flash('alert-class', 'alert-danger');
		return back();
    	
    }
    public function getDokter(Request $request) {
        $id         =   $request->input('id');
        $result     =   User::where('id', $id)->first();
        echo json_encode($result);
    }
    public function update(Request $request) {
		$nama       =   $request->input('nama');
        $jk   		=   $request->input('jk');
		$tgl_lahir  =   $request->input('tgl_lahir');
		$alamat   	=   $request->input('alamat');
        if ($nama == '' OR $jk == '' OR $tgl_lahir == '' OR $alamat == ''){
          return response()->json(['status' => 'error', 'message' => 'Please fill input field or fill with right input']);
        } else {
            $id         =   $request->input('id_dokter');
            $old_date   =   $request->input('tgl_lahir');
            $date       =   date("Y-m-d", strtotime($old_date));
            Dokter::where('id', $id)->update([
                'nama'          =>  $request->input('nama'),
                'jk'            =>  $request->input('jk'),
                'tgl_lahir'     =>  $date,
                'kota'          =>  $request->input('kota'),
                'alamat'        =>  $request->input('alamat')
            ]);

            Session::flash('message', 'Data berhasil disimpan'); 
            Session::flash('alert-class', 'alert-success');

            return back();
        }
    }
    public function delete(Request $request) {
        $id         = $request->dokter_id;
        $dokter     = Dokter::find($id);
        $dokter->delete();
        return back();
    }
	public function exUploader(Request $request) {
		$val01 		= $request->input('val01');
		$val03 		= $request->input('val03');
		$val04 		= $request->input('val04');
		$val05 		= $request->input('val05');
        if ($val01 == '' OR $val03 == '' OR $val04 == '' OR $val05 == ''){
			return response()->json(['icon' => 'error', 'warna' => '#bf441d', 'status' => 'Gagal', 'message' => 'Mohon isi semua form']);
			return back();
        } else {
			$id 		= $request->input('val01');
			$jenis 		= $request->input('val03');
			$judul 		= $request->input('val04');
			$nofoto 	= $request->input('val05');
			if ($jenis == 'hapus'){
				$periksa 	= Filefoto::where('id', $id)->first();
				if (isset($periksa->namafile)){
					$filefoto	= $periksa->namafile;
					if (File::exists(base_path()) ."/public/foto/". $filefoto) {
						File::delete(base_path() ."/public/foto/". $filefoto);
						Filefoto::where('id', $id)->delete();
						return response()->json(['icon' => 'success', 'warna' => '#5ba035', 'status' => 'Sukses', 'message' => 'Pic '.$filefoto.' Deleted']);
						return back();
					} else {
						return response()->json(['icon' => 'error', 'warna' => '#bf441d', 'status' => 'Gagal', 'message' => 'File Not Found']);
						return back();
					}
				} else {
					return response()->json(['icon' => 'error', 'warna' => '#bf441d', 'status' => 'Gagal', 'message' => 'Nothing to remove']);
					return back();
				}
			} else {
				$jenfile	= $request->file->getClientOriginalExtension();
				$file   	= $id.'-'.time().'.'.$request->file->getClientOriginalExtension();
				$request->file->move(public_path('foto'), $file);
				$filename 	= $file;
				$input		= Filefoto::create([
					'nofoto'	=> $nofoto,
					'namafile'	=> $filename,
					'jenisfile'	=> $jenfile,
					'judul'		=> $judul
				]);
				if ($input){
					return response()->json(['icon' => 'success', 'warna' => '#5ba035', 'status' => 'Sukses', 'message' => 'Pic. Uploaded']);
					return back();
				}else {
					return response()->json(['icon' => 'error', 'warna' => '#bf441d', 'status' => 'Gagal', 'message' => 'System Down, please try again in a few years...']);
					return back();
				}
			}
        }
    }
	public function exexpertisePacs(Request $request) {
		$keterangan 	= $request->input('keterangan');
		$kesimpulan 	= $request->input('kesimpulan');
		$iddokter 		= $request->input('dokter');
		$jumlah			= $kesimpulan;
		$kesimpulan		= '';
		if ($iddokter == 'Pilih' OR $iddokter == ''){
			return response()->json(['icon' => 'error', 'warna' => '#bf441d', 'status' => 'Error..!!', 'message' => 'Please Select Doctor Names']);
			return back();
		} else {
			$idperiksa 		= $request->input('periksa_id');
			$nofoto 		= $request->input('nofoto');
			$ruangan 		= $request->input('ruangan');
			$kerja 			= $request->input('val01');
			$jenisfont 		= $request->input('val07');
			$modality 		= $request->input('val09');
			$dlp 			= $request->input('val10');
			$ppds1 			= $request->input('val11');
			$ppds2 			= $request->input('val12');
			$ppds3 			= $request->input('val13');
			$berat 			= $request->input('val16');
			$klinis 		= $request->input('val17');
			$klinisi 		= $request->input('val18');
			$diagnosa2 		= $request->input('val19');
			$otheras 		= $request->input('val20');
			$otherppds 		= $request->input('val21');
			$analis 		= $request->input('analis');
			if ($keterangan != ''){
				KomponenJawaban::updateOrCreate(
					[
						'accnumber'		=> $nofoto,
						'template'		=> $dlp,
						'komponen'		=> 'keterangan',
					],
					[
						'isidata'		=> $keterangan,
						'created_by'	=> Session('nama')
					]
				);
			}
			
			$today 			= date('Y-m-d H:i:s');
			$periksa 		= Periksa::with(['getPasien', 'getPoli'])->find($idperiksa);
			$cekdokter 		= optional(User::find($iddokter));
			$cekanalis 		= optional(User::find($analis));
			$cekppds1 		= optional(User::find($ppds1));
			$cekppds2 		= optional(User::find($ppds2));
			$cekppds3 		= optional(User::find($ppds3));
			if ($otherppds) {
				$cekOtherPPDS = User::where('nama', $otherppds)->first();
				if ($cekOtherPPDS) {
					$otherppdsId = $cekOtherPPDS->id;
					$updateData['ppdsjunior2'] = ($otheras === 'Junior') ? $otherppdsId : 0;
					$updateData['ppdsmiddle2'] = ($otheras === 'Middle') ? $otherppdsId : 0;
					$periksa->update([
						'nmppdsjunior2' => $otheras === 'Junior' ? $cekOtherPPDS->nama : null,
						'nmppdsmiddle2' => $otheras === 'Middle' ? $cekOtherPPDS->nama : null,
					]);
				}
			}
			switch ($kerja) {
				case 'verifikasi':
					$updateData 	= [
						'keterangan' 	=> $keterangan,
						'dlp'			=> $dlp,
						'analis' 		=> $analis,
						'nmanalis' 		=> $cekanalis->nama ?? null,
						'dokter_id' 	=> $iddokter,
						'nmdokter' 		=> $cekdokter->nama ?? null,
						'ppdsjunior' 	=> $ppds1,
						'nmppdsjunior' 	=> $cekppds1->nama ?? null,
						'middleppds' 	=> $ppds2,
						'nmmiddleppds' 	=> $cekppds2->nama ?? null,
						'ppdssenior' 	=> $ppds3,
						'nmppdssenior' 	=> $cekppds3->nama ?? null,
						'tandatangan' 	=> $cekdokter->tandatangan ?? '',
						'verifikasi' 	=> $today,
						'nmexcutor'		=> Session('nama'),
						'excutor'		=> Session('id'),
						'status' 		=> 'Selesai',
					];
					$periksa->update($updateData);
					$surat 			= self::genSurat($periksa->id, 'dengan kop');
					Riwayat::create([
						'nofoto' 		=> $nofoto,
						'jawaban' 		=> $surat,
						'inputor' 		=> Session('nama'),
						'verifikasi' 	=> 'Accepted',
						'keterangan' 	=> 'Expertise',
					]);
					if (is_null($nofoto)){
						return response()->json(['icon' => 'success', 'warna' => '#5ba035', 'status' => 'Sukses', 'message' => 'Expertise Verified']);
					} else {
						$pesan = 'Expertise Saved';
						return response()->json(['icon' => 'success', 'warna' => '#5ba035', 'status' => 'Sukses', 'message' => $pesan]);
					}
				case 'Permohonan Verifikasi':
					$updateData 	= [
						'keterangan' 	=> $keterangan,
						'dlp'			=> $dlp,
						'analis' 		=> $analis,
						'nmanalis' 		=> $cekanalis->nama ?? null,
						'dokter_id' 	=> $iddokter,
						'nmdokter' 		=> $cekdokter->nama ?? null,
						'ppdsjunior' 	=> $ppds1,
						'nmppdsjunior' 	=> $cekppds1->nama ?? null,
						'middleppds' 	=> $ppds2,
						'nmmiddleppds' 	=> $cekppds2->nama ?? null,
						'ppdssenior' 	=> $ppds3,
						'nmppdssenior' 	=> $cekppds3->nama ?? null,
						'tandatangan' 	=> $cekdokter->tandatangan ?? '',
						'baca' 			=> $today,
						'nmexcutor'		=> Session('nama'),
						'excutor'		=> Session('id'),
						'nmpembaca'		=> Session('nama'),
						'status' 		=> 'Expertise Saved (Un Verified)',
					];
					$periksa->update($updateData);
					$surat 			= self::genSurat($periksa->id, 'dengan kop');
					Riwayat::create([
						'nofoto' 		=> $nofoto,
						'jawaban' 		=> $surat,
						'inputor' 		=> Session('nama'),
						'verifikasi' 	=> 'Accepted',
						'keterangan' 	=> 'Kirim ke SPV',
					]);
					return response()->json(['icon' => 'success', 'warna' => '#5ba035', 'status' => 'Sukses', 'message' => 'Permohonan Verifikasi Terkirim']);
					
				case 'tolakadendum':
					Riwayat::where('nofoto', $nofoto)->whereNull('verifikasi')->update([
						'verifikasi' 	=> 'Declined',
					]);
					return response()->json(['icon' => 'success', 'status' => 'Success', 'message' => 'Addendum Declined']);
				case 'terimadendum':
					$getid = Riwayat::where('keterangan', 'Adendum')->where('nofoto', $nofoto)->whereNull('verifikasi')->first();
					if (isset($getid->id)){
						Riwayat::where('id', $getid->id)->update([
							'verifikasi' 	=> 'Accepted',
						]);
						Periksa::where('nofoto', $getid->nofoto)->update([
							'nmexcutor'		=> Session('nama'),
							'excutor'		=> Session('id'),
							'tgladendum' 	=> now(),
							'keterangan'	=> $getid->jawaban
						]);
						return response()->json(['icon' => 'success', 'status' => 'Success', 'message' => 'Addendum Accepted']);
					} else {
						return response()->json(['icon' => 'error', 'status' => 'Gagal', 'message' => 'Addendum Data Cannot Be Found']);
					}
				default:
					$periksa->update([
						'keterangan' 	=> $keterangan,
						'kesimpulan' 	=> $kesimpulan,
						'dlp'			=> $dlp,
						'analis' 		=> $analis,
						'nmanalis' 		=> $cekanalis->nama ?? null,
						'dokter_id' 	=> $iddokter,
						'nmdokter' 		=> $cekdokter->nama ?? null,
						'ppdsjunior' 	=> $ppds1,
						'nmppdsjunior' 	=> $cekppds1->nama ?? null,
						'middleppds' 	=> $ppds2,
						'nmmiddleppds' 	=> $cekppds2->nama ?? null,
						'ppdssenior' 	=> $ppds3,
						'nmppdssenior' 	=> $cekppds3->nama ?? null,
						'tgldraft' 		=> $today,
						'nmdrafter'		=> Session('nama'),
						'nmexcutor'		=> Session('nama'),
						'excutor'		=> Session('id'),
						'status' 		=> 'Proses Analisis Sampel'
					]);
					return response()->json(['icon' => 'success', 'status' => 'Success', 'message' => 'Expertise Saved']);
			}
		}
    }
	public function cancelOrder(Request $request) {
		$val01 		= $request->input('alasan');
		$getsetting	= Setting::where('id', '1')->first();
		$pacsaddr	= $getsetting->pacs ?? '';
		$zfpaddr	= $getsetting->zfp ?? '';
		$port		= $getsetting->port ?? '';
		$idperiksa	= $request->input('nolab');
		Periksa::where('id', $idperiksa)->orWhere('nofoto', $idperiksa)->update([
			'keterangan'	=> 	$val01,
			'admin'			=> 	Session('nama'),
			'status' 		=> 	'Batal'
		]);
		if ($pacsaddr == '' OR $pacsaddr === null){
			$pesan = '';
		} else {
			$pesan = $this->Hl7SendCancel($idperiksa, $pacsaddr);
		}
		if ($pesan == '' OR $pesan == 'Send Cancel Order Success'){
			return response()->json(['icon' => 'success', 'warna' => '#5ba035', 'status' => 'Success', 'message' => 'Send Cancel Order Success']);
			return back();
		} else {
			return response()->json(['icon' => 'error', 'warna' => '#bf441d', 'status' => 'Gagal', 'message' => 'Error '.$pesan]);
			return back();
		}
    }
	public function sendOrder(Request $request) {
		$val09 		= $request->input('val09');
		$dokter 	= $request->input('dokter');
		$ruangan 	= $request->input('ruangan');
		if($val09 == '' OR $dokter == '' OR $ruangan == ''){
			return response()->json(['icon' => 'error', 'warna' => '#bf441d', 'status' => 'Error..!!', 'message' => 'Nama Dokter, Modality dan Ruangan Wajib di Isi']);
			return back();
        } else {
			$emailbody		= '';
			$idperiksa 		= $request->input('periksa_id');
			$nofoto 		= $request->input('nofoto');
			$ruangan 		= $request->input('ruangan');
			$iddokter 		= $request->input('dokter');
			$worklist 		= $request->input('keterangan');
			$jumlah 		= $request->input('kesimpulan');
			$tanggal 		= $request->input('val01');
			$rekuese 		= $request->input('val07');
			$modality 		= $request->input('val09');
			$dlp 			= $request->input('val10');
			$berat 			= $request->input('val11');
			$klinisi 		= $request->input('val12');
			$klinis 		= $request->input('val13');
			if ($iddokter == 'Pilih' OR $iddokter == ''){
				return response()->json(['icon' => 'error', 'warna' => '#bf441d', 'status' => 'Error..!!', 'message' => 'Please Select Doctor Names']);
				return back();
			}
			else {
				$periksa 	= Periksa::where('id', $idperiksa)->first();
				$idpasien	= $periksa->pasien_id;
				$keterangan	= $periksa->keterangan;
				$daftar 	= $periksa->daftar;
				$idruang 	= $periksa->ruangan_id;
				$kamar 		= $periksa->ruangan;
				$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;
				$kirimemail	= 'TIDAK';
				$ex_nofoto	= substr($nofoto, 8);
				$kamar   	= $periksa->getRuangan->poli ?? 'Deleted Data Ruang';
				$diagnosa	= $periksa->getLogbook->kepanjangan ?? $periksa->diagnosa;
				$tandatangan= $periksa->getTandatangan->tandatangan ?? url('/').'/boxed-bg.png';
				$dokter		= $periksa->nmdokter ?? 'Dokter Penanggung Jawab';
				$tanggal 	= date("Y-m-d H:i:s");
				if ($statuse == 'Selesai' OR $statuse == 'Arsip'){
					Periksa::where('id', $idperiksa)->update([
						'ruangan_id' 	=> $ruangan,
						'ruangan' 		=> $kamar,
						'dokter_id' 	=> $iddokter,
						'berat' 		=> $berat,
						'klinisi' 		=> $klinisi,
						'klinis' 		=> $klinis,
						'dlp'			=> $dlp,
						'modality'		=> $modality,
						'jumlah'		=> $jumlah,
						'foto' 			=> $tanggal,
						'nmanalis'		=> Session('nama'),
						'analis'		=> Session('id'),
					]);
				} else {
					Periksa::where('id', $idperiksa)->update([
						'ruangan_id' 	=> $ruangan,
						'ruangan' 		=> $kamar,
						'dokter_id' 	=> $iddokter,
						'berat' 		=> $berat,
						'klinisi' 		=> $klinisi,
						'klinis' 		=> $klinis,
						'dlp'			=> $dlp,
						'modality'		=> $modality,
						'jumlah'		=> $jumlah,
						'analis'		=> Session('id'),
						'nmanalis'		=> Session('nama'),
						'foto' 			=> $tanggal,
						'status'		=> 'Telah di kirim ke worklist/modalitas',
						'excutor'		=> null,
					]);
					Periksa::where('noregister', $noregister)
						->where('daftar', $daftar)
						->where('status', 'LIKE', '%Diperiksa%')
						->where('id', '!=', $idperiksa)
						->update([
							'status' 	=> null,
							'excutor' 	=> null,
						]);
					$kirimemail	= 'YES';
				}
				$today 		= str_replace('-', '', $tanggal);
				$today 		= str_replace(':', '', $today);
				$today 		= str_replace(' ', '', $today);
				
				$arrayttl 	= explode("-", $nofoto);
				$jenis 		= $arrayttl[0];
				$jk 		= $periksa->jkpasien;
				$tgllahir	= $periksa->tgllahirpasien;
				$kota 		= '';
				$alamat 	= $periksa->alamatpasien;
				$nama 		= $periksa->nmpasien;
				$norm 		= $periksa->noregister;
				$poli		= $periksa->getPoli->poli ?? 'EMI Primary';
				$tgllahir 	= str_replace('-', '', $tgllahir);
				$arrayttl 	= explode(" ", $nama);
				$blakang	= '';
				$tengah		= '';
				$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 	= '';
				//PV1.2 = value nya I (Inpatient), O (Outpatient), E (Emergency).
				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; }
				if ($worklist == 'pacs'){
					$getsetting		= Setting::where('id', '1')->first();
					$pacsaddr		= $getsetting->pacs;
					$port			= $getsetting->port;
					//$recievingfas	= 'OESEND_PROD';
					$portupdate		= '10020';
				} else {
					$getsetting		= Worklist::where('id', $worklist)->first();
					if (isset($getsetting->ipaddress)){
						$pacsaddr		= $getsetting->ipaddress;
						$port			= $getsetting->portnumber;
						$portupdate		= $getsetting->portnumber;
						//$recievingfas	= $getsetting->aetitle;
					} else{
						$getsetting		= Setting::where('id', '1')->first();
						$pacsaddr		= $getsetting->pacs;
						$port			= $getsetting->port;
						//$recievingfas	= 'OESEND_PROD';
						$portupdate		= '10020';
					}
				}
				$recievingfas	= 'OESEND_PROD';
				if (is_null($foto)){
					$msg = new Message();
					$msh = new MSH();
					//$msh->setField(1, '|');
					//$msh->setField(2, '^~\&');
					$msh->setField(3, 'RIS');
					$msh->setField(4, 'RSSA MALANG');
					//$msh->setField(5, $recievingfas);
					$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(16, $klinis);
					$orc->setField(17, 'Radiologi RSSA');
					$msg->addSegment($orc);
					
					$obr = new OBR();
					$obr->setField(2, [$nofoto, $poli]);
					$obr->setField(3, [$nofoto, $poli]);
					$obr->setField(4, [$modality, $rekuese, $poli]);
					$obr->setField(5, $prioritas);
					$obr->setField(6, $today);
					$obr->setField(16, [$iddokter, $dokter]);
					$obr->setField(18, $nofoto);
					$obr->setField(19, $modality);
					$obr->setField(21, $modality);
					$obr->setField(24, $modality);
					$obr->setField(27, ['1', 'once', $tanggal, $prioritas]);
					$obr->setField(36, $today);
					$msg->addSegment($obr);
					$result = null;
					$tes 	= 'tcp://'.$pacsaddr.':'.$port;
					try {
						$fp 	= stream_socket_client($tes, $errno, $errstr, 1);
					}catch (Exception $e) {
						$result = $e->getMessage();
					}
					if ($result !== null AND strpos($result, 'unable to connect') !== false) {
						return response()->json(['icon' => 'error', 'warna' => '#bf441d', 'status' => 'Connect to PACS Failed', 'message' => 'Saved to RIS Only']);
						return back();
					} else {
						$connection = new Connection($pacsaddr, $port);
						$ack 		= $connection->send($msg);
						$hasilkrm 	= $ack->toString(true);
						$msa 		= $ack->getSegmentsByName('MSA')[0];
						$ackCode 	= $msa->getAcknowledgementCode();
						if ($ackCode[1] === 'A') {
							$emailbody = 'Pasien atas nama '.$nama.' Dengan Order Pemeriksaan '.$rekuese.' Dari '.$asalpasien.' Terkirim ke Modality';
							$pesan 		= SendMail::mobilenotif('all', 'ppds', 'Pasien Terkirim ke PACS', $emailbody);
							return response()->json(['icon' => 'success', 'warna' => '#5ba035', 'status' => 'Sukses', 'message' => $pesan.'<br />'.$emailbody]);
							return back();
						}
						else {
							$pesan = "Error text: " . $msa->getTextMessage();
							return response()->json(['icon' => 'error', 'warna' => '#bf441d', 'status' => 'Error..!!', 'message' => $pesan]);
							return back();
						}
					}
				} else {
					$msg = new Message();
					$msh = new MSH();
					$msh->setField(3, 'RIS');
					$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);
					$result = null;
					$portupdate = '10020';
					$tes 	= 'tcp://'.$pacsaddr.':'.$portupdate;
					try {
						$fp 	= stream_socket_client($tes, $errno, $errstr, 1);
					}catch (Exception $e) {
						$result = $e->getMessage();
					}
					if ($result !== null AND strpos($result, 'unable to connect') !== false) {
						return response()->json(['icon' => 'error', 'warna' => '#bf441d', 'status' => 'Connect to PACS Failed', 'message' => 'Saved to RIS Only']);
						return back();
					} else {
						$connection = new Connection($pacsaddr, $portupdate);
						$ack 		= $connection->send($msg);
						$msa 		= $ack->getSegmentsByName('MSA')[0];
						$ackCode 	= $msa->getAcknowledgementCode();
						if ($ackCode[1] === 'A') {
							$emailbody 	= 'Pasien atas nama '.$nama.' Dengan Order Pemeriksaan '.$rekuese.' Dari '.$asalpasien.' Terupdate ke Modality';
							$pesan 		= SendMail::mobilenotif('all', 'ppds', 'Pasien Terkirim ke PACS', $emailbody);
							return response()->json(['icon' => 'success', 'warna' => '#5ba035', 'status' => 'Sukses', 'message' => $pesan.'<br />'.$emailbody]);
							return back();
						}
						else {
							$pesan = "Error text: " . $msa->getTextMessage();
							return response()->json(['icon' => 'error', 'warna' => '#bf441d', 'status' => 'Error..!!', 'message' => $pesan]);
							return back();
						}
					}
				}
			}
		}
    }
	public function getResult(Request $request) {
		$emailbody		= '';
		$idperiksa 		= $request->input('periksa_id');
		$nofoto 		= $request->input('nofoto');
		$ruangan 		= $request->input('ruangan');
		$iddokter 		= $request->input('dokter');
		$worklist 		= $request->input('keterangan');
		$jumlah 		= $request->input('kesimpulan');
		$tanggal 		= $request->input('val01');
		$rekuese 		= $request->input('val07');
		$modality 		= $request->input('val09');
		$dlp 			= $request->input('val10');
		$berat 			= $request->input('val11');
		$klinisi 		= $request->input('val12');
		$klinis 		= $request->input('val13');
		if ($worklist == 'getkomponenjawaban'){
			$cekdatanmaddendum 	= Periksa::where('nofoto', $nofoto)->first();
			$getdatapasangannya = Periksa::whereNotNull('nmadendum')->where('dlp', '!=', $ruangan)->where('daftar', $cekdatanmaddendum->daftar)->where('nofoto', '!=', $nofoto)->get();
			foreach ($getdatapasangannya as $item){
				$datayangperludicloning = KomponenJawaban::where('accnumber', $item->nofoto)->get();
				foreach ($datayangperludicloning as $rclone){
					$ceksudahcloning = KomponenJawaban::where('accnumber', $nofoto)
									->where('komponen', $rclone->komponen)
									->where('template', $ruangan)->count();
					if ($ceksudahcloning == 0){
						$komponen = '';
						if ($rclone->komponen == 'lsg_selepitel'){
							$komponen = 'id_selepitel';
						}
						if ($rclone->komponen == 'id_selepitel'){
							$komponen = 'lsg_selepitel';
						}
						if ($rclone->komponen == 'lsg_selradang'){
							$komponen = 'id_selradang';
						}
						if ($rclone->komponen == 'id_selradang'){
							$komponen = 'lsg_selradang';
						}
						if ($rclone->komponen == 'lsg_mikroorganisme'){
							$komponen = 'id_mikroorganisme';
						}
						if ($rclone->komponen == 'id_mikroorganisme'){
							$komponen = 'lsg_mikroorganisme';
						}
						if ($rclone->komponen == 'lsg_mikroorganismeoptional'){
							$komponen = 'id_mikroorganismeoptional';
						}
						if ($rclone->komponen == 'id_mikroorganismeoptional'){
							$komponen = 'lsg_mikroorganismeoptional';
						}
						if ($rclone->komponen == 'lsg_mikroorganismeoptional'){
							$komponen = 'id_mikroorganismeoptional';
						}
						if ($rclone->komponen == 'id_mikroorganismeoptional'){
							$komponen = 'lsg_mikroorganismeoptional';
						}
						if ($komponen != ''){
							KomponenJawaban::create([
								'accnumber'		=> $nofoto,
								'template'		=> $ruangan,
								'komponen'		=> $komponen,
								'isidata'		=> $rclone->isidata,
								'created_by'	=> Session('nama')
							]);
						}
						
					}
				}
			}
			$getkomponen		= KomponenJawaban::where('accnumber', $nofoto)->where('template', $ruangan)->get();
			return response()->json(['komponens' => $getkomponen]);
			return back();
		} else if ($worklist == 'isikomponenjawaban'){
			try {
				KomponenJawaban::updateOrCreate(
					[
						'accnumber'		=> $nofoto,
						'template'		=> $request->input('jenis'),
						'komponen'		=> $request->input('komponen'),
					],
					[
						'isidata'		=> $request->input('isi'),
						'created_by'	=> Session('nama')
					]
				);
				if ($request->input('komponen') == 'id_jenispemeriksaantb'){
					Periksa::where('nofoto', $nofoto)->update([
						'diagnosa2'	=> $request->input('isi')
					]);
				}
				Periksa::where('nofoto', $nofoto)->update([
					'dlp'	=> $request->input('jenis')
				]);
				$pesan = $nofoto.' Saved '.$request->input('jenis');
			}catch (Exception $e) {
				$pesan 	= $e->getMessage();
			}
			return $pesan;
		} else if ($worklist == 'isandasar'){
			try {
				$dokter_id 		= 0;
				$analis			= 0;
				$ppds3			= 0;
				$nmanalis		= '';
				$nmdokter 		= '';
				$nmppdssenior 	= '';
				if ($request->input('komponen') == 'analis' OR $request->input('komponen') == 'ppds3' OR $request->input('komponen') == 'dokter'){
					if ($request->input('isi') != 0){
						if ($request->input('komponen') == 'analis'){
							$analis		= $request->input('isi');
							$getnama 	= User::where('id', $analis)->first();
							Periksa::where('nofoto', $nofoto)->update([
								'analis'	=> $analis,
								'nmanalis'	=> $getnama->nama ?? ''
							]);
						} else if ($request->input('komponen') == 'ppds3'){
							$ppds3		= $request->input('isi');
							$getnama 	= User::where('id', $ppds3)->first();
							Periksa::where('nofoto', $nofoto)->update([
								'ppdssenior'	=> $ppds3,
								'nmppdssenior'	=> $getnama->nama ?? ''
							]);
						} else {
							$dokter_id 	= $request->input('isi');
							$getnama 	= User::where('id', $dokter_id)->first();
							Periksa::where('nofoto', $nofoto)->update([
								'dokter_id'	=> $dokter_id,
								'nmdokter'	=> $getnama->nama ?? ''
							]);
						}
					} else {
						if ($request->input('komponen') == 'analis'){
							Periksa::where('nofoto', $nofoto)->update([
								'analis'		=> 0,
								'nmanalis'		=> '',
								'nmdrafter'		=> Session('nama'),
							]);
						} else if ($request->input('komponen') == 'ppds3'){
							Periksa::where('nofoto', $nofoto)->update([
								'ppdssenior'	=> 0,
								'nmppdssenior'	=> '',
								'nmdrafter'		=> Session('nama'),
							]);
						} else {
							Periksa::where('nofoto', $nofoto)->update([
								'dokter_id'		=> 0,
								'nmdokter'		=> '',
								'nmdrafter'		=> Session('nama'),
							]);
						}
					}
				} else if ($request->input('komponen') == 'klinis'){
					Periksa::where('nofoto', $nofoto)->update([
						'klinis'			=> $request->input('isi'),
					]);
				} else if ($request->input('komponen') == 'bhp_media'){
					Periksa::where('nofoto', $nofoto)->update([
						'bhp_media'			=> $request->input('isi'),
					]);
				} else if ($request->input('komponen') == 'bhp_potsputum'){
					Periksa::where('nofoto', $nofoto)->update([
						'bhp_potsputum'		=> $request->input('isi'),
					]);
				} else if ($request->input('komponen') == 'bhp_poturine'){
					Periksa::where('nofoto', $nofoto)->update([
						'bhp_poturine'		=> $request->input('isi'),
					]);
				} else if ($request->input('komponen') == 'bhp_oshe'){
					Periksa::where('nofoto', $nofoto)->update([
						'bhp_oshe'			=> $request->input('isi'),
					]);
				} else if ($request->input('komponen') == 'bhp_obyekglass'){
					Periksa::where('nofoto', $nofoto)->update([
						'bhp_obyekglass'	=> $request->input('isi'),
					]);
				} else if ($request->input('komponen') == 'bhp_botolbd'){
					Periksa::where('nofoto', $nofoto)->update([
						'bhp_botolbd'		=> $request->input('isi'),
					]);
				} else if ($request->input('komponen') == 'bhp_parafilm'){
					Periksa::where('nofoto', $nofoto)->update([
						'bhp_parafilm'		=> $request->input('isi'),
					]);
				} else if ($request->input('komponen') == 'bhp_tips'){
					Periksa::where('nofoto', $nofoto)->update([
						'bhp_tips'			=> $request->input('isi'),
					]);
				} else if ($request->input('komponen') == 'bhp_cottonswab'){
					Periksa::where('nofoto', $nofoto)->update([
						'bhp_cottonswab'	=> $request->input('isi'),
					]);
				} else if ($request->input('komponen') == 'id_esbl'){
					Periksa::where('nofoto', $nofoto)->update([
						'id_esbl'	=> $request->input('isi'),
					]);
				} else if ($request->input('komponen') == 'id_mrsa'){
					Periksa::where('nofoto', $nofoto)->update([
						'id_mrsa'	=> $request->input('isi'),
					]);
				} else {
					Periksa::where('nofoto', $nofoto)->update([
						'bhp_antibiotiktambahan'	=> $request->input('isi'),
					]);
				}
				KomponenJawaban::updateOrCreate(
					[
						'accnumber'		=> $nofoto,
						'template'		=> $request->input('jenis'),
						'komponen'		=> $request->input('komponen'),
					],
					[
						'isidata'		=> $request->input('isi'),
						'created_by'	=> Session('nama')
					]
				);
				$pesan = $nofoto.' Saved '.$request->input('jenis');
			} catch (Exception $e) {
				$pesan 	= $e->getMessage();
			}
			return $pesan;
		} else if ($worklist == 'mappingalat'){
			try {
				Periksa::where('nofoto', $nofoto)->update([
					'modality'	=> $request->input('isi')
				]);
				$isi 		= 	$request->input('isi');
				$cekdata	= 	Periksa::where('nofoto', $nofoto)->first();
				$daftar		= 	$cekdata->daftar;
				$gettgl 	= 	explode(' ', $daftar);
				$tanggal 	= 	$gettgl[0];
				$getarrtgl 	= 	explode('-', $tanggal);
				$yy 		= 	$getarrtgl[0];
				$mm 		= 	$getarrtgl[1] ?? '00';
				$dd 		= 	$getarrtgl[2] ?? '00';
				$date 		= 	new DateTime($tanggal);
				$thnpendek 	= 	$date->format('y');
				$vitek 		= 	$dd.$mm.$yy.'-'.$cekdata->noloket;
				$bd 		= 	$thnpendek.'-'.$cekdata->noloket;
				$abbot 		= 	$yy.$mm.$dd.'-'.$cekdata->noloket;
				$data		= json_decode($isi);
				foreach($data as $alat){
					/*
					if ($alat == 'Vitek 1' OR $alat == 'Vitek 2'){
						$nofoto = $vitek;
					} else if ($alat == 'BD Bachtect' OR $alat == 'BD MGIT'){
						$nofoto = $bd;
					} else if ($alat == 'abbotm2000' || $alat == 'abbotm2000rt'){
						$nofoto = $abbot;
					} else {
					}
					*/
					PendaftaranOnListiner::updateOrCreate(
						[
							'rnoreg'	=> $nofoto,
							'regid'		=> $cekdata->id,
						],
						[
							'rtglast'		=> date('Y-m-d'),
							'norm'			=> $cekdata->noregister,
							'nama'			=> $cekdata->nmpasien,
							'alamat'		=> $cekdata->alamatpasien,
							'telp'			=> $cekdata->tlppasien,
							'hp'			=> $cekdata->tlppasien,
							'tgllahir'		=> $cekdata->tgllahirpasien,
							'umur'			=> $cekdata->usia,
							'bl_th'			=> '',
							'rjenis'		=> $cekdata->jkpasien,
							'kodedok'		=> $cekdata->dokter_id,
							'namadok'		=> $cekdata->nmdokter,
							'ruangan'		=> $cekdata->ruangan,
							'tes'			=> $cekdata->reques,
							'alat'			=> $alat,
							'kd_spesimen'	=> $cekdata->kd_spesimen,
							'nm_spesimen'	=> $cekdata->nm_spesimen,
						]
					);
				}
				$pesan 	= 'saved';
			} catch (Exception $e) {
				$pesan 	= $e->getMessage();
			}
			return $pesan;
		} else if ($worklist == 'arsipkan'){
			try {
				Periksa::where('created_at', 'LIKE', $request->input('isi').'%')->update([
					'status'=> 	'Arsip'
				]);
				$pesan = 'Sejumlah data di rentang '.$request->input('isi').' Berhasil di arsipkan';
			} catch (Exception $e) {
				$pesan 	= $e->getMessage();
				Log::error('Gagal Arsipkan Data.', [
					'message'    => $e->getMessage(), 
				]);
			}
			return $pesan;
		} else if ($worklist == 'getvitek'){
			$isidata 		= $request->input('isi');
			$getdataawal 	= Periksa::where('nofoto', $nofoto)->first();
			$orderid 		= $getdataawal->id ?? 0;
			$ketemu 		= '';
			$organism 		= '';
			$nomor 			= 1;
			$jsonantibiotik = array(
				'Oxacillin-OX',
				'Cefoxitin-FOX',
				'Benzylpenicillin-P',
				'Ampicillin-AM',
				'Azithromycin-AZM',
				'Erythromycin-ERY',
				'Cefazolin-CZO',
				'Cefepime-FEP',
				'Cefixime-CFM',
				'Cefotaxime-CTX',
				'Cefuroxime-CXM',
				'Ceftazidime-CAZ',
				'Ceftriaxone-CRO',
				'Ceftazidime/Avibactam-CZA',
				'Piperacilin/Tazobactam-TZP',
				'Ampicillin/Sulbactam-SAM',
				'Amoxicillin/Clavulanate-AMC',
				'Cefoperazon/Sulbactam-SCF',
				'Aztreonam-ATM',
				'Ceftaroline-CPT',
				'Ciprofloxacin-CIP',
				'Levofloxacin-LEV',
				'Moxifloxacin-MFX',
				'Clindamycin-CLI',
				'Colistin-CS',
				'Tetracyclin-TCY',
				'Tigecycline-TGC',
				'Gentamicin-GM',
				'Amikacin-AN',
				'Meropenem-MEM',
				'Imipenem-IPM',
				'Doripenem-DOR',
				'Ertapenem-ETP',
				'Minocycline-MNO',
				'Doxycycline-DOX',
				'Spectinomycin-SPT',
				'Tigecycline-TGC',
				'Trimethoprim/Sulfamethoxazole-SXT',
				'Fosfomycin-FOS',
				'Vancomycin-VAN',
				'Linezolid-LNZ',
				'Fluconazole',
				'Voriconazole',
				'Caspofungin',
				'Micafungin',
				'Amphotericin B',
				'Flucytosine'
			);
        
			try {
				$cekada 	= ResultSample::where('accession_number', 'LIKE', $nofoto.'%')->get();
				if (!empty($cekada)){
					foreach($cekada as $rows){
						if ($rows->organism !== null){
							$organism 	= $rows->organism;
							$sudah 		= Organisms::where('name', $organism)->count();
							if ($sudah == 0){
								Organisms::create([
									'kelompok' 	=> 'biakankultur',
									'name'		=> $organism,
									'category'	=> 'Vitek',
								]);
							}
						}
						if (!empty($rows->additional_result)) {
							$firstDecode = json_decode($rows->additional_result, true);
							if (is_string($firstDecode)) {
								$data = json_decode($firstDecode, true);
							} else {
								$data = $firstDecode;
							}
							if (is_array($data)) {
								foreach ($data as $item) {
									$glassreportname = in_array($item['antibiotic_name'], $jsonantibiotik);
									RekapAntibiotik::updateOrCreate(
										[
											'orderid'			=> $orderid,
											'antibiotic'		=> $item['antibiotic_name'],
										],
										[
											'resistance'		=> $item['resistance_note'] ?? null,
											'value'				=> $item['value'] ?? null,
											'interpretation'	=> $item['interpretation'] ?? null,
											'glassreportname'	=> $glassreportname,
											'created_at'		=> date('Y-m-d H:i:s'),
											'updated_at'		=> date('Y-m-d H:i:s'),
										]
									);
								}
							}
						}
					}
				}
				$gentabel = RekapAntibiotik::where('orderid', $orderid)->get();
				if (!empty($gentabel)){
					$nomor 		= 1;
					$isidata = '<table border="1" cellpadding="0" cellspacing="0" width="80%">
					<tr>
					<td width="5%"  style="text-align:center;"><strong>No</strong></td>
					<td width="65%" style="text-align:center;"><strong>Antibiotik</strong></td>
					<td width="15%" style="text-align:center;"><strong>Value</strong></td>
					<td width="15%" style="text-align:center;"><strong>S/I/R</strong></td>
					</tr>';
					foreach($gentabel as $rtabel){
						$isidata .= '<tr>
							<td style="text-align:center;">'.$nomor.'</td>
							<td>'.$rtabel->antibiotic.'</td>
							<td style="text-align:center;">'.$rtabel->value.'</td>
							<td style="text-align:center;">'.$rtabel->interpretation.'</td>
						</tr>';
						$nomor++;
					}
					$isidata .= '</table>';

					if ($organism != ''){
						$isidata = 'Organisme yang ditemukan <strong style="font-style: italic;">'.$organism.'</strong><br />'.$isidata;
						KomponenJawaban::updateOrCreate(
							[
								'accnumber'		=> $nofoto,
								'template'		=> $request->input('jenis'),
								'komponen'		=> 'bakteri',
							],
							[
								'isidata'		=> $organism,
								'created_by'	=> Session('nama')
							]
						);
					}
				} else {

				}
				if ($isidata == '' OR is_null($isidata)){
				} else {
					KomponenJawaban::updateOrCreate(
						[
							'accnumber'		=> $nofoto,
							'template'		=> $request->input('jenis'),
							'komponen'		=> $request->input('komponen'),
						],
						[
							'isidata'		=> $isidata,
							'created_by'	=> Session('nama')
						]
					);
				}
				$pesan = $isidata;
			}catch (Exception $e) {
				$pesan 	= $isidata.'<br />'.$e->getMessage();
			}
			return response()->json(['pesan' => $pesan, 'organism' => $organism]);
			return back();
		} else if ($worklist == 'getbbachtect' OR $worklist == 'getmgit' OR $worklist == 'getabbot'){
			$isidata = $request->input('isi');
			try {
				$ketemu 	= '';
				$nomor 		= 1;
				$cekdatalangsung 	= DataListiner::where('no_id', $nofoto)->whereIn('alat', ['BD Mikro 1', 'BD Mikro 2'])->first();
				$ketemu 			= $cekdatalangsung->organisme ?? '';
				if ($ketemu == ''){
					$cekada 	= ResultSample::where('accession_number', 'LIKE', $nofoto.'%')->get();
					if (!empty($cekada)){
						foreach($cekada as $rows){
							$ketemu = $rows->test_status;
						}
					} else {
						$cekdata = DB::table('lis_phoenix')->where('no_id', $nofoto)->first();
						$ketemu = $cekdata->organisme ?? '';
					}
				}
				
				if ($ketemu != ''){ 
					if ($isidata == '' OR is_null($isidata)){
						$isidata = $ketemu;
					} else {
						$isidata = $isidata.'<br />'.$ketemu;
					}
				} else {
					
				}
				if ($isidata == '' OR is_null($isidata)){

				} else {
					KomponenJawaban::updateOrCreate(
						[
							'accnumber'		=> $nofoto,
							'template'		=> $request->input('jenis'),
							'komponen'		=> $request->input('komponen'),
						],
						[
							'isidata'		=> $isidata,
							'created_by'	=> Session('nama')
						]
					);
				}
				$pesan = $isidata;
			}catch (Exception $e) {
				$pesan 	= $isidata.'<br />'.$e->getMessage();
			}
			return $pesan;
		} else if ($worklist == 'getgenexpert'){
			$isidata = $request->input('isi');
			try {
				$ketemu = '';
				$cekada = ResultSample::where('accession_number', 'LIKE', $nofoto.'%')->get();
				if ($cekada->isNotEmpty()){
					foreach($cekada as $rows){
						$ketemu .= ($ketemu ? '<br />' : '') . $rows->test_status;
					}
				} else {
					$payload = [
						'command' => 'request_result',
						'data' => [
							'sample_id' => $nofoto
						],
					];
					$response = Http::timeout(30)->post($this->lisServiceUrl . '/command', $payload);
					if ($response->successful()) {
						Log::info('Permintaan hasil berhasil dikirim ke LIS service.', [
							'sample_id' => $nofoto,
							'response' => $response->json()
						]);
					} else {
						Log::error('Gagal terhubung ke LIS service saat meminta hasil.', [
							'sample_id' => $nofoto,
							'status'    => $response->status(), 
							'body'      => $response->body()
						]);
					}
				}
				if ($ketemu != ''){ 
					if (is_null($isidata) || $isidata == ''){
						$isidata = $ketemu;
					} else {
						$isidata = $isidata.'<br />'.$ketemu;
					}
				}
				if (!is_null($isidata) && $isidata != ''){
					KomponenJawaban::updateOrCreate(
						[
							'accnumber'     => $nofoto,
							'template'      => $request->input('jenis'),
							'komponen'      => $request->input('komponen'),
						],
						[
							'isidata'       => $isidata,
							'created_by'    => Session('nama')
						]
					);
				}
				$pesan = $isidata;
			} catch (Exception $e) {
				$pesan  = (is_null($isidata) ? '' : $isidata . '<br />') . 'Error: ' . $e->getMessage();
				Log::error('Exception dalam fungsi requestResult.', [
					'sample_id' => $nofoto,
					'exception' => $e->getMessage()
				]);
			}
        	return response($pesan, 200);
		} else if ($worklist == 'addviralload'){
			$tabelawal 		= $request->input('tabelawal');
			$idtabel 		= $request->input('idtabel');
			$setnilai 		= $request->input('setnilai');
			$cekada 		= explode('</table', $tabelawal);
			if (isset($cekada[1])){
				$cekbaris 	= explode('</tr>', $tabelawal);
				$jumlahbaris= count($cekbaris);
				$nomor 		= $jumlahbaris - 1;
			} else {
				$nomor		= 1;
			}
			$tabel 			= '';
			$getdataawal 	= Periksa::where('nofoto', $nofoto)->first();
			$orderid 		= $getdataawal->id ?? 0;
			$getdata 		= SiraB::where('id', $idtabel)->first();
			if (isset($getdata->id)){
				$batasatas 	= $getdata->batasatas;
				$midrange	= $getdata->midrange;
				$batasbawah	= $getdata->batasbawah;
				if ($setnilai == 'S'){
					$setval = $batasatas;
				} else if ($setnilai == 'I'){
					$setval = $midrange;
				} else {
					$setval = $batasbawah;
				}
				if ($nomor == 1){
					$tabel 		= '<table border="1" cellpadding="0" cellspacing="0" width="100%"><tr><td width="5%"><strong>No</strong></td><td width="20%"><strong>Antibiotik</strong></td><td width="20%"><strong>Sub</strong></td><td width="10%"><strong>Disc Content</strong></td><td width="5%"><strong>S/I/R</strong></td></tr><tr><td>'.$nomor.'</td><td>'.$getdata->antibiotik.'</td><td>'.$getdata->subantibiotik.'</td><td>'.$getdata->diskcontent.'</td><td>'.$setnilai.'</td></tr></table>';

				} else {
					$baris 		= '<tr><td>'.$nomor.'</td><td>'.$getdata->antibiotik.'</td><td>'.$getdata->subantibiotik.'</td><td>'.$getdata->diskcontent.'</td><td>'.$setnilai.'</td></tr>';
					$tabel 		= str_replace('</table>', $baris, $tabelawal);
					$tabel 		= $tabel.'</table>';
				}
				if ($orderid != 0){
					if ($getdata->subantibiotik !== null && $getdata->subantibiotik != ''){
						$antibiotik = $getdata->subantibiotik;
					} else {
						$antibiotik = $getdata->antibiotik;
					}
					RekapAntibiotik::updateOrCreate(
						[
							'orderid'			=> $orderid,
							'antibiotic'		=> $antibiotik,
						],
						[
							'resistance'		=> $getdata->diskcontent,
							'value'				=> $setval,
							'interpretation'	=> $setnilai,
							'created_at'		=> $getdataawal->daftar ?? date('Y-m-d H:i:s'),
							'updated_at'		=> $getdataawal->akhir ?? date('Y-m-d H:i:s'),
						]
					);
				}
			}
			KomponenJawaban::updateOrCreate(
				[
					'accnumber'		=> $nofoto,
					'template'		=> 'Viral Load',
					'komponen'		=> 'viralload',
				],
				[
					'isidata'		=> $tabel,
					'created_by'	=> Session('nama')
				]
			);
			return $tabel;
		} else if ($worklist == 'addsirabketerangan'){
			$tabelawal 		= $request->input('tabelawal');
			$idtabel 		= $request->input('idtabel');
			$setnilai 		= $request->input('setnilai');
			$cekada 		= explode('</table', $tabelawal);
			if (isset($cekada[1])){
				$cekbaris 	= explode('</tr>', $tabelawal);
				$jumlahbaris= count($cekbaris);
				$nomor 		= $jumlahbaris - 1;
			} else {
				$nomor		= 1;
			}
			$getdataawal 	= Periksa::where('nofoto', $nofoto)->first();
			$orderid 		= $getdataawal->id ?? 0;
			$tabel 			= '';
			$getdata 		= SiraB::where('id', $idtabel)->first();
			if (isset($getdata->id)){
				$batasatas 	= $getdata->batasatas;
				$midrange	= $getdata->midrange;
				$batasbawah	= $getdata->batasbawah;
				if ($setnilai == 'S'){
					$setval = $batasatas;
				} else if ($setnilai == 'I'){
					$setval = $midrange;
				} else {
					$setval = $batasbawah;
				}
				if ($nomor == 1){
					$tabel 		= '<table border="1" cellpadding="0" cellspacing="0" width="80%"><tr><td style="text-align:center;" width="5%"><strong>No</strong></td><td style="text-align:center;" width="20%"><strong>Antibiotik</strong></td><td style="text-align:center;" width="20%"><strong>Sub</strong></td><td style="text-align:center;" width="10%"><strong>Disc Content</strong></td><td style="text-align:center;" width="5%"><strong>S/I/R</strong></td></tr><tr><td style="text-align:center;">'.$nomor.'</td><td>'.$getdata->antibiotik.'</td><td>'.$getdata->subantibiotik.'</td><td style="text-align:center;">'.$getdata->diskcontent.'</td><td style="text-align:center;">'.$setnilai.'</td></tr></table>';

				} else {
					$baris 		= '<tr><td style="text-align:center;">'.$nomor.'</td><td>'.$getdata->antibiotik.'</td><td>'.$getdata->subantibiotik.'</td><td style="text-align:center;">'.$getdata->diskcontent.'</td><td style="text-align:center;">'.$setnilai.'</td></tr>';
					$tabel 		= str_replace('</table>', $baris, $tabelawal);
					$tabel 		= $tabel.'</table>';
				}
				if ($orderid != 0){
					if ($getdata->subantibiotik !== null && $getdata->subantibiotik != ''){
						$antibiotik = $getdata->subantibiotik;
					} else {
						$antibiotik = $getdata->antibiotik;
					}
					RekapAntibiotik::updateOrCreate(
						[
							'orderid'			=> $orderid,
							'antibiotic'		=> $antibiotik,
						],
						[
							'resistance'		=> $getdata->diskcontent,
							'value'				=> $setval,
							'interpretation'	=> $setnilai,
							'created_at'		=> $getdataawal->daftar ?? date('Y-m-d H:i:s'),
							'updated_at'		=> $getdataawal->akhir ?? date('Y-m-d H:i:s'),
						]
					);
				}
			}
			Periksa::where('nofoto', $nofoto)->update([
				'keterangan'	=> $tabel
			]);
			return $tabel;
		} else {
			$periksa 		= Periksa::where('id', $idperiksa)->first();
			if (isset($periksa->id)){
				$idpasien	= $periksa->pasien_id;
				$keterangan	= $periksa->keterangan;
				$daftar 	= $periksa->daftar;
				$idruang 	= $periksa->ruangan_id;
				$kamar 		= $periksa->ruangan;
				$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;
				$kirimemail	= 'TIDAK';
				$ex_nofoto	= substr($nofoto, 8);
				
				$jruang 	= Ruangan::where('id', $ruangan)->first();
				$kamar 		= $jruang->ruangan ?? 'Kamar Periksa';
					
				if ($periksa->status == 'Selesai' OR $periksa->status == 'Arsip'){
					Periksa::where('id', $idperiksa)->update([
						'ruangan_id' 	=> $ruangan,
						'ruangan' 		=> $kamar,
						'dokter_id' 	=> $iddokter,
						'berat' 		=> $berat,
						'klinisi' 		=> $klinisi,
						'klinis' 		=> $klinis,
						'dlp'			=> $dlp,
						'modality'		=> $modality,
						'jumlah'		=> $jumlah,
						'foto' 			=> $tanggal,
						'excutor'		=> Session('id'),
						'nmexcutor'		=> Session('nama'),
					]);
				} else {
					Periksa::where('id', $idperiksa)->update([
						'ruangan_id' 	=> $ruangan,
						'ruangan' 		=> $kamar,
						'dokter_id' 	=> $iddokter,
						'berat' 		=> $berat,
						'klinisi' 		=> $klinisi,
						'klinis' 		=> $klinis,
						'dlp'			=> $dlp,
						'modality'		=> $modality,
						'jumlah'		=> $jumlah,
						'excutor'		=> Session('id'),
						'nmexcutor'		=> Session('nama'),
						'foto' 			=> $tanggal,
						'status'		=> 'Telah di kirim ke worklist/modalitas',
						'excutor'		=> null,
					]);
					Periksa::where('noregister', $noregister)
						->where('daftar', $daftar)
						->where('status', 'LIKE', '%Diperiksa%')
						->where('id', '!=', $idperiksa)
						->update([
							'status' 	=> null,
							'excutor' 	=> null,
						]);
					$kirimemail	= 'YES';
				}
				$pesan 		= $this->Hl7GetResult($periksa->id, $modality);
			} else {
				$pesan 		= '';
			}
			return $pesan;
		}
    }
	public function exExpertise(Request $request) {
		$idperiksa 		= $request->input('periksa_id');
		$nofoto 		= $request->input('nofoto');
		$ruangan 		= $request->input('ruangan');
		$iddokter 		= $request->input('dokter');
		$keterangan 	= $request->input('keterangan');
		$kesimpulan 	= $request->input('kesimpulan');
		//$dlp 			= $request->input('val01');
		$val02 			= $request->input('val02');
		$jenisfont 		= $request->input('val07');
		$modality 		= $request->input('val09');
		$dlp 			= $request->input('val10');
		$ppds1 			= $request->input('val11');
		$ppds2 			= $request->input('val12');
		$ppds3 			= $request->input('val13');
		$diagnosa2 		= $request->input('val16');
		$klinis 		= $request->input('val17');
		$klinisi 		= $request->input('val18');
		$berat 			= $request->input('val19');
		$otheras 		= $request->input('val20');
		$otherppds 		= $request->input('val21');
		$analis 		= $request->input('analis');
		if ($keterangan != ''){
			KomponenJawaban::updateOrCreate(
				[
					'accnumber'		=> $nofoto,
					'template'		=> $dlp,
					'komponen'		=> 'keterangan',
				],
				[
					'isidata'		=> $keterangan,
					'created_by'	=> Session('nama')
				]
			);
		}
		$junior2 		= 0;
		$middle2 		= 0;
		if ($otherppds != ''){
			$cekdokter 	= User::where('nama', $otherppds)->first();
			if (isset($cekdokter->id)){
				$otherppds 	= $cekdokter->id;
				if ($otheras == 'Junior'){
					$junior2 = $otherppds;
					Periksa::where('id', $idperiksa)->update([
						'nmppdsjunior2' => $cekdokter->nama
					]);
				} else {
					$middle2 = $otherppds;	
					Periksa::where('id', $idperiksa)->update([
						'nmppdsmiddle2' => $cekdokter->nama
					]);
				}
			}
		}
		$jumlah			= $kesimpulan;
		$kesimpulan 	= '';
		$getdataawal 	= Periksa::where('id', $idperiksa)->first();
		$cekstatus		= $getdataawal->status;
		$noregister		= $getdataawal->noregister;
		$daftar			= $getdataawal->daftar;
		$surat 			= self::genSurat($getdataawal->id, 'dengan kop');
		if ($cekstatus == 'Selesai' OR $cekstatus == 'Arsip'){
			$update = Riwayat::create([
				'nofoto'	=> $nofoto,
				'jawaban'	=> $surat,
				'inputor'	=> Session('nama'),
				'keterangan'=> 'Adendum',
			]);
			Periksa::where('id', $idperiksa)->update([
				'nmexcutor'		=> Session('nama'),
				'excutor'		=> Session('id'),
				'tgladendum' 	=> date('Y-m-d H:i:s'),
			]);
			if ($getdataawal->dokter_id != 0){
				$tuliskirim = Session('nama').' Mengisi Adendum Untuk Pasien an. '.$getdataawal->nmpasien.' Dengan Order Awal '.$getdataawal->reques;
				$getppds 	= User::where('id', $getdataawal->dokter_id)->first();
				if (isset($getppds->firebase)){
					$firebaseid = $getppds->firebase;
					$pesan 		= SendMail::mobilenotif($getppds->nama, $firebaseid, 'Adendum', $tuliskirim);
				}
			}
		} else {
			if ($val02 == 'Send'){
				$tlsstatus = 'Expertise Saved (Un Verified)';
				Riwayat::create([
					'nofoto'	=> $nofoto, 
					'jawaban'	=> $surat, 
					'inputor'	=> Session('nama'),
					'keterangan'=> 'Expertise',
				]);
				Periksa::where('id', $idperiksa)->update([
					'baca' 		=> date('Y-m-d H:i:s'),
					'nmpembaca'	=> Session('nama'),
					'nmexcutor'	=> Session('nama'),
					'excutor'	=> Session('id'),
				]);
				if ($getdataawal->dokter_id != 0){
					$getppds = User::where('id', $getdataawal->dokter_id)->first();
					if (isset($getppds->firebase)){
						$tuliskirim = Session('nama').' Mengisi Ekspertise Untuk Pasien an. '.$getdataawal->nmpasien.' Dengan Order Awal '.$getdataawal->reques;
						$firebaseid = $getppds->firebase;
						$pesan 		= SendMail::mobilenotif($getppds->nama, $firebaseid, 'Ekspertise', $tuliskirim);
					}
				}
			} else {
				$tlsstatus = 'Proses Analisis Sampel';
				Riwayat::create([
					'nofoto'	=> $nofoto, 
					'jawaban'	=> $surat, 
					'inputor'	=> Session('nama'),
					'keterangan'=> $tlsstatus,
				]);
				Periksa::where('id', $idperiksa)->update([
					'nmexcutor'	=> Session('nama'),
					'excutor'	=> Session('id'),
					'tgldraft' 	=> date('Y-m-d H:i:s'),
					'nmdrafter'	=> Session('nama'),
				]);
			}
			if ($ppds3 != 0){
				$cekdokter 	= User::where('id', $ppds3)->first();
				if (isset($cekdokter->nama)){
					Periksa::where('id', $idperiksa)->update([
						'nmppdssenior' => $cekdokter->nama
					]);
				}
			}
			if ($ppds2 != 0){
				$cekdokter 	= User::where('id', $ppds2)->first();
				if (isset($cekdokter->nama)){
					Periksa::where('id', $idperiksa)->update([
						'nmmiddleppds' => $cekdokter->nama
					]);
				}
			}
			if ($ppds1 != 0){
				$cekdokter 	= User::where('id', $ppds1)->first();
				if (isset($cekdokter->nama)){
					Periksa::where('id', $idperiksa)->update([
						'nmppdsjunior' => $cekdokter->nama
					]);
				}
			}
			if ($iddokter != 0){
				$cekdokter 	= User::where('id', $iddokter)->first();
				if (isset($cekdokter->nama)){
					Periksa::where('id', $idperiksa)->update([
						'nmdokter' => $cekdokter->nama
					]);
				}
			}
			if ($analis != 0){
				$cekdokter 	= User::where('id', $analis)->first();
				if (isset($cekdokter->nama)){
					Periksa::where('id', $idperiksa)->update([
						'nmanalis' => $cekdokter->nama
					]);
				}
			}
			if ($ruangan == 'Pilih' OR $ruangan == ''){
				$update = Periksa::where('id', $idperiksa)->update([
					'dokter_id' 	=> $iddokter,
					'analis' 		=> $analis,
					'ppdsjunior' 	=> $ppds1,
					'middleppds' 	=> $ppds2,
					'ppdssenior' 	=> $ppds3,
					'ppdsmiddle2' 	=> $middle2,
					'ppdsjunior2' 	=> $junior2,
					'keterangan' 	=> $keterangan,
					'kesimpulan' 	=> '',
					'berat' 		=> $berat,
					'dlp' 			=> $dlp,
					'modality'		=> $modality,
					'klinis'		=> $klinis,
					'klinisi'		=> $klinisi,
					'diagnosa2'		=> $diagnosa2,
					'baca' 			=> date('Y-m-d H:i:s'),
					'status' 		=> $tlsstatus,
					'nmexcutor'		=> Session('nama'),
					'excutor'		=> Session('id'),
				]);
			} else {
				$jruang 	= Ruangan::where('id', $ruangan)->first();
				if (isset($jruang->ruangan)){
					$kamar 		= $jruang->ruangan;
					$update = Periksa::where('id', $idperiksa)->update([
						'ruangan_id' 	=> $ruangan,
						'ruangan' 		=> $kamar,
						'dokter_id' 	=> $iddokter,
						'analis' 		=> $analis,
						'ppdsjunior' 	=> $ppds1,
						'middleppds' 	=> $ppds2,
						'ppdssenior' 	=> $ppds3,
						'ppdsmiddle2' 	=> $middle2,
						'ppdsjunior2' 	=> $junior2,
						'keterangan' 	=> $keterangan,
						'kesimpulan' 	=> '',
						'berat' 		=> $berat,
						'dlp' 			=> $dlp,
						'modality'		=> $modality,
						'klinis'		=> $klinis,
						'klinisi'		=> $klinisi,
						'diagnosa2'		=> $diagnosa2,
						'baca' 			=> date('Y-m-d H:i:s'),
						'status' 		=> $tlsstatus,
						'nmexcutor'		=> Session('nama'),
						'excutor'		=> Session('id'),
					]);
				} else {
					$update = Periksa::where('id', $idperiksa)->update([
						'dokter_id' 	=> $iddokter,
						'analis' 		=> $analis,
						'ppdsjunior' 	=> $ppds1,
						'middleppds' 	=> $ppds2,
						'ppdssenior' 	=> $ppds3,
						'ppdsmiddle2' 	=> $middle2,
						'ppdsjunior2' 	=> $junior2,
						'keterangan' 	=> $keterangan,
						'kesimpulan' 	=> '',
						'berat' 		=> $berat,
						'modality'		=> $modality,
						'klinis'		=> $klinis,
						'klinisi'		=> $klinisi,
						'diagnosa2'		=> $diagnosa2,
						'dlp'			=> $dlp,
						'baca' 			=> date('Y-m-d H:i:s'),
						'status' 		=> $tlsstatus,
						'nmexcutor'		=> Session('nama'),
						'excutor'		=> Session('id'),
					]);
				}
			}
		}
		if ($update) {
			if (Session('previlage') == 'supervisor'){
				return response()->json(['icon' => 'success', 'warna' => '#5ba035', 'status' => 'Success', 'message' => 'Patient Expertise Saved']);
				return back();
			} else {
				return response()->json(['icon' => 'success', 'warna' => '#5ba035', 'status' => 'Success', 'message' => 'Patient Expertise Saved, please show it to your SPV for verification']);
				return back();
			}
		} else {
			return response()->json(['icon' => 'error', 'warna' => '#bf441d', 'status' => 'Recieved NACK from remote', 'message' => 'System Down, please try again in a few years....']);
			return back();
		}
    }
	public function savePdf(Request $request) {
        $id             =   $request->input('id');
        $periksa        =   Periksa::where('id', $id)->first();
		if (isset($periksa->id)){
			$surat = self::genSurat($periksa->id, 'tanpa kop');
			return $surat;
		} else {
			$data                       = [];
            $data['kalimatheader']  	= 'Mohon Maaf';
            $data['kalimatbody']  		= 'Ekspertise dengan ID : '.$id.' Tidak ditemukan';
            return view('errors.error', $data);
		}
    }
	public function ctkFormhasil($id){
        $periksa        =   Periksa::where('nofoto', $id)->first();
		if (isset($periksa->id)){
			$surat = self::genSurat($periksa->id, 'dengan kop');
			return $surat;
		} else {
			$data                       = [];
            $data['kalimatheader']  	= 'Mohon Maaf';
            $data['kalimatbody']  		= 'Ekspertise dengan Accession Number : '.$id.' Tidak ditemukan';
            return view('errors.error', $data);
		}
    }
	public function gethasiltoSIMRS(Request $request){
		$nolab 			= $request->input('nolab');
        $periksa        =   Periksa::where('nofoto', $nolab)->first();
		if (isset($periksa->id)){
			$surat 		= self::genSurat($periksa->id, 'dengan kop');
			$dataraw	= KomponenJawaban::where('accnumber', $periksa->nofoto)->get();
			return response()->json(['htmlink' => url('/').'/hasil/'.$periksa->nofoto, 'html' => $surat, 'rawdata' => json_encode($dataraw)], 201);
		} else {
			return response()->json(['status' => 'Failed', 'message' => 'Nomor Lab : '.$nolab.' Tidak di Temukan Cek Kembali Variable Yang di Kirim Haruslah Variable nolab'], 500);
		}
    }
	public function getRiwayat(Request $request) {
    	$idpasien	= $request->input('val01');
    	$arrayfiles = [];
		if ($idpasien == 'sirab'){
			$getsirab = SiraB::orderBy('family', 'ASC')
				->orderBy('spesies', 'ASC')
				->get()
				->map(function($row) {
					return [
						'id'            => $row->id,
						'family'        => $row->family,
						'spesies'       => $row->spesies,
						'antibiotik'    => $row->antibiotik,
						'subantibiotik' => $row->subantibiotik,
						'diskcontent'   => $row->diskcontent,
						'batasatas'     => $row->batasatas,
						'midrange'      => $row->midrange,
						'batasbawah'    => $row->batasbawah,
						'sumber'        => $row->sumber,
						'kodedok'       => $row->kodedok,
						'atu'           => $row->atu,
						'kelompok'      => $row->kelompok,
						'antibiotikall' => $row->subantibiotik !== null && $row->subantibiotik !== ''
											? $row->subantibiotik
											: $row->antibiotik,
					];
				})
				->toArray();

			echo json_encode($getsirab);
			
		} else if ($idpasien == 'Bakteri'){
			$getsirab = Organisms::where('kelompok', 'biakankultur')->orderBy('category', 'ASC')->orderBy('name', 'ASC')->get();
			echo json_encode($getsirab);
		} else if ($idpasien == 'Mikroorganisme'){
			$getsirab = Organisms::where('kelompok', 'mikroorganisme')->orderBy('category', 'ASC')->orderBy('name', 'ASC')->get();
			echo json_encode($getsirab);
		} else if ($idpasien == 'listkodespesimen'){
			$getsirab = Organisms::where('kelompok', 'listkodespesimen')->orderBy('category', 'ASC')->orderBy('name', 'ASC')->get();
			echo json_encode($getsirab);
		} else if ($idpasien == 'allany'){
			$getsirab = Organisms::whereNotIn('kelompok', ['biakankultur', 'mikroorganisme', 'listkodespesimen'])->orderBy('category', 'ASC')->orderBy('name', 'ASC')->get();
			echo json_encode($getsirab);
		} else {
			$files 		= Periksa::where('pasien_id', $idpasien)->orderBy('created_at', 'DESC')->get();
			foreach ($files as $file) {
				$jenis 		= $file->nofoto;
				$arrayttl 	= explode("-", $jenis);
				$jenis1 	= $arrayttl[0];
				$arrayfiles[] = array(
					'idne' 			=> $file->id,
					'jenis' 		=> $jenis1,
					'nofoto'        => $file->nofoto,
					'status'        => $file->status,
					'tanggal' 		=> $file->created_at->toDateTimeString()
				);
			}
			echo json_encode($arrayfiles);
		}
    }
	public function getAdendum(Request $request) {
    	$nofoto	= $request->input('val01');
    	$arrayfiles = 	[];
		$files 		= Riwayat::where('nofoto', $nofoto)->orderBy('created_at', 'ASC')->get();
    	foreach ($files as $file) {			
	    	$arrayfiles[] = array(
				'idne' 		=> $file->id,
				'nofoto'    => $file->nofoto,
				'jawaban'   => $file->jawaban,
				'inputor'   => $file->inputor,
				'keterangan'=> $file->keterangan,
				'verifikasi'=> $file->verifikasi,
				'tanggal'	=> $file->created_at->toDateTimeString()
			);
    	}
    	echo json_encode($arrayfiles);
    }
	public function exaddAdendum(Request $request) {
        $nofoto     = $request->input('set01');
        $adendum    = $request->input('set02');
		$nama		= Session('nama');
		$jam 		= date("Y-m-d H:i:s");
		$adendum	= $adendum.'<br />Addendum added By '.$nama.' at '.$jam;
		if (Session('previlage') == 'supervisor'){
			$update 	= Riwayat::create([
				'nofoto'	=> $nofoto,
				'jawaban'	=> $adendum, 
				'inputor'	=> Session('nama'),
				'keterangan'=> 'Adendum',
				'verifikasi'=> 'Accepted',
			]);
			Periksa::where('nofoto', $nofoto)->update([
				'keterangan' => $adendum
			]);
		} else {
			$update 	= Riwayat::create([
				'nofoto'	=> $nofoto,
				'jawaban'	=> $adendum, 
				'inputor'	=> Session('nama'),
				'keterangan'=> 'Adendum',
			]);
			$getdataawal 	= Periksa::where('nofoto', $nofoto)->first();
			if (isset($getdataawal->dokter_id)){
				$getppds = User::where('id', $getdataawal->dokter_id)->first();
				if (isset($getppds->firebase)){
					$tuliskirim = Session('nama').' Mengisi Adendum Untuk Pasien an. '.$getdataawal->nmpasien.' Dengan Order Awal '.$getdataawal->reques;
					$firebaseid = $getppds->firebase;
					$pesan 		= SendMail::mobilenotif($getppds->nama, $firebaseid, 'Adendum', $tuliskirim);
				}
			}
		}
		if ($update){
			return response()->json(['icon' => 'success', 'warna' => '#5ba035', 'status' => 'Success', 'message' => 'Addendum Saved']);
			return back();
		} else {
			return response()->json(['icon' => 'error', 'warna' => '#bf441d', 'status' => 'Error..!!', 'message' => 'Adding Addendum Failed, Please try again in a few year..!!']);
			return back();
		}
    }
	public function periksa(Request $request) {
        $nofoto         = $request->input('nofoto');
        $id             = $request->input('id');
        $jpoli          = Periksa::where('id', $id)->first();
		$statuse		= $jpoli->status;
		$noregister		= $jpoli->noregister;
		$daftar			= $jpoli->daftar;
		$nama			= Session('nama');
		$idpemeriksa	= Session('id');
		$arrnofoto		= explode('-', $nofoto);
		$nofoto			= $arrnofoto[0];
		if ($statuse != 'Selesai'){
			Periksa::where('id', $id)->update([
				'status' 	=> 'Pemeriksaan Sampel',
				'excutor' 	=> $idpemeriksa,
			]);
		}
    }
	public function getFoto(Request $request) {
		$arrayjwblist	=   [];
		$nofoto			= 	$request->input('val01');
		$getfileawal	= 	Periksa::where('nofoto', $nofoto)->first();
		if (isset($getfileawal->filefoto)){
			$filefoto	= $getfileawal->filefoto;
			$getfileex	= explode('.', $filefoto);
			$jenfile	= $getfileex[1];
			if ($filefoto != ''){
				$arrayjwblist[] = array(
					'idne' 		=> '',
					'nofoto' 	=> $nofoto,
					'file' 		=> $filefoto,
					'jenfile'	=> $jenfile,
					'nama'		=> 'Scan Permintaan',
				);
			}
		}
        echo json_encode($arrayjwblist);
    }
	public function getListtem(Request $request) {
		$arrayjwblist	=   [];
		$arrfoto		=   [];
		$arrjawaban		= 	Subjawaban::orderBy('kategori')->get();
		foreach ($arrjawaban as $rjawaban) {
			$idkategori = $rjawaban->kategori;
			$keterangan = $rjawaban->subjawaban;
			$kesimpulan = $rjawaban->kesimpulan;
			if ($kesimpulan != ''){
				$keterangan = $keterangan.' '.$kesimpulan;
			}
			$cek   		= Jawaban::where('id',$idkategori)->count();
			if ($cek == 0){ 
				 $kategori	= 'Deleted Category';
			}
			else {
				 $jkategori = Jawaban::where('id',$idkategori)->first();
				 $kategori 	= $jkategori->jawaban;
			}
			$arrayjwblist[] = array(
				'id' 		=> $rjawaban->id,
				'kategori' 	=> $kategori,
				'judul' 	=> $rjawaban->judul,
				'isine' 	=> $keterangan,
				'kesimpulan'=> '',
			);
		}

        echo json_encode($arrayjwblist);
    }
	public function exprintLabel(Request $request) {
		$data		=   [];
		$idcetak	= 	$request->input('set01');
		$periksa	=   Periksa::where('id', $idcetak)->first();
		if (isset($periksa->id)){
			try {
				$qrcode 				= base64_encode(QrCode::format('png')->size(100)->generate($periksa->nofoto));
			} catch (\Exception $e) {
				$qrcode 				= ' ';
			}
			$data['qrcode'] 		= $qrcode;
			$data['datatoprint'] 	= $periksa;
        	return view('cetak.label', $data);
		}
    }
	public function exprintForm(Request $request) {
		$data		= [];
		$idcetak	= $request->input('set01');
		$kanan 		= '';
		$homebase	= url("/");
		$cetak 		= '';
		foreach($idcetak as $rid){
			$periksa        =   Periksa::where('id', $rid)->first();
			if (isset($periksa->id)){
				$idruangan      =   $periksa->ruangan_id;
				$statuse      	=   $periksa->status;
				$idpasien		= 	$periksa->pasien_id;
				$reques			= 	$periksa->reques;
				$tanggal        =   $periksa->daftar;
				$poli_id        =   $periksa->poli_id;
				$keterangan     = 	$periksa->keterangan;
				$kesimpulan     = 	$periksa->kesimpulan;
				$nofoto    	 	= 	$periksa->nofoto;
				$urgensi    	= 	$periksa->urgensi;
				$asuransi    	= 	$periksa->asuransi;
				$umur    		= 	$periksa->usia;
				$dlp    		= 	$periksa->dlp;
				$klinisi   		= 	$periksa->klinisi;
				$ppdssenior   	= 	$periksa->ppdssenior;
				$middleppds   	= 	$periksa->middleppds;
				$ppdsjunior   	= 	$periksa->ppdsjunior;
				$tandatangan   	= 	$periksa->tandatangan;
				$ruangan   		= 	$periksa->ruangan;
				$jk 			= 	$periksa->jkpasien;
				$tgllahir		= 	$periksa->tgllahirpasien;
				$kota 			= 	'';
				$alamat 		= 	$periksa->alamatpasien;
				$nama 			= 	$periksa->nmpasien;
				$norm 			= 	$periksa->noregister;
				$dokter			= 	$periksa->nmdokter ?? '';
				
				if ($cetak != ''){
					$cetak = $cetak.'<div style="page-break-before: always">';
				}
				$tulisdiqrcode				= $homebase.'/hasil/'.$periksa->nofoto;
				try {
					$qrcode 				= base64_encode(QrCode::format('png')->size(100)->generate($tulisdiqrcode));
				} catch (\Exception $e) {
					$qrcode 				= ' ';
				}
				
				$cetak = $cetak.'
					<table width="100%" border="0" cellpadding="0" cellspacing="0">
						<tr><td width="45">&nbsp;</td>
							<td width="486" valign="top">&nbsp;</td>
							<td width="12" valign="top">&nbsp;</td>
							<td width="497" valign="top">&nbsp;</td>
							<td width="43" valign="top">&nbsp;</td>
							<td width="15" valign="top">&nbsp;</td>
						</tr>
						<tr>
							<td colspan="6">
								<img src="'.$homebase.'/kopsurat.png" width="100%" />
							</td>
						</tr>
						<tr><td width="45">&nbsp;</td>
							<td valign="top">No. Foto</td>
							<td valign="top" align="center">:</td>
							<td valign="top">'.$nofoto.'</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
						</tr>
						<tr><td width="45">&nbsp;</td>
							<td valign="top">No. RM</td>
							<td valign="top" align="center">:</td>
							<td valign="top">'.$periksa->noregister.'</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
						</tr>
						<tr><td width="45">&nbsp;</td>
							<td valign="top">Nama</td>
							<td valign="top" align="center">:</td>
							<td valign="top">'.$nama.'</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
						</tr>
						<tr><td width="45">&nbsp;</td>
							<td valign="top">Jenis Kelamin / Tgl. Lahir</td>
							<td valign="top" align="center">:</td>
							<td valign="top">'.$periksa->jkpasien.' / '.$periksa->tgllahirpasien.'</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
						</tr>
						<tr><td width="45">&nbsp;</td>
							<td valign="top">Klinik / Ruang</td>
							<td valign="top" align="center">:</td>
							<td valign="top">'.$periksa->asalpasien.'</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
						</tr>
						<tr><td width="45">&nbsp;</td>
							<td valign="top">Tgl. Register</td>
							<td valign="top" align="center">:</td>
							<td valign="top">'.$periksa->daftar.'</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
						</tr>
						<tr><td width="45">&nbsp;</td>
							<td valign="top">Order</td>
							<td valign="top" align="center">:</td>
							<td valign="top">'.$periksa->reques.'</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
						</tr>
						<tr><td width="45">&nbsp;</td>
							<td valign="top">Dokter Pengirim</td>
							<td valign="top" align="center">:</td>
							<td valign="top">'.$periksa->klinisi.'</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
						</tr>
						<tr><td width="45">&nbsp;</td>
							<td valign="top">Dengan Klinis</td>
							<td valign="top" align="center">:</td>
							<td valign="top">'.$periksa->klinis.'</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
						</tr>
						<tr><td width="45">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
						</tr>
						<tr><td width="45">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
						</tr>
						<tr><td width="45">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
						</tr>
						<tr><td width="45">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
						</tr>
						<tr><td width="45">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
						</tr>
						<tr><td width="45">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
						</tr>
						<tr><td width="45">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
						</tr>
						<tr><td width="45">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
						</tr>
						<tr><td width="45">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
						</tr>
						<tr><td width="45">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
						</tr>
						<tr><td width="45">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
						</tr>
						<tr><td width="45">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
						</tr>
						<tr><td width="45">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
						</tr>
						<tr><td width="45">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
						</tr>
						<tr><td width="45">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
						</tr>
						<tr><td width="45">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
						</tr>
						<tr><td width="45">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
						</tr>
						<tr><td width="45">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
						</tr>
						<tr><td width="45">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
						</tr>
						<tr><td width="45">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
						</tr>
						<tr><td width="45">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
						</tr>
						<tr><td width="45">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
						</tr>
						<tr><td width="45">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
						</tr>
						<tr><td width="45">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
						</tr>
						<tr><td width="45">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
						</tr>
						<tr><td width="45">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
						</tr>
						<tr><td width="45">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
						</tr>
						<tr><td width="45">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
						</tr>
						<tr><td width="45">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
						</tr>
						<tr><td width="45">&nbsp;</td>
							<td valign="top"><img src="data:image/png;base64, '.$qrcode.' "></td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
							<td valign="top">&nbsp;</td>
						</tr>
					</table>';
			}
		}
		echo $cetak;
    }
	public function exsendTomany(Request $request) {
		$data		=   [];
		$iddokter	= 	$request->input('set01');
		$modality	= 	$request->input('set02');
		$worklist	= 	$request->input('set03');
		$idcetak	= 	$request->input('set04');
		$sukses 	=	0;
		$error		=	'';
		$emailbody 	= 	'';
			
		foreach($idcetak as $idperiksa){
			$periksa        =   Periksa::where('id', $idperiksa)->first();
			if (isset($periksa->id)){
				$idpasien	= $periksa->pasien_id;
				$keterangan	= $periksa->keterangan;
				$daftar 	= $periksa->daftar;
				$idruang 	= $periksa->ruangan_id;
				$kamar 		= $periksa->ruangan;
				$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;
				$namapoli   = $periksa->getRuangan->poli ?? 'Deleted Data Ruang';
				
				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 	= 'Dokter Penanggung Jawab';
				$arrayttl 	= explode("-", $nofoto);
				$jenis 		= $arrayttl[0];
				$jk 		= $periksa->jkpasien;
				$tgllahir	= $periksa->tgllahirpasien;
				$kota 		= '';
				$alamat 	= $periksa->alamatpasien;
				$nama 		= $periksa->nmpasien;
				$norm 		= $periksa->noregister;
				$poli		= $periksa->getPoli->poli ?? 'EMI Primary';
				$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 	= '';
				//PV1.2 = value nya I (Inpatient), O (Outpatient), E (Emergency).
				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; }
				if ($worklist == 'pacs'){
					$getsetting		= Setting::where('id', '1')->first();
					$pacsaddr		= $getsetting->pacs;
					$port			= $getsetting->port;
					$recievingfas	= 'OESEND_PROD';
					$portupdate		= '10020';
				} else {
					$getsetting		= Worklist::where('id', $worklist)->first();
					if (isset($getsetting->ipaddress)){
						$pacsaddr		= $getsetting->ipaddress;
						$port			= $getsetting->portnumber;
						$portupdate		= $getsetting->portnumber;
						$recievingfas	= $getsetting->aetitle;
					} else{
						$getsetting		= Setting::where('id', '1')->first();
						$pacsaddr		= $getsetting->pacs;
						$port			= $getsetting->port;
						$recievingfas	= 'OESEND_PROD';
						$portupdate		= '10020';
					}
				}
				if (is_null($foto)){
					$msg = new Message();
					$msh = new MSH();
					//$msh->setField(1, '|');
					//$msh->setField(2, '^~\&');
					$msh->setField(3, 'RIS');
					$msh->setField(4, 'RSSA MALANG');
					//$msh->setField(5, $recievingfas);
					$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(16, $klinis);
					$orc->setField(17, 'Radiologi RSSA');
					$msg->addSegment($orc);
					
					$obr = new OBR();
					$obr->setField(2, [$nofoto, $poli]);
					$obr->setField(3, [$nofoto, $poli]);
					$obr->setField(4, [$modality, $reques, $poli]);
					$obr->setField(5, $prioritas);
					$obr->setField(6, $today);
					$obr->setField(16, [$iddokter, $dokter]);
					$obr->setField(18, $nofoto);
					$obr->setField(19, $modality);
					$obr->setField(21, $modality);
					$obr->setField(24, $modality);
					$obr->setField(27, ['1', 'once', $tanggal, $prioritas]);
					$obr->setField(36, $today);
					$msg->addSegment($obr);
					try {
						$connection = new Connection($pacsaddr, $port);
						$ack 		= $connection->send($msg);
						$sukses++;
						$emailbody 	= $emailbody.'<br />Pasien atas nama '.$nama.' Dengan Order Pemeriksaan '.$reques.' Dari '.$asalpasien.' Terkirim ke Modality';
					}catch (Exception $e) {
						$result = $e->getMessage();
						$error	= $error.$result.'<br />';
					}
				} else {
					$msg = new Message();
					$msh = new MSH();
					$msh->setField(3, 'RIS');
					$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, $recievingfas);
					$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 {
						$port 		= '10020';
						$connection = new Connection($pacsaddr, $port);
						$ack 		= $connection->send($msg);
						$sukses++;
					}catch (Exception $e) {
						$result = $e->getMessage();
						$error	= $error.$result.'<br />';
					}
				}
			}
		}
		if ($error == ''){
			
			return response()->json(['icon' => 'success', 'warna' => '#5ba035', 'status' => 'Success', 'message' => 'Data Saved<br />'.$error]);
			return back();
		} else {
			return response()->json(['icon' => 'error', 'warna' => '#bf441d', 'status' => 'Error..!!', 'message' => $error]);
			return back();
		}
    }
	public function exsendToinsitu(Request $request) {
		$data		=   [];
		$idcetak	= 	$request->input('set01');
		$jumlah 	=	0;
		$gagal 		=	'';
		foreach($idcetak as $rid){
			$periksa    =   Periksa::where('id', $rid)->first();
			if (isset($periksa->id)){
				$ceksek = PeriksaSYNC::where('created_by', Session('username'))->where('nofoto', $periksa->nofoto)->count();
				if ($ceksek == 0){
					$periksaid 	= PeriksaSYNC::insertGetId([
						'noloket'		=> $periksa->noloket,
						'nofoto'		=> $periksa->nofoto,
						'noregister'	=> $periksa->noregister,
						'asalpasien'	=> $periksa->asalpasien,
						'nmrs'			=> $periksa->nmrs,
						'nmpasien'		=> $periksa->nmpasien,
						'jkpasien'		=> $periksa->jkpasien,
						'tgllahirpasien'=> $periksa->tgllahirpasien,
						'tlppasien'		=> $periksa->tlppasien,
						'alamatpasien'	=> $periksa->alamatpasien,
						'reques'		=> $periksa->reques,
						'usia'			=> $periksa->usia,
						'berat'			=> $periksa->berat,
						'ruangan'		=> $periksa->ruangan,
						'nmdokter'		=> $periksa->nmdokter,
						'nmppdssenior'	=> $periksa->nmppdssenior,
						'nmmiddleppds'	=> $periksa->nmmiddleppds,
						'nmppdsjunior'	=> $periksa->nmppdsjunior,
						'nmppdsmiddle2'	=> $periksa->nmppdsmiddle2,
						'nmppdsjunior2'	=> $periksa->nmppdsjunior2,
						'nmanalis'		=> $periksa->nmanalis,
						'nmexcutor'		=> $periksa->nmexcutor,
						'klinisi'		=> $periksa->klinisi,
						'klinis'		=> $periksa->klinis,
						'keterangan'	=> $periksa->keterangan,
						'asuransi'		=> $periksa->asuransi,
						'urgensi'		=> $periksa->urgensi,
						'diagnosa'		=> $periksa->diagnosa,
						'diagnosa2'		=> $periksa->diagnosa2,
						'modality'		=> $periksa->modality,
						'kd_spesimen'	=> $periksa->kd_spesimen,
						'nm_spesimen'	=> $periksa->nm_spesimen,
						'dlp'			=> $periksa->dlp,
						'daftar'		=> $periksa->daftar,
						'foto'			=> $periksa->foto,
						'tgldraft'		=> $periksa->tgldraft,
						'baca'			=> $periksa->baca,
						'verifikasi'	=> $periksa->verifikasi,
						'export'		=> $periksa->export,
						'tgladendum'	=> $periksa->tgladendum,
						'status'		=> '',
						'spvsender'		=> '',
						'created_by'	=> Session('username')
					]);
					if ($periksaid){
						$jumlah++;
					} else {
						$gagal = $gagal.'ID '.$rid.' Gagal Input<br />';
					}
				} else {
					$periksaid 	= PeriksaSYNC::where('created_by', Session('username'))->where('nofoto', $periksa->nofoto)->update([
						'noloket'		=> $periksa->noloket,
						'noregister'	=> $periksa->noregister,
						'asalpasien'	=> $periksa->asalpasien,
						'nmrs'			=> $periksa->nmrs,
						'nmpasien'		=> $periksa->nmpasien,
						'jkpasien'		=> $periksa->jkpasien,
						'tgllahirpasien'=> $periksa->tgllahirpasien,
						'tlppasien'		=> $periksa->tlppasien,
						'alamatpasien'	=> $periksa->alamatpasien,
						'reques'		=> $periksa->reques,
						'usia'			=> $periksa->usia,
						'berat'			=> $periksa->berat,
						'ruangan'		=> $periksa->ruangan,
						'nmdokter'		=> $periksa->nmdokter,
						'nmppdssenior'	=> $periksa->nmppdssenior,
						'nmmiddleppds'	=> $periksa->nmmiddleppds,
						'nmppdsjunior'	=> $periksa->nmppdsjunior,
						'nmppdsmiddle2'	=> $periksa->nmppdsmiddle2,
						'nmppdsjunior2'	=> $periksa->nmppdsjunior2,
						'nmanalis'		=> $periksa->nmanalis,
						'nmexcutor'		=> $periksa->nmexcutor,
						'klinisi'		=> $periksa->klinisi,
						'klinis'		=> $periksa->klinis,
						'keterangan'	=> $periksa->keterangan,
						'asuransi'		=> $periksa->asuransi,
						'urgensi'		=> $periksa->urgensi,
						'diagnosa'		=> $periksa->diagnosa,
						'diagnosa2'		=> $periksa->diagnosa2,
						'modality'		=> $periksa->modality,
						'kd_spesimen'	=> $periksa->kd_spesimen,
						'nm_spesimen'	=> $periksa->nm_spesimen,
						'dlp'			=> $periksa->dlp,
						'daftar'		=> $periksa->daftar,
						'foto'			=> $periksa->foto,
						'tgldraft'		=> $periksa->tgldraft,
						'baca'			=> $periksa->baca,
						'verifikasi'	=> $periksa->verifikasi,
						'export'		=> $periksa->export,
						'tgladendum'	=> $periksa->tgladendum,
					]);
					if ($periksaid){
						$jumlah++;
					} else {
						$gagal = $gagal.'ID '.$rid.' Gagal Input<br />';
					}
				}
			}
		}
		return response()->json(['icon' => 'success', 'warna' => '#5ba035', 'status' => 'Success', 'message' => 'Data Send Count '.$jumlah.' <br /> '.$gagal]);
		return back();
    }
	public function exprintLabelSIMRS(Request $request) {
		$data		=   [];
		$idcetak	= 	$request->input('set01');
		$periksa	=   Periksa::where('id', $idcetak)->first();
		if (isset($periksa->id)){
			try {
				$qrcode 				= base64_encode(QrCode::format('png')->size(100)->generate($periksa->nofoto));
			} catch (\Exception $e) {
				$qrcode 				= ' ';
			}
			$data['qrcode'] 		= $qrcode;
			$data['datatoprint'] 	= $periksa;
        	return view('cetak.label', $data);
		}
    }
	public function exprintFormSIMRS(Request $request) {
		$data		= [];
		$idcetak	= $request->input('set01');
		$kanan 		= '';
		$homebase	= url("/");
		$cetak 		= '';
		foreach($idcetak as $rid){
			$periksa        =   Periksa::where('id', $rid)->first();
			if (isset($periksa->id)){
				$daftar 	= 	$periksa->daftar;
				$gettgl 	= 	explode(' ', $daftar);
				$tanggal 	= 	$gettgl[0];
				$getarrtgl 	= 	explode('-', $tanggal);
				$yy 		= 	$getarrtgl[0];
				$mm 		= 	$getarrtgl[1] ?? '00';
				$dd 		= 	$getarrtgl[2] ?? '00';
				$date 		= 	new DateTime($tanggal);
				$thnpendek 	= 	$date->format('y');
				$vitek 		= 	$dd.$mm.$yy.'-'.$periksa->noloket;
				$bd 		= 	$thnpendek.'-'.$periksa->noloket;
				$abbot 		= 	$yy.$mm.$dd.'-'.$periksa->noloket;
				$komponens1	= 	KomponenJawaban::where('accnumber', $periksa->nofoto)->where('komponen', 'hasilpemeriksaanttcmmtbrifxpert_kodeunik')->first();
				$komponens2	= 	KomponenJawaban::where('accnumber', $periksa->nofoto)->where('komponen', 'hasilpemeriksaanttcmmtbrifxpert_kodeunikpagi')->first();
				$komponens3	= 	KomponenJawaban::where('accnumber', $periksa->nofoto)->where('komponen', 'hasilpemeriksaanttcmmtbxdrxpert_kodeunikpagi')->first();
				$komponens4	= 	KomponenJawaban::where('accnumber', $periksa->nofoto)->where('komponen', 'hasilpemeriksaanttcmmtbxdrxpert_kodeunik')->first();
				if ($cetak != ''){
					$cetak = $cetak.'<div style="page-break-before: always">';
				}
				$cetak = $cetak.'
					<table cellpadding="0" cellspacing="0" width="800" border="0">
						<tr>
							<td colspan="8">
								<img src="'.$homebase.'/templateimage/kopsurat.png" width="100%" />
							</td>
						</tr>
						<tr>
							<td colspan="8" align="center"><strong><u>FORM PEMERIKSAAN MIKROBIOLOGI KLINIK</u></strong></td>
						</tr>
						<tr>
							<td width="45">&nbsp;</td>
							<td class="truncate" width="223" align="left" valign="top">Nomor Laboratorium</td>
							<td width="12">:</td>
							<td class="truncate" width="230" colspan="2" align="left" valign="top">'.$periksa->nofoto.'</td>
							<td width="128" align="left" valign="top">Tanggal Terima</td>
							<td width="12" align="left" valign="top">:</td>
							<td class="truncate" width="150" align="left" valign="top">'.$periksa->mulai.'</td>
						</tr>
						<tr>
							<td width="45">&nbsp;</td>
							<td class="truncate" align="left" valign="top">Nama Pasien</td>
							<td align="center" valign="top">:</td>
							<td class="truncate" colspan="2" align="left" valign="top">'.$periksa->nmpasien.'</td>
							<td width="128" align="left" valign="top">Tanggal MRS</td>
							<td width="12" align="left" valign="top">:</td>
							<td class="truncate" width="150" align="left" valign="top">'.$periksa->cetak.'</td>
						</tr>
						<tr>
							<td>&nbsp;</td>
							<td class="truncate" align="left" valign="top">Jenis Kelamin</td>
							<td align="center" valign="top">:</td>
							<td class="truncate" colspan="2" align="left" valign="top">'.$periksa->jkpasien.'</td>
							<td class="truncate" align="left" valign="top">No Rekam Medik</td>
							<td align="center" valign="top">:</td>
							<td class="truncate" align="left" valign="top">'.$periksa->noregister.'</td>
						</tr>
						<tr>
							<td>&nbsp;</td>
							<td class="truncate" align="left" valign="top">Usia</td>
							<td align="center" valign="top">:</td>
							<td class="truncate" colspan="2" align="left" valign="top">'.$periksa->usia.'</td>
							<td class="truncate" align="left" valign="top">Dokter Pengirim</td>
							<td align="center" valign="top">:</td>
							<td class="truncate" align="left" valign="top">'.$periksa->klinisi.'</td>
						</tr>
						<tr>
							<td>&nbsp;</td>
							<td class="truncate" align="left" valign="top">Tanggal Lahir</td>
							<td align="center" valign="top">:</td>
							<td class="truncate" colspan="2" align="left" valign="top">'.$periksa->tgllahirpasien.'</td>
							<td class="truncate" align="left" valign="top">Ruang Pengirim</td>
							<td align="center" valign="top">:</td>
							<td class="truncate" align="left" valign="top">'.$periksa->asalpasien.'</td>
						</tr>
						<tr>
							<td>&nbsp;</td>
							<td class="truncate" align="left" valign="top">Tanggal selesai hasil</td>
							<td align="center" valign="top">:</td>
							<td class="truncate" colspan="2" align="left" valign="top">'.$periksa->verifikasi.'</td>
							<td class="truncate" align="left" valign="top">Jenis Pemeriksaan</td>
							<td align="center" valign="top">:</td>
							<td class="truncate" align="left" valign="top">'.$periksa->reques.'</td>
						</tr>
						<tr><td colspan="8">&nbsp;</td></tr>
						<tr>
							<td>&nbsp;</td>
							<td class="truncate" align="left" valign="top">Barcode</td>
							<td align="center" valign="top">:</td>
							<td class="truncate" colspan="2" align="left" valign="top">'.$periksa->nofoto.'</td>
							<td align="left" valign="top" colspan="3"><img src="'.route('generate.barcode', ['data' => $periksa->nofoto]).'" alt="Barcode" style="max-width: 100%; height: auto;"></td>
						</tr>
					</table>';
			}
		}
		echo $cetak;
    }
	public function ctkLabel($id){
		$periksa        =   Periksa::where('nofoto', $id)->first();
		$id             =   $periksa->id;
		$idruangan      =   $periksa->ruangan_id;
		$statuse        =   $periksa->status;
		$idpasien       =   $periksa->pasien_id;
		$reques         =   $periksa->reques;
		$tanggal        =   $periksa->created_at->toDateString();
		$poli_id        =   $periksa->poli_id;
		$keterangan     =   $periksa->keterangan;
		$kesimpulan     =   $periksa->kesimpulan;
		$nofoto         =   $periksa->nofoto;
		$urgensi        =   $periksa->urgensi;
		$asuransi       =   $periksa->asuransi;
		$umur           =   $periksa->usia;
		$dlp            =   $periksa->dlp;
		$klinisi        =   $periksa->klinisi;
		$ppdssenior     =   $periksa->ppdssenior;
		$middleppds     =   $periksa->middleppds;
		$ppdsjunior     =   $periksa->ppdsjunior;
		$tandatangan    =   $periksa->tandatangan;
		$ruangan        =   $periksa->ruangan;
		$baca           =   $periksa->baca;
		$verifikasi     =   $periksa->verifikasi;
		$getumur		= 	explode(' ',$umur);
		$umur			= 	$getumur[0];
		$jk 			= 	$periksa->jkpasien;
        $tgllahir		= 	$periksa->tgllahirpasien;
        $kota 			= 	'';
        $alamat 		= 	$periksa->alamatpasien;
        $nama 			= 	$periksa->nmpasien;
        $norm 			= 	$periksa->noregister;
		$alamat 		= 	substr($kota, 0, 20);

        $cetak          = '<table width="100%" class="printiki" border="0" cellspacing="0" cellpadding="0">
							<tr>
								<td colspan="3" style="border-bottom-color: #000; border-bottom-style: double; border-bottom-width: thin;" valign="bottom"><br /><strong>'.$periksa->noloket.'</td>

							</tr>
							<tr>
								<td valign="top">No.RM</td>
								<td valign="top">:</td>
								<td valign="top">'.$norm.'</td>
							</tr>
							<tr>
								<td valign="top">Nama</td>
								<td valign="top">:</td>
								<td valign="top">'.$nama.'</td>
							</tr>
 					  		<tr>
								<td valign="top">Tgl. Lahir (Umur)</td>
								<td valign="top">:</td>
								<td valign="top">'.$tgllahir.' ('.$umur.')</td>
							</tr>
							<tr>
								<td valign="top">Tgl. Register</td>
								<td valign="top">:</td>
								<td valign="top">'.$tanggal.'</td>
							</tr>
							<tr>
								<td valign="top">Ruang/Poli</td>
								<td valign="top">:</td>
								<td valign="top">'.$periksa->asalpasien.'</td>
							</tr>
						</table>';
		$data['datatoprint'] = $cetak;
        return view('cetak.labelpengambilan', $data);
    }
	public function exTandaTerima(Request $request) {
		$data		= [];
		$idcetak	= $request->input('set01');
		$kanan 		= '';
		$homebase	= url("/");
		$cetak 		= '<table class="table table-striped table-bordered" border="1"><thead><tr><th align="center"><strong>NO</strong></th><th align="center"><strong>No.Lab</strong></th><th align="center"><strong>No.RM</strong></th><th align="center"><strong>Nama</strong></th><th align="center"><strong>Kelamin</strong></th><th align="center"><strong>Tanggal</strong></th><th align="center"><strong>Asal Pasien</strong></th><th align="center"><strong>Kode</strong></th><th align="center"><strong>Nama Kode</strong></th><th align="center" colspan="2"><strong>Paraf</strong></th></tr></thead><tbody>';
		$nomor 		= 1;
		foreach($idcetak as $rid){
			$periksa        =   Periksa::where('id', $rid)->first();
			if (isset($periksa->id)){
				Periksa::where('id', $periksa->id)->update([
					'status' 	=> 'Penerimaan Sampel',
				]);
				if ($kanan == ''){
					$kolomttd 	= '<td><font color="grey">'.$nomor.'</font></td><td>&nbsp;</td>';
					$kanan 		= '1';
				} else {
					$kolomttd 	= '<td>&nbsp;</td><td><font color="grey">'.$nomor.'</font></td>';
					$kanan 		= '';
				}
				$cetak = $cetak.'<tr><td align="center">'.$nomor.'</td><td>'.$periksa->nofoto.'</td><td>'.$periksa->noregister.'</td><td>'.$periksa->nmpasien.'</td><td>'.$periksa->jkpasien.'</td><td>'.$periksa->mulai.'</td><td>'.$periksa->asalpasien.'</td><td>'.$periksa->kd_spesimen.'</td><td>'.$periksa->nm_spesimen.'</td>'.$kolomttd.'</tr>';
				$nomor++;
			}
		}
		$cetak = $cetak.'</tbody></table>';
		echo $cetak;
    }
	public function ekstrakExpertise(Request $request) {
		$data		= [];
		$nofoto		= $request->input('nofoto');
		$noregister	= $request->input('noregister');
		$homebase	= url("/");
		$alldata    = Periksa::where('noregister', $noregister)->get();
		if (!empty($alldata)){
			foreach($alldata as $rows){
				$urlhasil 		= url('/').'/hasil/'.$rows->nofoto;
				$status 		= $rows->status;
				$keterangan		= '';
				if ($status == '' OR is_null($status)){
					$status 	= 'new';
				} else {
					$cekbatal 	= explode('batalkan dengan alasan ', $status);
					if (isset($cekbatal[1])){
						$keterangan = $cekbatal[1];
						$status 	= 'Batal';
					} else {
						if ($status == 'Arsip' OR $status == 'Selesai'){
							$status = 'Selesai';
						} elseif ($status == 'Decliend'){
							$status = 'Ulang';
							$keterangan = 'Di Periksa Ulang PPDS';
						} else {
							$status = 'Proses';
						}
					}
				}
				$data[] = array(
					'nofoto' 			=> $rows->nofoto,
					'nolab' 			=> $rows->orderid,
					'norm' 				=> $rows->norm,
					'jenispemeriksaan' 	=> $rows->reques,
					'mulai' 			=> $rows->daftar,
					'selesai' 			=> $rows->verifikasi,
					'urlhasil' 			=> $urlhasil,
					'status'			=> $status,
					'keterangan'		=> $keterangan,
					'rawdata'			=> self::genSurat($rows->id, 'dengan kop'),
				);
			}
		}
		return response()->json(['data' => $data], 201);
    }
	public function getNOLabnorm(Request $request) {
		$data		= [];
		$nolab		= $request->input('nolab');
		$noregister	= $request->input('noregister');
		$homebase	= url("/");
		$alldata    = Periksa::where('noregister', $noregister)->where('orderid', $nolab)->get();
		if (!empty($alldata)){
			foreach($alldata as $rows){
				$urlhasil 		= url('/').'/hasil/'.$rows->nofoto;
				$status 		= $rows->status;
				$keterangan		= '';
				if ($status == '' OR is_null($status)){
					$status 	= 'new';
				} else {
					$cekbatal 	= explode('batalkan dengan alasan ', $status);
					if (isset($cekbatal[1])){
						$keterangan = $cekbatal[1];
						$status 	= 'Batal';
					} else {
						if ($status == 'Arsip' OR $status == 'Selesai'){
							$status = 'Selesai';
						} elseif ($status == 'Decliend'){
							$status = 'Ulang';
							$keterangan = 'Di Periksa Ulang PPDS';
						} else {
							$status = 'Proses';
						}
					}
				}
				$data[] = array(
					'nofoto' 			=> $rows->nofoto,
					'nolab' 			=> $rows->orderid,
					'norm' 				=> $rows->norm,
					'jenispemeriksaan' 	=> $rows->reques,
					'mulai' 			=> $rows->daftar,
					'selesai' 			=> $rows->verifikasi,
					'urlhasil' 			=> $urlhasil,
					'status'			=> $status,
					'keterangan'		=> $keterangan,
					'rawdata'			=> self::genSurat($rows->id, 'dengan kop'),
				);
			}
		}
		return response()->json(['data' => $data], 201);
    }
}
