<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Poli;
use App\Logbook;
use App\User;
use App\Periksa;
use App\Dokter;
use App\Pasien;
use App\Jadwalperiksa;
use App\Riwayat;
use App\RekapAntibiotik;
use DateTime;
use Carbon\Carbon;
use Session;

class ReportController extends Controller
{
    public function index() {
		if (Session::get('previlage') == ''){
			return redirect('/login');
		} else {
    		return view('admin.report');
		}
    }
    public function rekapPeriksa(Request $request) {
		set_time_limit(0);
		$bulan = $request->input('bulan');
		$tahun = $request->input('tahun');
		if ($bulan == 'ALL' OR $bulan == 'Pick Month') {
			$orderbydate 	= Periksa::selectRaw('SUM(id) as jumlah, DATE(daftar) as day')->whereYear('daftar', $tahun)->groupBy(DB::raw('daftar'))->orderBy('daftar', 'ASC')->get();
			$bulan 			= '';
		} else {
			$tglcari 		= $tahun . '-' . str_pad($bulan, 2, '0', STR_PAD_LEFT);
			$orderbydate 	= Periksa::selectRaw('SUM(id) as jumlah, DATE(daftar) as day')->where('day', 'LIKE', '%' . $tglcari . '%')->groupBy(DB::raw('daftar'))->orderBy('daftar', 'ASC')->get();
			$bulanNames 	= [
				'01' => 'BULAN JANUARI',
				'02' => 'BULAN FEBRUARI',
				'03' => 'BULAN MARET',
				'04' => 'BULAN APRIL',
				'05' => 'BULAN MEI',
				'06' => 'BULAN JUNI',
				'07' => 'BULAN JULI',
				'08' => 'BULAN AGUSTUS',
				'09' => 'BULAN SEPTEMBER',
				'10' => 'BULAN OKTOBER',
				'11' => 'BULAN NOVEMBER',
				'12' => 'BULAN DESEMBER',
			];
			$bulan = $bulanNames[$bulan] ?? $bulan;
		}
		$data = [];
		$data['bulan'] 		= $bulan;
		$data['tahun']		= $tahun;
		$data['orderbydate']= $orderbydate;
		$generatetabel = view('cetak.rekap_periksa_table', $data)->render();
		echo $generatetabel;
	}
	protected static function getPasienData($result) {
		return [
			'nama' 		=> $result->nmpasien,
			'tgl' 		=> $result->tgllahirpasien,
			'jk' 		=> $result->jkpasien,
		];
	}
	protected static function updateTotals($totals, $asuransi, $urgensi, $jk) {
		if ($jk == 'L') {
			$totals['m']++;
		} else {
			$totals['f']++;
		}

		if ($asuransi == 'JKN') {
			$totals['jkn']++;
		} elseif ($asuransi == 'Umum') {
			$totals['umum']++;
		} elseif ($asuransi == 'TAG') {
			$totals['tag']++;
		} elseif ($asuransi == 'GCU') {
			$totals['gcu']++;
		} elseif ($asuransi == 'Billing') {
			$totals['bill']++;
		} else {
			$totals['swasta']++;
		}

		if ($urgensi == 'Elective') {
			$totals['electiv']++;
		} else {
			$totals['cito']++;
		}

		return $totals;
	}
	protected static function mapResultToArray($result) {
		$nmpasien 		= 	$result->nmpasien;
		$tgl 			= 	$result->tgllahirpasien;
		$jk     		=   $result->jkpasien;
		$jenis			= 	$result->reques;
		$tlppasien		= 	$result->tlppasien;
		$nofoto     	=   $result->nofoto;
		$verifikasi		= 	$result->verifikasi;
		$tanggal		= 	$result->daftar;
		$tanggalfoto	= 	$result->foto;
		$asuransi		= 	$result->asuransi;
		$urgensi		= 	$result->urgensi;
		$from 			= \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $result->daftar);
		if (is_null($verifikasi)){ 
			$verifikasi = ''; 
			$to 		= '';
			$durasi 	= 'On Progress';
		} else {
			$to 		= \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $verifikasi);
			$durasi 	= $to->diffForHumans($from);
		}
		$arrayttllhr	= 	explode("-", $tgl);
		if (isset($arrayttllhr[2])){
			$yy 			= 	$arrayttllhr[0];
			$mm 			= 	$arrayttllhr[1];
			$dd 			= 	$arrayttllhr[2];
			$tgllahir		= 	$dd.'-'.$mm.'-'.$yy;
		} else { $tgllahir = $tgl; }
		$arrayttl 		= explode(" ", $tanggal);
		$tanggal 		= $arrayttl[0];
		if ($jk == 'L') {
			$l 	= 	'1';
			$p 	= 	'';
		} else {
			$l 	= 	'';
			$p 	= 	'1';
		}
		if ($asuransi == 'JKN') {
			$jkn 	= 	'1';
			$umm 	= 	'';
			$swasta	= 	'';
			$gcu	= 	'';
			$tag	= 	'';
			$bill	= 	'';
		} else if ($asuransi == 'Umum') {
			$jkn 	= 	'';
			$umm 	= 	'1';
			$swasta	= 	'';
			$gcu	= 	'';
			$tag	= 	'';
			$bill	= 	'';
		} else if ($asuransi == 'TAG') {
			$jkn 	= 	'';
			$umm 	= 	'';
			$swasta	= 	'';
			$gcu	= 	'';
			$bill	= 	'';
			$tag	= 	'1';
		} else if ($asuransi == 'GCU') {
			$jkn 	= 	'';
			$umm 	= 	'';
			$swasta	= 	'';
			$gcu	= 	'1';
			$tag	= 	'';
			$bill	= 	'';
		} else if ($asuransi == 'Billing') {
			$jkn 	= 	'';
			$umm 	= 	'';
			$swasta	= 	'';
			$gcu	= 	'';
			$bill	= 	'1';
			$tag	= 	'';
		} else {
			$jkn 	= 	'';
			$umm 	= 	'';
			$swasta	= 	'1';
			$gcu	= 	'';
			$tag	= 	'';
			$bill	= 	'';
		}
		if ($urgensi == 'Elective') {
			$ele    =   '1';
			$cito   =   '';
		} else {
			$ele    =   '';
			$cito   =   '1';
		}
		$getjennofoto	= explode("-", $nofoto);
		$jenis			= $getjennofoto[0].' '.$jenis;
		return [
			'id'          	=> $result->id,
			'filefoto'    	=> '<a href="' . url('/') . '/hasil/' . $result->nofoto . '" target="_blank">' . $result->nofoto . '</a>',
			'l' 			=> 	$l,
			'p' 			=> 	$p,
			'jenis' 		=> 	$jenis,
			'jkn' 			=> 	$jkn,
			'umm' 			=> 	$umm,
			'gcu' 			=> 	$gcu,
			'tag' 			=> 	$tag,
			'swasta' 		=> 	$swasta,
			'billing' 		=> 	$bill,
			'ele' 			=> 	$ele,
			'cito' 			=> 	$cito,
			'asuransi' 		=> 	$asuransi,
			'nofoto' 		=> 	$result->nofoto,
			'noregister' 	=> 	$result->noregister,
			'nmpasien' 		=> 	$nmpasien,
			'usia' 			=> 	$result->usia,
			'kesimpulan' 	=> 	$result->kesimpulan,
			'ruangan' 		=> 	$result->ruangan,
			'daftar' 		=> 	$result->daftar,
			'created_at' 	=> 	$result->created_at,
			'nmdokter' 		=> 	$result->nmdokter,
			'nmppdssenior' 	=> 	$result->nmppdssenior,
			'nmmiddleppds' 	=> 	$result->nmmiddleppds,
			'nmppdsjunior' 	=> 	$result->nmppdsjunior,
			'nmppdsmiddle2' => 	$result->nmppdsmiddle2,
			'nmppdsjunior2'	=> 	$result->nmppdsjunior2,
			'diagnosa2' 	=> 	$result->diagnosa2,
			'nmanalis' 		=> 	$result->nmanalis,
			'nmexcutor' 	=> 	$result->nmexcutor,
			'alamatpasien' 	=> 	$result->alamatpasien,
			'tgllahirpasien'=> 	$tgl,
			'jkpasien' 		=> 	$jk,
			'tlppasien' 	=> 	$tlppasien,
			'modality' 		=> 	$result->modality,
			'dlp' 			=> 	$result->dlp,
			'kd_spesimen' 	=> 	$result->kd_spesimen,
			'nm_spesimen' 	=> 	$result->nm_spesimen,
			'status' 		=> 	$result->status,
			'asalpasien' 	=> 	$result->asalpasien,
			'nmrs' 			=> 	$result->nmrs,
			'berat' 		=> 	$result->berat,
			'klinisi' 		=> 	$result->klinisi,
			'klinis' 		=> 	$result->klinis,
			'telpon' 		=> 	$tlppasien,
			'verifikasi' 	=> 	$result->verifikasi,
			'noloket' 		=> 	$result->noloket,
			'foto' 			=> 	$result->foto,
			'export' 		=> 	$result->export,
			'nmdrafter' 	=> 	$result->nmdrafter,
			'tgldraft' 		=> 	$result->tgldraft,
			'baca' 			=> 	$result->baca,
			'nmpembaca' 	=> 	$result->nmpembaca,
			'tgladendum' 	=> 	$result->tgladendum,
			'nmadendum' 	=> 	$result->nmadendum,
			'durasi'    	=> 	$durasi,
		];
	}
	protected static function getTotalRow($totals) {
		return [
			'id'        => '',
			'filefoto'  => '',
			'noregister'=> '',
			'nama'      => '<strong>Total</strong>',
			'l'         => $totals['m'],
			'p'         => $totals['f'],
			'jkn'       => $totals['jkn'],
			'umm'       => $totals['umum'],
			'gcu'       => $totals['gcu'],
			'tag'       => $totals['tag'],
			'swasta'    => $totals['swasta'],
			'billing'   => $totals['bill'],
			'ele'       => $totals['electiv'],
			'cito'      => $totals['cito'],
		];
	}
	public function report(Request $request) {
		$bulan     		= $request->input('bulan');
		$tahun     		= $request->input('tahun');
		$jenisreport	= $request->input('jenisreport');
		$homebase  		= url("/");
		$arraylist 		= [];
		$limit     		= $request->input('limit') ?? 500;
		$page      		= $request->input('pagenum') ?? 1;
		$order     		= $request->input('order') ?? 'id desc';
		$filterscount 	= $request->input('filterscount') ?? 0;
		if ($jenisreport == 'biorepository'){
			if ($bulan == 'ALL'){
				$lists		= DB::table('db_komponenjawaban')
								->select('db_komponenjawaban.*', 
								'periksa.nofoto', 
								'periksa.noregister', 
								'periksa.nmpasien', 
								'periksa.usia', 
								'periksa.reques',
								'periksa.dlp', 
								'periksa.nm_spesimen', 
								'periksa.kd_spesimen',
								DB::raw("CONCAT('<a href=\"http://10.10.123.218/hasil/', nofoto, '\" target=\"_blank\">Lihat Hasil</a>') as urlhasil"))
								->leftJoin('periksa', 'db_komponenjawaban.accnumber', 'periksa.nofoto')
								->whereIn('db_komponenjawaban.komponen', ['id_bakteri01', 'id_bakteri02', 'bakteri'])
								->where('db_komponenjawaban.isidata', '!=', '')
								->where('periksa.daftar', 'LIKE', $tahun.'-%')->orderBy('periksa.id', 'DESC')->get();
			} else {
				$lists		= DB::table('db_komponenjawaban')
								->select('db_komponenjawaban.*', 
								'periksa.nofoto', 
								'periksa.noregister', 
								'periksa.nmpasien', 
								'periksa.usia', 
								'periksa.reques',
								'periksa.dlp',
								'periksa.nm_spesimen', 
								'periksa.kd_spesimen',
								DB::raw("CONCAT('<a href=\"http://10.10.123.218/hasil/', nofoto, '\" target=\"_blank\">Lihat Hasil</a>') as urlhasil"))
								->leftJoin('periksa', 'db_komponenjawaban.accnumber', 'periksa.nofoto')
								->whereIn('db_komponenjawaban.komponen', ['id_bakteri01', 'id_bakteri02', 'bakteri'])
								->where('db_komponenjawaban.isidata', '!=', '')
								->where('periksa.daftar', 'LIKE', $tahun.'-'.$bulan.'-%')->orderBy('periksa.id', 'DESC')->get();
			}
			echo json_encode($lists);
		} else {
			if ($bulan === 'pertanggal' || $bulan === 'terjadwal') {
				$results 	= DB::table($bulan === 'terjadwal' ? 'jadwalperiksan' : 'periksa')->when($bulan === 'terjadwal', function ($query) use ($tahun) {
									return $query->whereNull('jadwalperiksan.status')
												->where('jadwalperiksan.daftar', 'LIKE', "%$tahun%");
								}, function ($query) use ($tahun) {
									return $query->where('periksa.daftar', 'LIKE', "$tahun%");
								})->get();
				$totals 	= ['m' => 0, 'f' => 0, 'jkn' => 0, 'umum' => 0, 'tag' => 0, 'gcu' => 0, 'bill' => 0, 'swasta' => 0, 'electiv' => 0, 'cito' => 0];
				foreach ($results as $result) {
					$asuransi 		= $result->asuransi;
					$urgensi 		= $result->urgensi;
					$totals 		= self::updateTotals($totals, $asuransi, $urgensi, $result->jkpasien);
					$arraylist[] 	= self::mapResultToArray($result);
				}
				if ($bulan === 'pertanggal') {
					$arraylist[] = self::getTotalRow($totals);
				}
				echo json_encode($arraylist);
			} else {
				if ($bulan == 'ALL' || $bulan == 'Pick Month') {
					$results = DB::table('periksa')->where('daftar', 'LIKE', $tahun.'%')->get();
				} else {
					$tglcari = $tahun.'-'.$bulan;
					$results = DB::table('periksa')->where('daftar', 'LIKE', $tglcari.'%')->get();
				}
				$totals 	= ['m' => 0, 'f' => 0, 'jkn' => 0, 'umum' => 0, 'tag' => 0, 'gcu' => 0, 'bill' => 0, 'swasta' => 0, 'electiv' => 0, 'cito' => 0];
				foreach ($results as $result) {
					$asuransi 		= $result->asuransi;
					$urgensi 		= $result->urgensi;
					$totals 		= self::updateTotals($totals, $asuransi, $urgensi, $result->jkpasien);
					$arraylist[] 	= self::mapResultToArray($result);
				}
				$arraylist[] = self::getTotalRow($totals);
				echo json_encode($arraylist);
			}
		}
		
    }
	public function genRekapAntibiotik(Request $request) {
		$data 				= [];
		$bulan 				= $request->input('bulan');
		$tahun 				= $request->input('tahun');
		if ($tahun == '' OR is_null($tahun)){
			$getarray 		= explode('?', $bulan);
			$bulan 			= $getarray[0] ?? date('m');
			$tahun 			= $getarray[1] ?? date('Y');
			$bulan 			= str_replace('bulan=', '', $bulan);
			$tahun 			= str_replace('tahun=', '', $tahun);
		}
		if ($bulan == '' OR $bulan == 'ALL' OR $bulan == 'Pick Month') {
			$orderbydate = Periksa::whereYear('daftar', $tahun)->get();
			$jsonantibiotik = RekapAntibiotik::whereIn('orderid', $orderbydate->pluck('id'))->get()->groupBy('orderid');
		} else {
			$orderbydate = Periksa::whereMonth('daftar', $bulan)->whereYear('daftar', $tahun)->get();
			$jsonantibiotik = RekapAntibiotik::whereIn('orderid', $orderbydate->pluck('id'))->get()->groupBy('orderid');
		}
    	return view('admin.rekapantibiotik', compact('orderbydate', 'jsonantibiotik', 'bulan', 'tahun'));
  	}
	public function genGlassReport(Request $request) {
		$data 				= [];
		$bulan 				= $request->input('bulan');
		$tahun 				= $request->input('tahun');
		if ($tahun == '' OR is_null($tahun)){
			$getarray 		= explode('?', $bulan);
			$bulan 			= $getarray[0] ?? date('m');
			$tahun 			= $getarray[1] ?? date('Y');
			$bulan 			= str_replace('bulan=', '', $bulan);
			$tahun 			= str_replace('tahun=', '', $tahun);
		}
		if ($bulan == '' OR $bulan == 'ALL' OR $bulan == 'Pick Month') {
			$orderbydate 	= Periksa::whereYear('daftar', $tahun)->get();
			$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', //tidak ada
				'Tetracyclin-TCY',
				'Tigecycline-TGC', //double
				'Gentamicin-GM',
				'Amikacin-AN',
				'Meropenem-MEM',
				'Imipenem-IPM',
				'Doripenem-DOR',
				'Ertapenem-ETP',
				'Minocycline-MNO',
				'Doxycycline-DOX',
				'Spectinomycin-SPT',
				'Tigecycline-TGC', //sama-ini
				'Trimethoprim/Sulfamethoxazole-SXT',
				'Fosfomycin-FOS',
				'Vancomycin-VAN',
				'Linezolid-LNZ',
				'Fluconazole', //tidak ada
				'Voriconazole', //tidak ada
				'Caspofungin', //tidak ada
				'Micafungin', //tidak ada
				'Amphotericin B', //tidak ada
				'Flucytosine' //tidak ada
			);
		} else {
			$orderbydate 	= Periksa::whereMonth('daftar', $bulan)->whereYear('daftar', $tahun)->get();
			$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'
			);
		}
    	return view('admin.glassreport', compact('orderbydate', 'jsonantibiotik', 'bulan', 'tahun'));
  	}
	public function genZNreport(Request $request) {
		$data 				= [];
		$bulan 				= $request->input('bulan');
		$tahun 				= $request->input('tahun');
		if ($tahun == '' OR is_null($tahun)){
			$getarray 		= explode('?', $bulan);
			$bulan 			= $getarray[0] ?? date('m');
			$tahun 			= $getarray[1] ?? date('Y');
			$bulan 			= str_replace('bulan=', '', $bulan);
			$tahun 			= str_replace('tahun=', '', $tahun);
		}
		if ($bulan == '' OR $bulan == 'ALL' OR $bulan == 'Pick Month') {
			$results = DB::table('periksa as p')
					->leftJoin('db_komponenjawaban', 'p.nofoto', 'db_komponenjawaban.accnumber')
					->whereMonth('daftar', $bulan)->whereYear('daftar', $tahun)
					->whereIn('db_komponenjawaban.komponen', ['lsg_pewarnaanziehlnielsen', 'id_pewarnaanziehlnielsen'])
					->select('db_komponenjawaban.komponen', DB::raw('COUNT(*) as jumlah'))
					->groupBy('db_komponenjawaban.komponen')
					->orderByDesc('jumlah')
					->get();
		} else {
			$results = DB::table('periksa as p')
					->leftJoin('db_komponenjawaban', 'p.nofoto', 'db_komponenjawaban.accnumber')
					->whereMonth('daftar', $bulan)->whereYear('daftar', $tahun)
					->whereIn('db_komponenjawaban.komponen', ['lsg_pewarnaanziehlnielsen', 'id_pewarnaanziehlnielsen'])
					->select('db_komponenjawaban.komponen', DB::raw('COUNT(*) as jumlah'))
					->groupBy('db_komponenjawaban.komponen')
					->orderByDesc('jumlah')
					->get();
		}
		
    	return view('admin.znreport', compact('results', 'bulan', 'tahun'));
  	}
}
