<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Http;

use App\Services\AstmMessageService;
use App\Services\SerialCommunicationService;
use App\Http\Controllers\SendMail;
use App\Http\Controllers\DokterController;
use App\Periksa;
use App\PeriksaTest;
use App\Pasien;
use App\Poli;
use App\Subpoli;
use App\Subsubpoli;
use App\Ruangan;
use App\User;
use App\Jadwalperiksa;
use App\Setting;
use App\PeriksaSYNC;
use App\Logbook;
use App\Worklist;
use App\Jawaban;
use App\PendaftaranOnListiner;
use App\Subjawaban;
use App\Organisms;
use App\Dokter;
use Validator;
use Session;
use DateTime;
use QrCode;
use Exception;

use Carbon\Carbon;

class FrontpageController extends Controller
{
	protected $lisServiceUrl;

    public function __construct()
    {
        // Mengambil URL service dari file .env, dengan fallback default
        $this->lisServiceUrl = env('LIS_SERVICE_URL', 'http://10.10.120.14:5000');
    }
	private function sendRegistrationToLis(array $data)
    {
        // Memetakan data dari fungsi register Anda ke format yang dibutuhkan LIS service
        // PENTING: Pastikan pemetaan ini benar, terutama 'test_code'.
        $payload = [
            'command' => 'register_patient',
            'data' => [
                'patient_name' => $data['nama'],
                'patient_id'   => $data['noregister'], // Menggunakan no register sebagai ID Pasien
                'sample_id'    => $data['nofoto'],     // Menggunakan nofoto sebagai ID Sampel unik
                'test_code'    => $data['kd_spesimen'],// Kode tes spesifik untuk GeneXpert (e.g., MTBRIF)
                'test_name'    => $data['nm_spesimen'],
                'dob'          => $data['tgllahir'] ? \Carbon\Carbon::parse($data['tgllahir'])->format('Ymd') : '',
                'gender'       => $data['jk'],
            ],
        ];
        try {
            $response = Http::timeout(30)->post($this->lisServiceUrl . '/command', $payload);

            if ($response->failed()) {
                Log::error('Gagal mengirim data pendaftaran ke LIS service.', [
                    'sample_id' => $data['nofoto'],
                    'status' 	=> $response->status(),
                    'response' 	=> $response->body()
                ]);
            } else {
                Log::info('Data pendaftaran berhasil dikirim ke LIS service.', [
                    'sample_id' => $data['nofoto'],
                    'response' 	=> $response->json()
                ]);
            }
        } catch (Exception $e) {
            Log::error('Koneksi ke LIS service gagal saat pendaftaran.', [
                'sample_id' => $data['nofoto'],
                'exception' => $e->getMessage()
            ]);
        }
    }
    public function index() {
		$data       		= [];
		$data['antrkrmsitu']= PeriksaSYNC::where('created_by', Session('username'))->where('status', '')->count();
		$i 					= 0;
		$yesterday 			= date("Y-m-d", strtotime( '-1 days' ) );
		$previlage 			= Session('previlage');
		$iduser 			= Session('id');
		$semua 				= 0;
		$fnk 				= 0;
		$fk 				= 0;
		$mri 				= 0;
		$ct 				= 0;
		$usg 				= 0;
		if ($previlage && $previlage != '') {
			$getttd			= User::where('id', $iduser)->first();
			$tandatangan	= $getttd->getTandatangan->xfile ?? '/boxed-bg.jpg';
			$ppds			= User::where('previlage', 'ppds')->count();
			$unveri			= Periksa::where('status', 'like', '%Un Verified%')->count();
			$hariini		= Periksa::whereDate('daftar', Carbon::today())->count();
			$kemarin		= Periksa::whereDate('daftar', $yesterday)->count();
			if ($hariini > $kemarin){
				$persen = $hariini - $kemarin;
				$tulis 	= '+ '.$persen;
			} else {
				$persen = $kemarin - $hariini;
				$tulis 	= '- '.$persen;
			}
			$data['tandatangan']        = $tandatangan;
			$data['totalkasus']         = $semua;
			$data['totalkasusfnk']		= $fnk;
			$data['totalkasusfk']       = $fk;
			$data['totalkasusmri']      = $mri;
			$data['totalkasusct']       = $ct;
			$data['totalkasususg']      = $usg;
			$data['totalppds']         	= $ppds;
			$data['butuhverifikasi']    = $unveri;
			$data['antrian']    		= $hariini;
			$data['persenantrian']    	= $tulis;
			return view('dokter.dashborad', $data);
		} else {
			try {
				$qrcode 				= base64_encode(QrCode::format('png')->size(100)->generate(url('/')));
			} catch (\Exception $e) {
				$qrcode 				= ' ';
			}
			$getdomain 			= url()->current();
			$data['qrcode'] 	= $qrcode;
			$data['getdomain'] 	= $getdomain;
			$data['firebaseid'] = '';
			return view('jadwal', $data);
		}
    }
	public function getKalenderlist() {
        $data   = Periksa::select('id as idne', 'mulai as start', 'akhir as end', 'reques as description', 'urgensi as location', 'ruangan as calendar', DB::raw("CONCAT('on ', ruangan, ' Request ', reques, '  for Patient ID ', noregister) as subject"), 'daftar', 'ruangan_id')->where('daftar', '>=', Carbon::yesterday())->orderBy('daftar', 'ASC')->orderBy('ruangan_id', 'ASC')->get();
    	echo json_encode($data);
    }
	public function pendaftaran() {
		if (Session::get('previlage') == ''){
			return redirect('/login');
		} else {
			$polis  = Ruangan::groupBy('poli')->select('poli')->get();
			$data	= [];
			$i      = 0;
			foreach ($polis as $poli) {
				$j  = 0;
				$poli   = $poli->poli;
				$rooms  = Ruangan::where('poli', $poli)->orderBy('ruangan', 'ASC')->get();
				foreach ($rooms as $room) {
					$data['ruangans'][$i][$j]['id']  	= $room->id;
					$data['ruangans'][$i][$j]['ruangan']= $room->ruangan;
					$j++;
				}
				$i++;
			}
			$x  = 0;
			foreach ($polis as $poli) {
				$data['polis'][$x]  = $poli->poli;
				$x++;
			}
			if ($x == 0){
				$data['ruangans'][0][0]['id']  		= 0;
				$data['ruangans'][0][0]['ruangan']	= 'No Data';
				$data['polis'][0]  					= 'No Data';
			}
			$dokters            = User::where('previlage', 'supervisor')->get();
			$previlage 			= Session('previlage');
			$data['lisspesimen']= Organisms::where('kelompok', 'listkodespesimen')->get();
			$data['dokters']    = $dokters;
			$data['polis']		= Poli::all();
			return view('pendaftaran', $data);
		}
	}
	public function autocompleteKlinik(Request $request){
		$search = $request->get('term');
		$result = Ruangan::where('ruangan', 'LIKE', '%'.$search.'%')->get();
		return response()->json($result);
	}
	public function autocompleteDokter(Request $request){
		$search = $request->get('term');
		$result = Dokter::where('nama', 'LIKE', '%'.$search.'%')->get();
		return response()->json($result);
	}
	public function viewMikro() {
		if (!Session::has('previlage')) {
			return redirect('/login');
		}
		$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'],
		]);
	
		// Mapping nama kelompok di array dengan nama kelompok di tabel database
		$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',
		];
	
		// Ambil data tambahan untuk kelompok organisme dari koleksi yang sudah diambil
		foreach ($kelompokMapping as $key => $kelompok) {
			$data[$key] = $allOrganisms->where('kelompok', $kelompok)->values();
		}
	
		// Kembalikan view dengan data
		return view('dokter.ppds', $data);
	}
	public function pengambilan() {
		if (Session::get('previlage') == ''){
			return redirect('/login');
		} else {
			$polis  = Ruangan::groupBy('poli')->select('poli')->get();
			$data 	= [];
			return view('pengambilan', $data);
		}
	}
    public function auto(Request $request) {
		return response()->json(DB::table('pasien')->orderBy('id', 'asc')->get()->map(fn($pasien) => ['id' => $pasien->id, 'nama' => $pasien->nama, 'tulis' => $pasien->nama . ' ( ' . $pasien->alamat . ' ' . $pasien->kota . ' )']));
    }
    public function kirimWA(Request $request) {
    	$id			= $request->input('set01');
    	$email		= $request->input('set02');
		$hape		= $request->input('set03');
		$getdata	= Periksa::where('id', $id)->first();
		$nofoto		= $getdata->nofoto;
		$norm		= $getdata->noregister;
		Pasien::where('norm', $norm)->update([
			'telpon'     =>  $hape
		]);
		$alamathasil		= url('/').'/hasil/'.$nofoto;
      	$linke				= 'Berikut%20kami%20kirimkan%20hasil%20dari%20pemeriksaan​%20foto%20anda,%20silahkan%20klik%20tautan%20dibawah%20ini​%0a'.$alamathasil;
		$linke 				= 'https://api.whatsapp.com/send?phone='.$hape.'&text='.$linke;
		echo $linke;
	}
	public function getListdoneonly(Request $request) {
		$arraylist  = [];
		$jenis 		= $request->input('val01');
		$mulai 		= $request->input('val02');
		$akhir 		= $request->input('val03');
		$data       = $this->getDataBasedOnMaster('pengambilan', $jenis, $mulai, $akhir, '');
		if (!empty($data)){
			$dataArray = $data->get()->toArray();
			$total 		= count($dataArray);
			$arraylist = array_map(function ($list) use ($master) {
                $tgl        = $list['tgllahirpasien'];
				$poli_id    = $list['poli_id'];
				$foto    	= $list['foto'];
				$baca    	= $list['baca'];
				$export    	= $list['export'];
				$nofoto    	= $list['nofoto'];
				$noregister = $list['noregister'];
				$usia    	= $list['usia'];
				$urgensi    = $list['urgensi'];
				$reques    	= $list['reques'];
				$ruangan    = $list['ruangan'];
				$daftar    	= $list['daftar'];
				$status    	= $list['status'];
				$asalpasien	= $list['asalpasien'];
				$dokter_id	= $list['dokter_id'];
				$ppdssenior	= $list['ppdssenior'];
				$middleppds	= $list['middleppds'];
				$ppdsjunior	= $list['ppdsjunior'];
				$middleppds2= $list['ppdsmiddle2'];
				$ppdsjunior2= $list['ppdsjunior2'];
				$pasiedin	= $list['pasien_id'];
				$keterangan	= $list['keterangan'];
				$kesimpulan	= $list['kesimpulan'];
				$verifikasi	= $list['verifikasi'];
				$nama       = $list['nmpasien'];
				$jk         = $list['jkpasien'];
				$telpon     = $list['tlppasien'];
				$alamat     = $list['alamatpasien'];
				$tgllahir   = $list['tgllahirpasien'];
                $from       = $verifikasi ? \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $verifikasi) : null;
                $to         = $verifikasi ? \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $verifikasi)->toString() : '';
                if ($from && $from->isValid()) {
                    $durasi = $verifikasi ? \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $verifikasi)->diffForHumans($from) : 'On Progress';
                } else {
                    $durasi = 'On Progress';
                }
                if ($middleppds2 != 0){
					$ppdsas 	= 'Middle';
					$otherppds	= $list['nmppdsmiddle2'];
				} else {
					$ppdsas 	= 'Junior';
					$otherppds	= $ppdsjunior2;
					$otherppds	= $list['nmppdsjunior2'];
				}
				
                $arrdaftar		= explode(" ", $daftar);
				$tgldaftar		= $arrdaftar[0];
				$jamdaftar		= $arrdaftar[1];
				$daftar			= $tgldaftar;
                $tglfoto        = $foto ?: date("Y-m-d H:i:s");
                $datatampilan 	= $this->setStatusStyles($status, $nofoto, $noregister, $nama, $telpon, $jk, $usia, $urgensi, $reques, $ruangan, $daftar, $asalpasien);
                return [
                    'asalpasien'    => $list['asalpasien'],
                    'tlsnofoto'     => $datatampilan['nofoto'],
                    'tlsnoregister' => $datatampilan['noregister'],
                    'tlsnama'       => $datatampilan['nama'],
                    'tlsjk'         => $datatampilan['jk'],
                    'tlsusia'       => $datatampilan['usia'],
                    'tlsurgensi'    => ($list['urgensi'] == 'CITO') ? '<span style="background-color: red;">C I T O</span>' : $datatampilan['urgensi'],
                    'tlsreques'     => $datatampilan['reques'],
                    'tlsruangan'    => $list['ruangan'],
                    'tlsdaftar'     => $datatampilan['daftar'],
                    'tlsstatus'     => $datatampilan['status'],
                    'id'            => $list['id'],
                    'nofoto'        => $nofoto,
                    'noregister'    => $noregister,
                    'nama'          => $nama,
                    'jk'            => $jk,
                    'usia'          => $usia,
                    'urgensi'       => $urgensi,
                    'poli'          => $reques,
                    'idpasien'      => $pasiedin,
                    'ruangan'       => $ruangan,
                    'daftar'        => $list['daftar'],
                    'daftartgl'     => $daftar,
                    'daftarjam'     => $jamdaftar,
                    'status'        => $status,
                    'dokter'        => $master != 'kiriman' ? $list['nmdokter'] : '',
                    'ppds1'         => $master != 'kiriman' ? $list['nmppdssenior'] : '',
                    'ppds2'         => $master != 'kiriman' ? $list['nmmiddleppds'] : '',
                    'ppds3'         => $master != 'kiriman' ? $list['nmppdsjunior'] : '',
                    'keterangan'    => $keterangan,
                    'kesimpulan'    => $kesimpulan,
                    'idruangan'     => $list['ruangan_id'],
                    'iddokter'     	=> $list['dokter_id'],
                    'ppdssenior'   	=> $list['ppdssenior'],
                    'middleppds'    => $list['middleppds'],
                    'ppdsjunior'    => $list['ppdsjunior'],
                    'diagnosa'    	=> $list['diagnosa'],
                    'diagnosa2'    	=> $list['diagnosa2'],
                    'kd_spesimen'   => $list['kd_spesimen'],
                    'nm_spesimen'   => $list['nm_spesimen'],
                    'berat'    		=> $list['berat'],
                    'klinis'    	=> $list['klinis'],
                    'klinisi'    	=> $list['klinisi'],
                    'filefoto'    	=> $list['filefoto'],
                    'dlp'    		=> $list['dlp'],
                    'analis'   		=> $list['analis'],
                    'excutor'    	=> $list['excutor'],
                    'modality'    	=> $list['modality'],
                    'viewfoto'    	=> $list['foto'],
                    'tglfoto'    	=> $tglfoto,
		            'nmppdssenior'  => $list['nmppdssenior'],
                    'nmmiddleppds'  => $list['nmmiddleppds'],
                    'nmppdsjunior'  => $list['nmppdsjunior'],
                    'nmppdsmiddle2' => $list['nmppdsmiddle2'],
                    'nmppdsjunior2' => $list['nmppdsjunior2'],
                    'nmanalis' 		=> $list['nmanalis'],
                    'nmexcutor'    	=> $list['nmexcutor'],
                    'telpon'    	=> $list['tlppasien'],
                    'asuransi'    	=> $list['asuransi'],
                    'tgllahir'    	=> $list['tgllahirpasien'],
                    'alamat'    	=> $list['alamatpasien'],
                    'timestamp1'    => $from ? $from->toString() : null,
                    'timestamp2'    => $to,
                    'durasi'    	=> $durasi,
                    'ppdsas'    	=> $ppdsas,
                    'otherppds'    	=> $otherppds,
                ];
            }, $dataArray);
        }
		$response = [
			'message'   => 'List Laporan',
			'data'      => $arraylist,
			'total'     => $total
		];
        return response()->json($response, 200);
    }
	public function viewCheckout() {
		$data       	= [];
		$api_access_key = '$2y$10$2DkIHkWoYvCH.U2U.2dCi.SrDITVitZrJhQGaSrFQ3Hcsn/RnwXOe';
		$msg 			= array (
			'fakultas' 	=>  ''
		);
		$headers = array
		(
			'Accept: application/json',
			'Content-type: application/json',
			'Authorization: Bearer '.$api_access_key,
		);
		$url = 'https://insitu.fk.ub.ac.id/api/auth/listallpejabat';
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_POST, false); //POST Set True
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,  0);
		curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );		
		//curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($msg));
		$result = curl_exec($ch);
		curl_close($ch);
		$response		= json_decode($result);
		$data['dosens']	= $response;
		$url 			= 'https://insitu.fk.ub.ac.id/api/auth/listallkegiatan';
		$ch 			= curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_POST, false); //POST Set True
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,  0);
		curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );		
		//curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($msg));
		$result2 = curl_exec($ch);
		curl_close($ch);
		$response2				= json_decode($result2);
		$data['jkegiatan']		= $response2;
		$data['antrkrmsitu']	= PeriksaSYNC::where('created_by', Session('username'))->where('status', '')->count();
		$data['allspv']			= User::where('previlage', 'supervisor')->get();
		$data['biodata']		= [];
		return view('dokter.synctoinsitu', $data);
    }
	public function exDatapenugasan(Request $request) {
        $validator  = Validator::make($request->all(), [
            'val01'	=>  'required',
            'val03' =>  'required',
            'val04' =>  'required',
            'val05' =>  'required',
            'val06' =>  'required',
            'val07' =>  'required',
            'val08' =>  'required',
            'val09' =>  'required',
        ]);
        if($validator->fails()) {
        	return response()->json(['icon' => 'error', 'warna' => '#bf441d', 'status' => 'Gagal', 'message' => 'Mohon Lengkapi Data Anda']);
			return back();
		} else {										
			$arraylist  	= [];
			$i				= 0;
			$lists			= PeriksaSYNC::where('created_by', Session('username'))->where('status', '')->get();
			if (!empty($lists)){
				foreach ($lists as $list) {
					$diagnosa 		= '';
					$cekreques   	= Logbook::where('id', $list->diagnosa)->first();
					if (isset($cekreques->kepanjangan)){
						$diagnosa   = $cekreques->kepanjangan;
					}
					$arraylist[] = array(
						'diagnosa2'     => $list->diagnosa2,   
						'id'            => $list->id,   
						'telpon'        => $list->tlppasien,
						'diagnosa'    	=> $diagnosa,
						'kd_spesimen'	=> $list->kd_spesimen,
						'nm_spesimen'	=> $list->nm_spesimen,
						'berat'    		=> $list->berat,
						'klinis'    	=> $list->klinis,
						'klinisi'    	=> $list->klinisi,
						'dlp'    		=> $list->dlp,
						'modality'    	=> $list->modality,
						'tgl'        	=> $list->tgllahirpasien,
						'foto'    		=> $list->foto,
						'baca'    		=> $list->baca,
						'export'    	=> $list->export,
						'nofoto'    	=> '<a href="'.url('/').'/hasil/'.$list->nofoto.'">'.$list->nofoto.'</a>',
						'noregister' 	=> $list->noregister,
						'usia'    		=> $list->usia,
						'urgensi'    	=> $list->urgensi,
						'reques'    	=> $list->reques,
						'ruangan'    	=> $list->ruangan,
						'daftar'    	=> $list->daftar,
						'status'    	=> $list->status,
						'asalpasien'	=> $list->asalpasien,
						'ppdssenior'	=> $list->nmppdssenior,
						'middleppds'	=> $list->nmmiddleppds,
						'ppdsjunior'	=> $list->nmppdsjunior,
						'middleppds2'	=> $list->nmmiddleppds2,
						'ppdsjunior2'	=> $list->nmppdsjunior2,
						'analis'		=> $list->nmanalis,
						'excutor'		=> $list->nmexcutor,
						'keterangan'	=> $list->keterangan,
						'kesimpulan'	=> $list->kesimpulan,
						'verifikasi'	=> $list->verifikasi,
						'nama'    		=> $list->nmpasien,
						'jk'    		=> $list->jkpasien,
						'dokter'		=> $list->nmdokter,
					);
					$i++;
				}
			}
			if ($i == 0){
				return response()->json(['icon' => 'error', 'warna' => '#bf441d', 'status' => 'Gagal', 'message' => 'Sync Gagal, Mohon Pilih Dulu Kasus Yang Ingin di Laporkan di Menu Modalitas']);
				return back();
			} else {
				$api_access_key = '$2y$10$2DkIHkWoYvCH.U2U.2dCi.SrDITVitZrJhQGaSrFQ3Hcsn/RnwXOe';
				$msg 			= array (
					'arraylist'		=> json_encode($arraylist),
					'set01'			=> $request->input('file'),
					'set02'			=> $request->input('file2'),
					'nim'			=> $request->input('val01'),
					'idps'			=> $request->input('val02'),
					'tanggal'		=> $request->input('val03'),
					'waktu'			=> $request->input('val04'),
					'topik'			=> $request->input('val05'),
					'masterno'		=> $request->input('val06'),
					'deskripsi'		=> $request->input('val07'),
					'kodejenis'		=> $request->input('val08'),
					'durasi'		=> $request->input('val09'),
					'rumahsakit'	=> $request->input('val10'),
					'rumahsakitnama'=> $request->input('val11'),
					'idne'			=> $request->input('val12'),
					'laborat'		=> $request->input('val13'),
					'spvlain'		=> $request->input('val14'),
					'jumlah'		=> $request->input('val15'),
					'spv2'			=> $request->input('val16'),
					'spv3'			=> $request->input('val17'),
					'role'			=> $request->input('val18'),
					'role2'			=> $request->input('val19'),
					'semester'		=> $request->input('val20'),
				);
				$headers = array
				(
					'Accept: application/json',
					'Content-type: application/json',
					'Authorization: Bearer '.$api_access_key,
				);
				
				$url 	= 'https://insitu.fk.ub.ac.id/api/auth/synckegiatandrris';
				$ch		= curl_init();
				curl_setopt($ch, CURLOPT_URL, $url);
				curl_setopt($ch, CURLOPT_POST, true); //POST Set True
				curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
				curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,  0);
				curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );		
				curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($msg));
				//curl_setopt($ch, CURLOPT_VERBOSE, true);
				//$letakfile= public_path('logfile.txt');
				//$verbose  = fopen($letakfile, 'w+');
				//curl_setopt($ch, CURLOPT_STDERR, $verbose);
				$result = curl_exec($ch);
				curl_close($ch);
				if ($result){
					$result	= json_decode($result, true);
					if ($result['icon'] != 'error' AND $result != null){
						PeriksaSYNC::where('created_by', Session('username'))->where('status', '')->update([
							'status'	=> $result['icon']
						]);
						return response()->json(['icon' => 'success', 'warna' => $result['warna'], 'status' => $result['status'], 'message' => $result['message']]);
						return back();
					} else {
						return response()->json(['icon' => 'error', 'warna' => $result['warna'], 'status' => $result['status'], 'message' => $result['message']]);
						return back();
					}
				} else {
					return response()->json(['icon' => 'error', 'warna' => '#bf441d', 'status' => 'Gagal', 'message' => 'Sync Gagal, Hubungi TIM IT Kedua Belah Pihak']);
					return back();
				}
			}
        }
    }
	public function jsonAllorderlist(){
        $allpejabat = Poli::all();
        echo json_encode($allpejabat);
    }
    public function registerApiFormatJSON(Request $request) {
    	$nama 			= $request->input('nama');
		$noregister     = $request->input('norm');
		$jk 			= $request->input('kelamin') ?? 'L';
		$tgllahir   	= $request->input('tgllahir') ?? date('Y-m-d');
		$telpon			= $request->input('nohap') ?? '0000000000';
		$alamat 		= $request->input('alamat') ?? config('global.addressapps');
		$kota 			= $request->input('kota') ?? config('global.subdomainapps');
		$berat   		= $request->input('beratbadan') ?? 0;
		$nik   			= $request->input('nik') ?? 0;
		$bpjs   		= $request->input('bpjs') ?? 0;
		$tlsasal       	= $request->input('asalpasien');
		$nmrs   		= $request->input('namarspengirim') ?? 'RSSA Malang';
		$klinisi   		= $request->input('drpeminta');
		$insurance      = $request->input('asuransi') ?? 'UMM';
		$rekues         = $request->input('layanan');
		$urgensi        = $request->input('urgensi') ?? 'Elective';
		$kd_spesimen    = $request->input('kode') ?? '';
		$nm_spesimen    = $request->input('spesimen') ?? '';
		$klinis        	= $request->input('klinis');
		$notransaksi	= $request->input('notransaksi');
		$telpon 		= str_replace('_', '', $telpon);
		$rekues 		= str_replace('_', ' ', $rekues);
		$tlsasal 		= str_replace('_', ' ', $tlsasal);
		$iddokter		= '';
		$ruangan        = 1;
		$kelompok		= 'admin';
		$daftar         = date('Y-m-d H:i:s');
		$mulai			= $daftar;
		$tambah			= ' + 360 second';
		$akhir			= date('Y-m-d h:i:s',strtotime($tambah,strtotime($daftar)));
		$start 			= strtotime(date("Y-m-d H:i:s",strtotime($mulai)));
		$finish 		= strtotime(date("Y-m-d H:i:s",strtotime($akhir)));
		$tglsekarang	= date('Y-m-d');
		$noregister		= strtoupper($noregister);
		$yy				= date("Y");
		$mm				= date("m");
		$terjadwal 		= 'sekarang';
		$kamar 			= 'Mikrobiologi';
		$tgllahir 		= \Carbon\Carbon::createFromFormat('Y-m-d', $tgllahir);
		$pasien    		= Pasien::where('norm', $noregister)->first();
		try {
			if (isset($pasien->id)) {
				$pasien_id	= $pasien->id;
				Pasien::where('norm', $noregister)->update([
					'nama'          =>  $nama,
					'jk'            =>  $jk,
					'tgl_lahir'     =>  $tgllahir,
					'kota'          =>  $kota,
					'telpon'        =>  $telpon,
					'alamat'        =>  $alamat,
					'nik'        	=>  $nik,
					'bpjs'        	=>  $bpjs,
				]);
			} else {
				$pasien_id = Pasien::insertGetId([
					'norm'          =>  $noregister,
					'nama'          =>  $nama,
					'jk'            =>  $jk,
					'tgl_lahir'     =>  $tgllahir,
					'kota'          =>  $kota,
					'telpon'        =>  $telpon,
					'alamat'        =>  $alamat,
					'nik'        	=>  $nik,
					'bpjs'        	=>  $bpjs,
				]);
			}
		} catch (\Exception $e) {
			Log::error('Error in register Pasien: '.$e->getMessage());
		}
		
		$datetime   = new DateTime($tgllahir);
		$today      = new DateTime();
		$diff       = $today->diff($datetime);
		$tahun      = $diff->y;
		$bulan      = $diff->m;

		if ($tahun ==0) {
			$usia   = $bulan." Bulan";
		} else {
			$usia   = $tahun." Tahun, ". $bulan. " Bulan";
		}
		$jruang 	= Ruangan::where('id', $ruangan)->first();
		if (isset($jruang->ruangan)){
			$kamar 	= $jruang->ruangan;
		} else { $kamar = '-'; $ruangan = 1; }
		$tahuncari		= date("Y");
		$cekloket		= Periksa::whereNotNull('noloket')->where('daftar', 'LIKE', $tahuncari.'%')->count();
		if ($cekloket == 0){
			$noloket 	= 1;
		} else {
			$getloket	= Periksa::whereNotNull('noloket')->where('daftar', 'LIKE', $tahuncari.'%')->orderBy('noloket', 'DESC')->first();
			$noloket	= $getloket->noloket;
			$noloket	= $noloket + 1;
		}
		$code_poli  	= 'Mikrobiologi';
		if ($rekues == '' OR is_null($rekues)){
			$poli_id	= 0;
		} else {
			$check   		= Poli::where('subpoli', $rekues)->first();
			if (isset($check->id)){
				$poli_id	= $check->id;
				$kd_spesimen= $check->subsubpoli;
				$nm_spesimen= $check->modaliti;
			} else {
				$poli_id 	= Poli::insertGetId([
					'poli'		=> 'Mikrobiologi',
					'subpoli'	=> $rekues,
				]);
			}
		}
		
		$nofoto 	= date('y').'-'.sprintf("% 06s", $noloket);
		if ($iddokter == ''){
			$iddokter	= 0;
			$dokter		= null;
		} else {
			$getdokter 	= User::where('id', $iddokter)->first();
			if (isset($getdokter->nama)){
				$dokter 	= $getdokter->nama;
			} else { $dokter = 'Dokter Spesialis'; }
		}
		$clientIp 			= $request->server('HTTP_X_FORWARDED_FOR') ?: $request->ip();
		$clientIpNumeric 	= ip2long($clientIp);
		$periksaid 			= Periksa::insertGetId([
			'mulai'        	=>  $mulai,
			'akhir'        	=>  $akhir,
			'noloket'       =>  $noloket,
			'nofoto'        =>  $nofoto,
			'noregister'    =>  $noregister,
			'asalpasien'    =>  $tlsasal,
			'nmrs'    		=>  $nmrs,
			'pasien_id'     =>  $pasien_id,
			'nmpasien'		=> 	$nama,
			'jkpasien'		=> 	$jk,
			'ktp'			=> 	$nik,
			'bpjs'			=> 	$bpjs,
			'tgllahirpasien'=> 	$tgllahir,
			'tlppasien'		=> 	$telpon,
			'alamatpasien'	=> 	$alamat,
			'reques'     	=>  $rekues,
			'usia'          =>  $usia,
			'berat'         =>  $berat,
			'ruangan_id'    =>  $ruangan,
			'ruangan'    	=>  $kamar,
			'klinisi'       =>  $klinisi,
			'klinis'		=>  $klinis,
			'poli_id'       =>  $poli_id,
			'kd_spesimen'	=>  $kd_spesimen,
			'nm_spesimen'	=>  $nm_spesimen,
			'keterangan'    =>  '',
			'kesimpulan'    =>  '',
			'asuransi'      =>  $insurance,
			'urgensi'       =>  $urgensi,
			'daftar'        =>  $mulai,
			'pendaftar'   	=>  $clientIpNumeric,
			'nmpendaftar'	=>  $clientIp,
			'orderid'		=> 	$notransaksi,
		]);
		$pesan 			= $nofoto;
		if ($kd_spesimen != '' AND $nm_spesimen != ''){
			PendaftaranOnListiner::updateOrCreate(
				[
					'rnoreg'	=> $nofoto,
				],
				[
					'rtglast'		=> $tglsekarang,
					'norm'			=> $noregister,
					'nama'			=> $nama,
					'alamat'		=> $alamat,
					'telp'			=> $telpon,
					'hp'			=> $telpon,
					'tgllahir'		=> $tgllahir,
					'umur'			=> $usia,
					'rjenis'		=> $jk,
					'kodedok'		=> $notransaksi,
					'namadok'		=> $klinisi,
					'ruangan'		=> $kamar,
					'tes'			=> $rekues,
					'alat'			=> 'All',
					'kd_spesimen'	=> $kd_spesimen,
					'nm_spesimen'	=> $nm_spesimen,
				]
			);
			$dataForLis = [
				'nama' 			=> $nama,
				'noregister' 	=> $noregister,
				'nofoto' 		=> $nofoto,
				'kd_spesimen' 	=> $kd_spesimen,
				'nm_spesimen' 	=> $nm_spesimen,
				'tgllahir' 		=> $tgllahir,
				'jk' 			=> $jk,
			];
			//$this->sendRegistrationToLis($dataForLis);
		}
		if ($pesan != ''){
			return response()->json(['status' => 'Sukses', 'message' => $pesan], 201);
		} else {
			return response()->json(['status' => 'Failed', 'message' => 'Mohon Menentukan Layanan Yang di Inginkan'], 500);
		}
	}
	public function registerApi(Request $request) {
		//Log::info(' Incomming '.json_encode($request->input()));
		$decodedData 	= $request->json()->all();
		$norm 			= $decodedData['norm'] ?? null;
		$nama 			= $decodedData['nama'] ?? null;
		$alamat 		= $decodedData['alamat'] ?? config('global.addressapps');
		$kota 			= $decodedData['kota'] ?? config('global.subdomainapps');
		$tgllahir 		= $decodedData['tgllahir'] ?? date('Y-m-d');
		$nohap 			= $decodedData['nohap'] ?? '0000000000';
		$jk 			= $decodedData['kelamin'] ?? 'L';
		$urgensi 		= $decodedData['urgensi'] ?? 'Elective';
		$berat 			= $decodedData['beratbadan'] ?? '0';
		$nik 			= $decodedData['nik'] ?? '0';
		$bpjs 			= $decodedData['nobpjs'] ?? '0';
		$drpeminta 		= $decodedData['drpeminta'] ?? null;
		$tlsasal 		= $decodedData['asalpasien'] ?? null;
		//$rekues 		= $decodedData['layanan'] ?? null;
		$statusbayar 	= $decodedData['statusbayar'] ?? null;
		$notransaksi 	= $decodedData['notransaksi'] ?? null;
		$insurance 		= $decodedData['asuransi'] ?? 'UMM';
		$klinis 		= $decodedData['klinis'] ?? null;
		$klinisi 		= $decodedData['klinisi'] ?? $drpeminta;
		$rekues 		= $decodedData['kode'] ?? null;
		$nm_spesimen 	= $decodedData['spesimen'] ?? null;
		$pengambilan 	= $decodedData['pengambilan'] ?? null;
		$nmrs 			= $decodedData['namarspengirim'] ?? 'RSSA Malang';
		$telpon 		= str_replace('_', '', $nohap);
		//$rekues 		= str_replace('_', ' ', $rekues);
		$tlsasal 		= str_replace('_', ' ', $tlsasal);
		$klinisi 		= str_replace('_', ' ', $klinisi);
		$nama 			= str_replace('_', ' ', $nama);
		$alamat 		= str_replace('_', ' ', $alamat);
		$kd_spesimen	= '';
		$getkodespesimen= Organisms::where('name', $nm_spesimen)->where('kelompok', 'listkodespesimen')->first();
		if (isset($getkodespesimen->category)){
			$kd_spesimen= $getkodespesimen->category;
		} else {
			$cekdulu = explode(' ', $nm_spesimen);
			if (isset($cekdulu[1])){
				$kd_spesimen = str_replace('.', '', $cekdulu[0]);
			} else {
				foreach ($cekdulu as $kata) {
					$kd_spesimen .= substr($kata, 0, 1);
				}
			}
			Organisms::create([
				'name'		=> $nm_spesimen,
				'category'	=> $kd_spesimen,
				'kelompok'	=> 'listkodespesimen'
			]);
			
		}
		$iddokter		= '';
		$ruangan        = 1;
		$kelompok		= 'admin';
		$daftar         = date('Y-m-d H:i:s');
		$mulai			= $daftar;
		$tambah			= ' + 360 second';
		$akhir			= date('Y-m-d h:i:s',strtotime($tambah,strtotime($daftar)));
		$start 			= strtotime(date("Y-m-d H:i:s",strtotime($mulai)));
		$finish 		= strtotime(date("Y-m-d H:i:s",strtotime($akhir)));
		$tglsekarang	= date('Y-m-d');
		$noregister		= strtoupper($norm);
		$yy				= date("Y");
		$mm				= date("m");
		$terjadwal 		= 'sekarang';
		$kamar 			= 'Mikrobiologi';
		$tgllahir 		= \Carbon\Carbon::createFromFormat('Y-m-d', $tgllahir);
		$pasien    		= Pasien::where('norm', $noregister)->first();
		try {
			if (isset($pasien->id)) {
				$pasien_id	= $pasien->id;
				Pasien::where('norm', $noregister)->update([
					'nama'          =>  $nama,
					'jk'            =>  $jk,
					'tgl_lahir'     =>  $tgllahir,
					'kota'          =>  $kota,
					'telpon'        =>  $telpon,
					'alamat'        =>  $alamat,
					'nik'        	=>  $nik,
					'bpjs'        	=>  $bpjs,
				]);
			} else {
				$pasien_id = Pasien::insertGetId([
					'norm'          =>  $noregister,
					'nama'          =>  $nama,
					'jk'            =>  $jk,
					'tgl_lahir'     =>  $tgllahir,
					'kota'          =>  $kota,
					'telpon'        =>  $telpon,
					'alamat'        =>  $alamat,
					'nik'        	=>  $nik,
					'bpjs'        	=>  $bpjs,
				]);
			}
		} catch (\Exception $e) {
			Log::error('Error in register Pasien: '.$e->getMessage());
		}
		
		$datetime   = new DateTime($tgllahir);
		$today      = new DateTime();
		$diff       = $today->diff($datetime);
		$tahun      = $diff->y;
		$bulan      = $diff->m;

		if ($tahun ==0) {
			$usia   = $bulan." Bulan";
		} else {
			$usia   = $tahun." Tahun, ". $bulan. " Bulan";
		}
		$jruang 	= Ruangan::where('id', $ruangan)->first();
		if (isset($jruang->ruangan)){
			$kamar 	= $jruang->ruangan;
		} else { $kamar = '-'; $ruangan = 1; }
		$tahuncari		= date("Y");
		$cekloket		= Periksa::whereNotNull('noloket')->where('daftar', 'LIKE', $tahuncari.'%')->count();
		if ($cekloket == 0){
			$noloket 	= 1;
		} else {
			$getloket	= Periksa::whereNotNull('noloket')->where('daftar', 'LIKE', $tahuncari.'%')->orderBy('noloket', 'DESC')->first();
			$noloket	= $getloket->noloket;
			$noloket	= $noloket + 1;
		}
		$code_poli  	= 'Mikrobiologi';
		$check   		= Poli::where('subpoli', $rekues)->first();
		if (isset($check->id)){
			$poli_id	= $check->id;
			$kd_spesimen= $check->subsubpoli;
			$nm_spesimen= $check->modaliti;
		} else {
			$poli_id 	= Poli::insertGetId([
				'poli'		=> 'Mikrobiologi',
				'subpoli'	=> $rekues,
			]);
		}
		$nofoto 	= date('y').'-'.sprintf("% 06s", $noloket);
		if ($iddokter == ''){
			$iddokter	= 0;
			$dokter		= null;
		} else {
			$getdokter 	= User::where('id', $iddokter)->first();
			if (isset($getdokter->nama)){
				$dokter 	= $getdokter->nama;
			} else { $dokter = 'Dokter Spesialis'; }
		}
		$clientIp 			= $request->server('HTTP_X_FORWARDED_FOR') ?: $request->ip();
		$clientIpNumeric 	= ip2long($clientIp);
		$periksaid 			= Periksa::insertGetId([
			'mulai'        	=>  $mulai,
			'akhir'        	=>  $akhir,
			'noloket'       =>  $noloket,
			'nofoto'        =>  $nofoto,
			'noregister'    =>  $noregister,
			'asalpasien'    =>  $tlsasal,
			'nmrs'    		=>  $nmrs,
			'pasien_id'     =>  $pasien_id,
			'nmpasien'		=> 	$nama,
			'jkpasien'		=> 	$jk,
			'ktp'			=> 	$nik,
			'bpjs'			=> 	$bpjs,
			'tgllahirpasien'=> 	$tgllahir,
			'tlppasien'		=> 	$telpon,
			'alamatpasien'	=> 	$alamat,
			'reques'     	=>  $rekues,
			'usia'          =>  $usia,
			'berat'         =>  $berat,
			'ruangan_id'    =>  $ruangan,
			'ruangan'    	=>  $kamar,
			'klinisi'       =>  $klinisi,
			'klinis'		=>  $klinis,
			'poli_id'       =>  $poli_id,
			'kd_spesimen'	=>  $kd_spesimen,
			'nm_spesimen'	=>  $nm_spesimen,
			'keterangan'    =>  '',
			'kesimpulan'    =>  '',
			'asuransi'      =>  $insurance,
			'urgensi'       =>  $urgensi,
			'daftar'        =>  $mulai,
			'pendaftar'   	=>  $clientIpNumeric,
			'nmpendaftar'	=>  $clientIp,
			'orderid'		=> 	$notransaksi,
		]);
		$pesan 			= $nofoto;
		try {
			DB::table('paslab')->insert([
				'rnoreg'		=> $nofoto,
				'nama'			=> $nama,
				'norm'			=> $noregister,
				'rtglast'		=> $mulai,
				'alamat'		=> $alamat,
				'rjenis'		=> $jk,
				'umur'			=> $usia,
				'namadok'		=> $dokter,
				'ruangan'		=> 'Mikrobiologi',
				'tes'			=> $rekues,
				'alat'			=> 'ALL',
				'kd_spesimen'	=> $kd_spesimen,
				'nm_spesimen'	=> $nm_spesimen,
				'tgllahir'		=> $tgllahir,
				'flg_vitek1'	=> false,
				'flg_vitek2'	=> false,
				'flg_bd1'		=> false,
				'flg_bd2'		=> false,
				'flg_gxp1'		=> false,
				'flg_gxp2'		=> false,
			]);
			if ($kd_spesimen != '' AND $nm_spesimen != ''){
				PendaftaranOnListiner::updateOrCreate(
					[
						'rnoreg'	=> $nofoto,
					],
					[
						'rtglast'		=> $tglsekarang,
						'norm'			=> $noregister,
						'nama'			=> $nama,
						'alamat'		=> $alamat,
						'telp'			=> $telpon,
						'hp'			=> $telpon,
						'tgllahir'		=> $tgllahir,
						'umur'			=> $usia,
						'rjenis'		=> $jk,
						'kodedok'		=> Session('id'),
						'namadok'		=> Session('nama'),
						'ruangan'		=> $kamar,
						'tes'			=> $rekues,
						'alat'			=> 'All',
						'kd_spesimen'	=> $kd_spesimen,
						'nm_spesimen'	=> $nm_spesimen,
					]
				);
				/*
				$dataForLis = [
					'nama' 			=> $nama,
					'noregister' 	=> $noregister,
					'nofoto' 		=> $nofoto,
					'kd_spesimen' 	=> $kd_spesimen,
					'nm_spesimen' 	=> $nm_spesimen,
					'tgllahir' 		=> $tgllahir,
					'jk' 			=> $jk,
				];
				$this->sendRegistrationToLis($dataForLis);
				*/
			}
			return response()->json(['status' => 'Sukses', 'message' => $pesan], 201);
		} catch (Exception $e) {
			return response()->json(['status' => 'Sukses', 'message' => $pesan], 201);
		}
	}
	public function register(Request $request) {
    	$validator  = Validator::make($request->all(), [
            'nama'          =>  'required',
            'jk'            =>  'required',
            'insurance'     =>  'required',
            'urgensi'       =>  'required',
			'poli_id'		=> 	'required'
        ]);
        if($validator->fails()) {
            return response()->json(['status' => 'Failed', 'message' => 'Periksa Kembali Isian Anda, Pastikan Nama, Jenis Kelamin, Asuransi, Urgensi, Kota, No. HP dan Jenis Pemeriksaan Telah Anda Isi']);
			return back();
        } else {
            $jk     		= $request->input('jk');
			$nik     		= $request->input('nik') ?? time();
			$bpjs     		= $request->input('bpjs') ?? time();
			$alamat 		= $request->input('alamat') ?? config('global.addressapps');
			$kota 			= $request->input('kota') ?? config('global.subdomainapps');
			$noregister     = $request->input('noregister');
            $pasien_id      = $request->input('pasien_id');
            $insurance      = $request->input('insurance');
            $ruangan        = $request->input('ruangan');
            $nmpoli        	= $request->input('nmpoli');
            $nmruangan      = $request->input('nmruangan');
            $lainlain       = $request->input('lainlain');
            $asuransi       = $request->input('asuransi');
            $urgensi        = $request->input('urgensi');
			$nama       	= $request->input('nama');
            $tgllahir   	= $request->input('tgl') ?? date ('d-m-Y');
			$asalpasien   	= $request->input('asal');
			$berat   		= $request->input('val01');
			$nmrs   		= $request->input('val02');
			$klinisi   		= $request->input('val03');
			$jadwal   		= $request->input('val04');
			$jammulai  		= $request->input('val05');
			$jamselesai		= $request->input('val06');
			$telpon			= $request->input('val07') ?? '0000000000';
			$jeniskerja		= $request->input('val08');
			$iddokter		= $request->input('val09');
			$jenisgambar	= $request->input('jenisgambar');
			$file			= $request->input('file');
			$poli_id		= $request->input('poli_id') ?? 1;
			$cekkodespes 	= Organisms::where('id', $ruangan)->first();
			if (isset($cekkodespes->name)){
				$nm_spesimen    = $cekkodespes->name;
				$kd_spesimen    = $cekkodespes->category;
			} else {
				$kd_spesimen    = $request->input('kd_spesimen') ?? '';
				$nm_spesimen    = $request->input('nm_spesimen') ?? '';
			}
			
			$reques			= 'Specimen';
			$kelompok		= Session('previlage');
			$daftar         = date('Y-m-d H:i:s');
			try {
				$tgllahir 		= \Carbon\Carbon::createFromFormat('Y-m-d', $tgllahir);
			} catch (Exception $e) {
				
			}
			if ($jeniskerja == 'tambahbaru'){
				try {
					if ($nmruangan != ''){
						$tlsasal 	= $nmruangan;
					} else if ($nmpoli != ''){
						$tlsasal 	= $nmpoli;
					} else {
						$tlsasal 	= $lainlain;
					}
					if ($jammulai == ''){
						$mulai		= $daftar;
						$tambah		= ' + 360 second';
						$akhir		= date('Y-m-d h:i:s',strtotime($tambah,strtotime($daftar)));
						$start 		= strtotime(date("Y-m-d H:i:s",strtotime($mulai)));
						$finish 	= strtotime(date("Y-m-d H:i:s",strtotime($akhir)));
					} else {
						$mulai		= $jadwal.' '.$jammulai.':00';
						if ($jamselesai == ''){
							$tambah	= ' + 360 second';
							$akhir	= date('Y-m-d h:i:s',strtotime($tambah,strtotime($daftar)));
						} else {
							$akhir	= $jadwal.' '.$jamselesai.':00';
						}
						$start 		= strtotime(date("Y-m-d H:i:s",strtotime($mulai)));
						$finish 	= strtotime(date("Y-m-d H:i:s",strtotime($akhir)));
					}
					$tglsekarang	= date('Y-m-d');
					$noregister		= strtoupper($noregister);
					$yy				= date("Y");
					$mm				= date("m");
					$pesan 			= '';
					$year_now   	= date("y");
					if ($noregister == ''){
						$getlastid = Pasien::orderBy('id', 'DESC')->count();
						if ($getlastid == 0){
							$noregister = 'LIS-1';
						}else {
							$getlastid 	= Pasien::orderBy('id', 'DESC')->first();
							$lastid		= $getlastid->id;
							$lastid		= $lastid + 1;
							$noregister	= 'LIS-'.$lastid;
						}
					}
					
					$kota 			= config('global.subdomainapps');
					$alamat 		= $request->input('alamat') ?? config('global.addressapps');
					$nama 			= $request->input('nama');
					$jk 			= $request->input('jk');
					try {
						$cekid    		= Pasien::where('norm', $noregister)->count();
						if ($cekid == 0) {
							$pasien_id 	= Pasien::insertGetId([
								'norm'          =>  $noregister,
								'nama'          =>  $nama,
								'jk'            =>  $jk,
								'tgl_lahir'     =>  $tgllahir,
								'kota'          =>  $kota,
								'telpon'        =>  $telpon,
								'alamat'        =>  $alamat,
								'nik'        	=>  $nik,
								'bpjs'        	=>  $bpjs,
							]);
						} else {
							$pasien    	= Pasien::where('norm', $noregister)->first();
							$pasien_id	= $pasien->id;
							Pasien::where('norm', $noregister)->update([
								'nama'          =>  $nama,
								'jk'            =>  $jk,
								'tgl_lahir'     =>  $tgllahir,
								'kota'          =>  $kota,
								'telpon'        =>  $telpon,
								'alamat'        =>  $alamat,
								'nik'        	=>  $nik,
								'bpjs'        	=>  $bpjs,
							]);
						}
					} catch (Exception $e) {
						Log::error('Error in register Pasien: '.$e->getMessage());
					}
					
					$datetime   = new DateTime($tgllahir);
					$today      = new DateTime();
					$diff       = $today->diff($datetime);
					$tahun      = $diff->y;
					$bulan      = $diff->m;
	
					if ($tahun ==0) {
						$usia   = $bulan." Bulan";
					} else {
						$usia   = $tahun." Tahun, ". $bulan. " Bulan";
					}
					$kamar 			= 'Mikrobiologi';
					$tahuncari		= date("Y");
					$cekloket		= Periksa::whereNotNull('noloket')->where('daftar', 'LIKE', $tahuncari.'%')->count();
					if ($cekloket == 0){
						$noloket 	= 1;
					} else {
						$getloket	= Periksa::whereNotNull('noloket')->where('daftar', 'LIKE', $tahuncari.'%')->orderBy('noloket', 'DESC')->first();
						$noloket	= $getloket->noloket;
						$noloket	= $noloket + 1;
					}
					$code_poli  	= 'mikro';
					$check   		= Poli::where('id', $poli_id)->first();
					$nmpoli			= $check->poli ?? 'Mikrobiologi';
					$subpoli  		= $check->subpoli ?? '';
					$modality		= $check->modaliti ?? 'OT';
					$modaliti2		= $check->modaliti2 ?? '';
					if (isset($check->subsubpoli)){
						$rekues 	= $subpoli.' - '.$check->subsubpoli;
					} else {
						$rekues 	= $subpoli;
					}
					if ($modality != 'OT' AND $modality != ''){
						$nm_spesimen    = $modality;
						$kd_spesimen    = $check->subsubpoli;
					} 
					$nofoto 	= date('y').'-'.sprintf("% 06s", $noloket);
					if ($iddokter == ''){
						$iddokter	= 0;
						$dokter		= null;
					} else {
						$getdokter 	= User::where('id', $iddokter)->first();
						if (isset($getdokter->nama)){
							$dokter 	= $getdokter->nama;
						} else { $dokter = 'Dokter Spesialis'; }
					}
					$periksaid 	= Periksa::insertGetId([
						'mulai'        	=>  $mulai,
						'akhir'        	=>  $akhir,
						'noloket'       =>  $noloket,
						'nofoto'        =>  $nofoto,
						'noregister'    =>  $noregister,
						'asalpasien'    =>  $tlsasal,
						'nmrs'    		=>  $nmrs,
						'pasien_id'     =>  $pasien_id,
						'nmpasien'		=> 	$nama,
						'jkpasien'		=> 	$jk,
						'ktp'			=> 	$nik,
						'bpjs'			=> 	$bpjs,
						'tgllahirpasien'=> 	$tgllahir,
						'tlppasien'		=> 	$telpon,
						'alamatpasien'	=> 	$alamat,
						'reques'     	=>  $rekues,
						'usia'          =>  $usia,
						'berat'         =>  $berat,
						'ruangan_id'    =>  $ruangan,
						'ruangan'    	=>  $kamar,
						'klinisi'       =>  $klinisi,
						'klinis'		=>  $request->input('val10'),
						'poli_id'       =>  $poli_id,
						'keterangan'    =>  '',
						'kesimpulan'    =>  '',
						'asuransi'      =>  $insurance,
						'urgensi'       =>  $urgensi,
						'daftar'        =>  $mulai,
						'kd_spesimen'	=>  $kd_spesimen,
						'nm_spesimen'	=>  $nm_spesimen,
						'pendaftar'   	=>  Session('previlage'),
						'nmpendaftar'	=>  Session('nama'),
					]);
					DB::table('paslab')->insert([
						'rnoreg'		=> $nofoto,
						'nama'			=> $nama,
						'norm'			=> $noregister,
						'rtglast'		=> $mulai,
						'alamat'		=> $alamat,
						'rjenis'		=> $jk,
						'umur'			=> $usia,
						'namadok'		=> $dokter,
						'ruangan'		=> 'Mikrobiologi',
						'tes'			=> $rekues,
						'alat'			=> 'ALL',
						'kd_spesimen'	=> $kd_spesimen,
						'nm_spesimen'	=> $nm_spesimen,
						'tgllahir'		=> $tgllahir,
						'flg_vitek1'	=> false,
						'flg_vitek2'	=> false,
						'flg_bd1'		=> false,
						'flg_bd2'		=> false,
						'flg_gxp1'		=> false,
						'flg_gxp2'		=> false,
					]);
					if ($kd_spesimen != '' AND $nm_spesimen != ''){
						PendaftaranOnListiner::updateOrCreate(
							[
								'rnoreg'	=> $nofoto,
							],
							[
								'rtglast'		=> $mulai,
								'norm'			=> $noregister,
								'nama'			=> $nama,
								'alamat'		=> $alamat,
								'telp'			=> $telpon,
								'hp'			=> $telpon,
								'tgllahir'		=> $tgllahir,
								'umur'			=> $usia,
								'rjenis'		=> $jk,
								'kodedok'		=> Session('id'),
								'namadok'		=> Session('nama'),
								'ruangan'		=> $kamar,
								'tes'			=> $rekues,
								'alat'			=> 'All',
								'kd_spesimen'	=> $kd_spesimen,
								'nm_spesimen'	=> $nm_spesimen,
							]
						);
						/*
						$dataForLis = [
							'nama' 			=> $nama,
							'noregister' 	=> $noregister,
							'nofoto' 		=> $nofoto,
							'kd_spesimen' 	=> $kd_spesimen,
							'nm_spesimen' 	=> $nm_spesimen,
							'tgllahir' 		=> $tgllahir,
							'jk' 			=> $jk,
						];
						$this->sendRegistrationToLis($dataForLis);
						*/
					}
					$pesan 		= $pesan.' Nomor Lokal '.$nofoto.' dengan No. Urut '.$noloket.' Berhasil di Simpan';
					if ($pesan != ''){
						if ($file != '' AND $jenisgambar != ''){
							Xfiles::create([
								'xmarking'	=> $nofoto,
								'xtabel'	=> 'File Permintaan',
								'xjenis'	=> $jenisgambar,
								'xfile'		=> $file
							]);
							Periksa::where('nofoto', $nofoto)->update([
								'filefoto' => $nofoto
							]);
						}
						return response()->json(['status' => 'Status', 'message' => $pesan]);
						return back();
					} else {
						return response()->json(['status' => 'Failed', 'message' => 'Mohon Memeriksa isian form pendaftaran kembali dan pastikan semua sudah terisi']);
						return back();
					}
				} catch (Exception $e) {
					$result = $e->getMessage();
					return response()->json(['status' => 'Failed', 'message' => $result]);
					return back();
				}
			} else {
				try {
					if ($nmruangan != ''){
						$tlsasal 	= $nmruangan;
					} else if ($nmpoli != ''){
						$tlsasal 	= $nmpoli;
					} else {
						$tlsasal 	= $lainlain;
					}
					if ($jammulai == ''){
						$mulai		= $daftar;
						$tambah		= ' + 360 second';
						$akhir		= date('Y-m-d h:i:s',strtotime($tambah,strtotime($daftar)));
						$start 		= strtotime(date("Y-m-d H:i:s",strtotime($mulai)));
						$finish 	= strtotime(date("Y-m-d H:i:s",strtotime($akhir)));
					} else {
						$mulai		= $jadwal.' '.$jammulai.':00';
						if ($jamselesai == ''){
							$tambah	= ' + 360 second';
							$akhir	= date('Y-m-d h:i:s',strtotime($tambah,strtotime($daftar)));
						} else {
							$akhir	= $jadwal.' '.$jamselesai.':00';
						}
						$start 		= strtotime(date("Y-m-d H:i:s",strtotime($mulai)));
						$finish 	= strtotime(date("Y-m-d H:i:s",strtotime($akhir)));
					}
					$tglsekarang	= date('Y-m-d');
					$noregister		= strtoupper($noregister);
					$yy				= date("Y");
					$mm				= date("m");
					$pesan 			= '';
					$year_now   	= date("y");
					$check   		= Poli::where('id', $poli_id)->first();
					$nmpoli			= $check->poli ?? 'Mikrobiologi';
					$subpoli  		= $check->subpoli ?? '';
					$modality		= $check->modaliti ?? 'OT';
					$modaliti2		= $check->modaliti2 ?? '';
					if (isset($check->subsubpoli)){
						$rekues = $subpoli.' - '.$check->subsubpoli;
					} else {
						$rekues = $subpoli;
					}
					if ($modality != 'OT' AND $modality != ''){
						$nm_spesimen    = $modality;
						$kd_spesimen    = $check->subsubpoli;
					} 
					$getdata 	= Periksa::where('id', $jeniskerja)->first();
					$nofoto		= $getdata->nofoto;
					$usia		= $getdata->usia;
					$periksaid 	= Periksa::where('id', $jeniskerja)->update([
						'nmpasien'		=> 	$nama,
						'noregister'    =>  $noregister,
						'jkpasien'		=> 	$jk,
						'ktp'			=> 	$nik,
						'bpjs'			=> 	$bpjs,
						'tgllahirpasien'=> 	$tgllahir,
						'tlppasien'		=> 	$telpon,
						'alamatpasien'	=> 	$alamat,
						'asalpasien'    =>  $tlsasal,
						'nmrs'    		=>  $nmrs,
						'reques'     	=>  $rekues,
						'ruangan_id'    =>  $ruangan,
						'klinisi'       =>  $klinisi,
						'klinis'		=>  $request->input('val10'),
						'poli_id'       =>  $poli_id,
						'asuransi'      =>  $insurance,
						'urgensi'       =>  $urgensi,
						'daftar'        =>  $mulai,
						'kd_spesimen'	=>  $kd_spesimen,
						'nm_spesimen'	=>  $nm_spesimen,
					]);
					$pesan 		= $pesan.' Data Berhasil di Update';
					if ($kd_spesimen != '' AND $nm_spesimen != ''){
						PendaftaranOnListiner::updateOrCreate(
							[
								'rnoreg'	=> $nofoto,
							],
							[
								'rtglast'		=> $mulai,
								'norm'			=> $noregister,
								'nama'			=> $nama,
								'alamat'		=> $alamat,
								'telp'			=> $telpon,
								'hp'			=> $telpon,
								'tgllahir'		=> $tgllahir,
								'umur'			=> $usia,
								'rjenis'		=> $jk,
								'kodedok'		=> Session('id'),
								'namadok'		=> Session('nama'),
								'ruangan'		=> 'Mikrobiologi',
								'tes'			=> $rekues,
								'alat'			=> 'All',
								'kd_spesimen'	=> $kd_spesimen,
								'nm_spesimen'	=> $nm_spesimen,
							]
						);
						
					}
					if ($pesan != ''){
						if ($file != '' AND $jenisgambar != ''){
							Xfiles::create([
								'xmarking'	=> $nofoto,
								'xtabel'	=> 'File Permintaan',
								'xjenis'	=> $jenisgambar,
								'xfile'		=> $file
							]);
							Periksa::where('nofoto', $nofoto)->update([
								'filefoto' => $nofoto
							]);
						}
						return response()->json(['status' => 'Status', 'message' => $pesan]);
						return back();
					} else {
						return response()->json(['status' => 'Failed', 'message' => 'Mohon Memeriksa isian form pendaftaran kembali dan pastikan semua sudah terisi']);
						return back();
					}
				} catch (Exception $e) {
					$result = $e->getMessage();
					return response()->json(['status' => 'Failed', 'message' => $result]);
					return back();
				}
			}
        }
	}
	public function exMoveApiRegister(
		Request $request,
		AstmMessageService $astmMessageService,
        SerialCommunicationService $serialCommunicationService
		) {
    	$nofoto     	= $request->input('nofoto');
		$modality		= $request->input('reques');
		$cekdata 		= Periksa::where('nofoto', $nofoto)->first();
		if (isset($cekdata->id)){
			$nama 			= $cekdata->nmpasien;
			$jk 			= $cekdata->jkpasien;
			$urgensi 		= $cekdata->urgensi ?? 'Elective';
			$alamat 		= $cekdata->alamatpasien ?? 'Malang';
			
			Periksa::where('nofoto', $nofoto)->update([
				'excutor'    	=> Session('id'),
				'nmexcutor'    	=> Session('nama'),
			]);
			try {
				if ($modality == 'genexpert01' OR $modality == 'genexpert02' OR $modality == 'genexpert03'){
					$dataForLis = [
						'nama' 			=> $cekdata->nmpasien,
						'noregister' 	=> $cekdata->noregister,
						'nofoto' 		=> $cekdata->nofoto,
						'kd_spesimen' 	=> $cekdata->kd_spesimen,
						'nm_spesimen' 	=> $cekdata->nm_spesimen,
						'tgllahir' 		=> $cekdata->tgllahirpasien,
						'jk' 			=> $cekdata->jkpasien,
					];
					$this->sendRegistrationToLis($dataForLis);
				} else {
					$pesan 		= 'Cannot send on Serial Port From Server';
				}
			}catch (Exception $e) {
				$pesan = $e->getMessage();
			}
			
			return response()->json(['status' => 'Status', 'message' => $pesan ?? 'Unkown Error']);
			return back();
		} else {
			return response()->json(['status' => 'Failed', 'message' => $nofoto.' Tidak di Temukan']);
			return back();
		}
	}
	public function exCekAksess(Request $request) {
    	$nofoto     =   $request->input('nofoto');
        $tgllahir   =   $request->input('tgllahir');
		if ($nofoto == 'noregister'){
			$noregister   	=   $request->input('noregister');
			$tabel 			= 	'';
			$lists		= DB::table('periksa')
							->select('periksa.*', 'organisms.satuan as satuanperspesimen', 'organisms.nilai as nilaiperspesimen')
							->leftJoin('periksa', 'organisms.category', 'periksa.kd_spesimen')
							->where('periksa.noregister', $noregister)
							->where('periksa.tgllahirpasien', $tgllahir)
							->get();
			if (!empty($lists)){
				$tabel = '<div class="timeline">';
				$kanan = '';
				foreach($lists as $rows){
					$status 	= $rows->status;
					$id_periksa = $rows->id;
					if ( !empty($rows->rating) ) {
						$saved_rating = $rows->rating;
						$bintang_html = '';
						for ($i = 1; $i <= 5; $i++) {
							if ( $i <= $saved_rating ) {
								$bintang_html .= '<i class="fa fa-star" style="font-size:18px; color:orange;"></i>';
							} else {
								$bintang_html .= '<i class="fa fa-star-o" style="font-size:18px; color:orange;"></i>';
							}
						}
						$ratingBintang = '
						<div class="rating-stars" data-id="'.$id_periksa.'">
							<small class="text-muted">Terimka kasih atas rating yang diberikan:</small><br>
							'.$bintang_html.'
						</div>';
					} else {
						$ratingBintang = '
									<div class="rating-stars" data-id="'.$id_periksa.'">
										<small class="text-muted">Beri Rating:</small><br>
										<i class="fa fa-star-o" style="cursor:pointer; font-size:18px; color:orange;" onclick="btnisiRating('.$id_periksa.', 1)"></i>
										<i class="fa fa-star-o" style="cursor:pointer; font-size:18px; color:orange;" onclick="btnisiRating('.$id_periksa.', 2)"></i>
										<i class="fa fa-star-o" style="cursor:pointer; font-size:18px; color:orange;" onclick="btnisiRating('.$id_periksa.', 3)"></i>
										<i class="fa fa-star-o" style="cursor:pointer; font-size:18px; color:orange;" onclick="btnisiRating('.$id_periksa.', 4)"></i>
										<i class="fa fa-star-o" style="cursor:pointer; font-size:18px; color:orange;" onclick="btnisiRating('.$id_periksa.', 5)"></i>
									</div>';
					}
					
					if ($status == 'Selesai'){
						$tombolcetak = url('/').'/hasil/'.$rows->nofoto;
						$tombolcetak = '<a href="'.$tombolcetak.'"><button type="button" class="btn btn-icon waves-effect waves-light btn-success"> <i class="fa fa-print"></i> </button></a>';
					} else {
						$tombolcetak = 'Masih dalam proses dan perkiraan selesai adalah '.$rows->nilaiperspesimen.' '.$rows->satuanperspesimen.' dari sample diterima';
					}
					if ($kanan == ''){
						$tabel = $tabel.'<article class="timeline-item"><div class="timeline-desk"><div class="panel"><div class="timeline-box"><span class="arrow"></span><span class="timeline-icon bg-custom"><i class="mdi mdi-adjust"></i></span><h4 class="text-custom">'.$rows->daftar.'</h4><p class="timeline-date text-muted"><small>'.$rows->reques.'</small></p><p>'.$rows->status.'</p>'.$ratingBintang.'<div class="btn btn-group">'.$tombolcetak.'</div></div></div></div></article>';
						$kanan = 'kanan';
					} else {
						$tabel = $tabel.'<article class="timeline-item alt"><div class="timeline-desk"><div class="panel"><div class="timeline-box"><span class="arrow-alt"></span><span class="timeline-icon bg-custom"><i class="mdi mdi-adjust"></i></span><h4 class="text-custom">'.$rows->daftar.'</h4><p class="timeline-date text-muted"><small>'.$rows->reques.'</small></p><p>'.$rows->status.'</p>'.$ratingBintang.'<div class="btn btn-group">'.$tombolcetak.'</div></div></div></div></article>';
						$kanan = '';
					}
				}
				$tabel = $tabel.'</div>';
			} else {
				$tabel = 'Data Tidak ditemukan, Pastikan Kembali Apakah No. RM ('.$noregister.') dan tanggal lahir ('.$tgllahir.') sudah benar';
			}
			echo $tabel;
		} else if ($nofoto == 'isirating'){
			Periksa::where('id', $request->input('id'))->update([
				'rating'	=> $request->input('rating')
			]);
		} else if ($nofoto == 'stiker'){
			$header 		= $request->input('nm_spesimen');
			$footer 		= '';
			$noregister   	= $request->input('noregister');
			$daftartgl   	= $request->input('daftartgl');
			$nama 			= '';
			$tgllahir 		= '';
			$asalpasien 	= '';
			$nofoto 		= '';
			$kelamin 		= '';
			$marking 		= $noregister.'-'.$daftartgl.'-'.$header;
			$marking 		= md5($marking);
			$sql = Periksa::where('noregister', $request->input('noregister'))->whereDate('daftar', $request->input('daftartgl'))->where('nm_spesimen', $request->input('nm_spesimen'))->get();
			foreach($sql as $row){
				$nama 			= $row->nmpasien;
				$tgllahir 		= $row->tgllahirpasien;
				$asalpasien 	= $row->asalpasien;
				$nofoto 		= $row->nofoto;
				$kd_spesimen 	= $row->kd_spesimen;
				$kelamin 		= $row->jkpasien;
				if ($footer == ''){
					$footer 	= $kd_spesimen;
				} else {
					if ($footer == $kd_spesimen){
						
					} else {
						$footer 	= $footer.', '.$kd_spesimen;
					}
				}
			}
			Periksa::where('noregister', $request->input('noregister'))->whereDate('daftar', $request->input('daftartgl'))->where('nm_spesimen', $request->input('nm_spesimen'))->update([
				'nmadendum'	=> $marking
			]);
			
			$item 		= $asalpasien.'<>'.$header.'<>'.$noregister.'<>'.$nama.'<>'.$tgllahir.'<>'.$footer.'<>'.$daftartgl.'<>'.$kelamin;
			return response()->json(['item' => $item, 'nofoto' => $nofoto]);
			return back();
			
		} else {
			$periksa    = 	Periksa::where('nofoto', $nofoto)->where('tgllahirpasien', $tgllahir)->first();
			if (isset($periksa->id)){
				if ($periksa->status != 'Selesai'){
					Periksa::where('id', $periksa->id)->update([
						'export'  =>  date('Y-m-d H:i:s')
					]);
				}
				$hasil = DokterController::genSurat($periksa->id, 'dengan kop');

				return response()->json(['status' => 'Success', 'message' => $hasil]);
				return back();
			} else {
				return response()->json(['status' => 'Failed', 'message' => 'Data No Foto Dengan Tanggal Lahir tidak Cocok']);
				return back();
			}
		}
	}
}
