<?php
include_once './config/database.php';
require "../vendor/autoload.php";
use \Firebase\JWT\JWT;

header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
//header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With, x-token, qqq");
//header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, x-token, X-Requested-With");
//header("Authorization: *");

$kartu = '';
$nik = '';
$telp = '';
$tglperiksa = '';
$kodepoli = '';
$referensi = '';
$jenreferensi = '';
$req = '';
$eks = '';
$NoMR = '';
$nomorantrean = ''; 
$kodebooking = '';
$jenisantrean = '';
$estimasidilayani = '';
$namapoli = '';
$namadokter = '';


$secret_key = "HOSMIS";
$jwt = null;
$databaseService = new DatabaseService();
$conn = $databaseService->getConnection();

$data = json_decode(file_get_contents("php://input"));

	
$kartu = $data->nomorkartu;
$nik = $data->nik;
$telp = $data->nohp;
$kodepoli = $data->kodepoli;
$norm= $data->norm;
$tglperiksa = $data->tanggalperiksa;
$kodedokter= $data->kodedokter;
$jampraktek= $data->jampraktek;
$jenreferensi = '1';
//$jenreferensi = $data->jeniskunjungan;
$referensi = $data->nomorreferensi;
//echo $jampraktek;
$req = "1";

$ini = "";
$iniall = "";
//$jampraktek="";
$jampraktekT="";
$jampraktekF="";

$namadokter = "";
$namapolibpjs= "";
$totp="";
$kuo="";
$kuon="";
//echo $jampraktek;
// if($kartu == ""){
	// echo json_encode(
            // array(
                // "metadata" => array("code" => 201, "message" => "No Peserta Kosong"),
				// "response" => null
				// ));
			// exit;
// }

// // cek 13 digit
// if(strlen($kartu) != 13){
// echo json_encode(
            // array(
                // "metadata" => array("code" => 201, "message" => "No BPJS Tidak Sesuai Kurang Dari 13 Digit"),
				// "response" => null
				// ));
			// exit;
// }
/*
// cek pasien
//echo $NoMR;
$query="(select mrno from patientmaster where mrno = :mrno)";
		$stmt = $conn->prepare( $query );
		$stmt->bindParam(':mrno', $norm, PDO::PARAM_STR, 50);
		$stmt->execute();
		$num = $stmt->rowCount();
		if($num > 0){
			//$row = $stmt->fetch(PDO::FETCH_ASSOC);
		//echo "ada";	
		}
		else {
			echo json_encode(
            array(
                "metadata" => array("code" => 201, "message" => "Maaf Anda Belum memiliki data RM di RS ... SIlahkan langsung datang ke RS untuk mendaftarkan rekam medik"),
				"response" => null
				));
				exit;
		}
*/
//echo $jampraktek;
// $query="(select jampraktek from inisial where KDokSEP = :kodedokter)";
		// $stmt = $conn->prepare( $query );
		// $stmt->bindParam(':kodedokter', $kodedokter, PDO::PARAM_STR, 50);
		// $stmt->execute();
		// $num = $stmt->rowCount();
		// if($num > 0){
			// $row = $stmt->fetch(PDO::FETCH_ASSOC);
			// $jamp = $row['jampraktek'];
			// if ($jamp <> $jampraktek) {
				// //echo $jamp;
				// //echo $kodedokter;
				// //echo $jampraktek;
				// echo json_encode(
				// array(
                // "metadata" => array("code" => 201, "message" => "Maaf Jam Praktek Tidak Sesuai"),
				// "response" => null
				// ));
				// exit;
			// }
			// //$row = $stmt->fetch(PDO::FETCH_ASSOC);
		// //echo "ada";	
		// }
		// else {
			// echo json_encode(
            // array(
                // "metadata" => array("code" => 201, "message" => "Maaf Jam Praktek Belum Di Set"),
				// "response" => null
				// ));
				// exit;
		// }


// $pecah = explode("-", $tglperiksa);
// if ($pecah[2] == "") {
	// $pecah[2] = 40;
// }
// if ($pecah[1] == "") {
	// $pecah[1] = 40;
// }
// if ($pecah[0] == "") {
	// $pecah[0] = 99999;
// }

// if (!checkdate($pecah[1], $pecah[2], $pecah[0])) {
	// echo json_encode(
            // array(
                // "metadata" => array("code" => 201, "message" => "Mohon Maaf Format Tgl Tidak Sesuai, Foramt Tgl Yg Benar yyyy-mm-dd"),
				// "response" => null
				// ));
			// exit;
// }
// if (strlen($pecah[0])> 4) {
	// echo json_encode(
            // array(
                // "metadata" => array("code" => 201, "message" => "Mohon Maaf Format Tgl Tidak Sesuai, Foramt Tgl Yg Benar yyyy-mm-dd"),
				// "response" => null
				// ));
			// exit;
// }

//cek tanggal tidak boleh kurang dari hari ini
 //echo json_encode(array(
 //           "message" => strtotime($tglperiksa), "::" => strtotime(date('Y-m-d'))
 //       ));
// if (strtotime($tglperiksa) < strtotime(date('Y-m-d'))) {
	// echo json_encode(
            // array(
                // "metadata" => array("code" => 201, "message" => "Tgl Periksa Tidak Boleh Kurang Dari Hari Ini"),
				// "response" => null
				// ));
			// exit;
// }


//cek sudah punya mr atau belum,

/*
//cek validasi nomor rujukan dan kartu
//bikin file
$isi = $referensi; //"ini adalah data yang akan ditambahkan kedalam file"; //string data yang akan dimasukan kedalam file.txt
$file = "SEP_RUJUKAN.txt";
$fhandle = fopen($file, 'w') or die("can’t open file"); //membuka “file.txt” jika file tidak ada didirektori maka dengan mode “w” file.txt akan dibuat secara otomatis didirektori tsb.
fwrite($fhandle, $isi); //untuk menambahkan data “$isi” kedalam file.txt
fclose($fhandle); //menutup file.txt

//delay 3 detik
sleep(3);

//baca file sep_hasilcari
$testfile = "SEP_HASILCARI.txt";
$file = fopen($testfile,"r");
$filedata = fread($file,filesize($testfile));
fclose($file);
//echo $filedata;
$hasilcari = explode("^", $filedata);
if ($hasilcari[0] <> '200') {
	echo json_encode(
            array(
                "metadata" => array("code" => 201, "message" => $hasilcari[1]),
				"response" => null
				));
			exit;
}
else {
	//cek nomor kartu sama atau tidak
	if($kartu <> $hasilcari[23]){
		echo json_encode(
            array(
                "metadata" => array("code" => 201, "message" => "Nomor kartu tidak sesuai dengan nomor kartu yang ada di nomor referensi"),
				"response" => null
				));
			exit;
	}
	//cek tgl > 90 hari
	$date1= date_create($tglperiksa); //date('Y-m-d'); //date_create("2019-01-01"); //mis. tgl chekin
	$date2=date_create($hasilcari[40]); //date_create("2019-01-02"); //mis. tgl chekout
	$diff=date_diff($date1,$date2); //menyimpan didalam fungsi date_diff
	$total = $diff->y * 365.25 + $diff->m * 30 + $diff->d + $diff->h/24 + $diff->i / 60;
	if ($total > 90) {
		echo json_encode(
				array(
					//"metadata" => array("code" => 201, "message" => "Tanggal Periksa Tidak Boleh Melebihi 90 Hari Dari Rujukan FKTP"),
					"metadata" => array("code" => 201, "message" => "Mohon Maaf Masa Berlaku Rujukan Habis"),
					"response" => null
					));
				exit;
	}
//$diff=date_diff($date2,$date1); //menyimpan didalam fungsi date_diff
//$jumlah_hari=$diff->format("%d%"); //menampilkan jumlah hari
//$harga=$jumlah_hari * 250000; //mengkalikan jumlah hari dengan nilai tertentu
//echo number_format($harga,2,",",".");
	//echo json_encode(array("message" => $hasilcari[0]));
	
	//echo json_encode(
    //        array(
    //            "metadata" => array("code" => 201, "message" => $jumlah_hari, "tgl1" => $date1, "tgl2" => $date2, "jml" => $total),
	//			"response" => null
	//			));
	//		exit;
}

//delete sep_hasilcari
//unlink($testfile);


*/
//cek poli
/*
$querycek="(select kartu from antrian where kartu = :kartu and tglperiksa = :tgl)";
		$stmt = $conn->prepare( $querycek );
		$stmt->bindParam(':kartu', $kartu, PDO::PARAM_STR, 50);
		$stmt->bindParam(':tgl', $tglperiksa, PDO::PARAM_STR, 50);
		$stmt->execute();
		$num = $stmt->rowCount();
		if($num > 0){
			echo json_encode(
            array(
                "metadata" => array("code" => 201, "message" => "Nomor Antrean Hanya Dapat Diambil 1 Kali Pada Tanggal Yang Sama"),
				"response" => null
				));
				exit;
		}
*/

// $queryinisial="(select inisial,namadokter, namapolibpjs, totkapasitas, kuotajkn, kuotanjkn from Inisial where polybpjs = :poly)";
		// $stmt = $conn->prepare( $queryinisial );
		// $stmt->bindParam(':poly', $kodepoli, PDO::PARAM_STR, 50);
		// $stmt->execute();
		// $num = $stmt->rowCount();
		// if($num > 0){
			// $row = $stmt->fetch(PDO::FETCH_ASSOC);
			// $ini = $row['inisial'];
			// $namadokter = $row['namadokter'];
			// $namapolibpjs =  $row['namapolibpjs'];
			// $totp=$row['totkapasitas'];
// $kuo=$row['kuotajkn'];
// $kuon=$row['kuotanjkn'];
		// }
		// else {
			// echo json_encode(
            // array(
                // "metadata" => array("code" => 201, "message" => "Mohon Maaf Poli Tidak Ditemukan"),
				// "response" => null
				// ));
				// exit;
		// }

//echo $kodepoli;
// $querypraktek="(select case when length(jampraktek) = 1 then concat(:tgl,' 0',jampraktek,':00:00') 
					// else concat(:tgl,' ',jampraktek,':00:00')  end as jampraktek
// from jadwal 
// where polybpjs = :poly
			// and hari = case when date_format(:tgl,'%w') = 0 THEN 'Minggu'
											// when date_format(:tgl,'%w') = 1 THEN 'Senin'
											// when date_format(:tgl,'%w') = 2 THEN 'Selasa'
											// when date_format(:tgl,'%w') = 3 THEN 'Rabu'
											// when date_format(:tgl,'%w') = 4 THEN 'Kamis'
											// when date_format(:tgl,'%w') = 5 THEN 'Jumat'
											// when date_format(:tgl,'%w') = 6 THEN 'Sabtu'
								// end
		// )";
		// $stmt = $conn->prepare( $querypraktek );
		// $stmt->bindParam(':poly', $kodepoli, PDO::PARAM_STR, 50);
		// $stmt->bindParam(':tgl', $tglperiksa, PDO::PARAM_STR, 50);
		// $stmt->execute();
		// $num = $stmt->rowCount();
		// if($num > 0){
			// $row = $stmt->fetch(PDO::FETCH_ASSOC);
			// $jampraktek = $row['jampraktek'];
		// }
		// else {
			// echo json_encode(
            // array(
                // "metadata" => array("code" => 201, "message" => "Mohon Maaf Jadwal Poli Penuh/Libur"),
				// "response" => null
				// ));
				// exit;
		// }

// if($jenreferensi == "") {
	// echo json_encode(
            // array(
                // "metadata" => array("code" => 201, "message" => "Mohon Maaf Jenis Referensi Tidak Sesuai"),
				// "response" => null
				// ));
			// exit;
// }
// if($jenreferensi < 1) {
	// echo json_encode(
            // array(
                // "metadata" => array("code" => 201, "message" => "Mohon Maaf Jenis Referensi Tidak Sesuai"),
				// "response" => null
				// ));
			// exit;
// }
// if($jenreferensi > 2) {
	// echo json_encode(
            // array(
                // "metadata" => array("code" => 201, "message" => "Mohon Maaf Jenis Referensi Tidak Sesuai"),
				// "response" => null
				// ));
			// exit;
// }

// if($req == "") {
	// echo json_encode(
            // array(
                // "metadata" => array("code" => 201, "message" => "Mohon Maaf Jenis Request Tidak Sesuai"),
				// "response" => null
				// ));
			// exit;
// }
// if($req < 1) {
	// echo json_encode(
            // array(
                // "metadata" => array("code" => 201, "message" => "Mohon MaafJenis Request Tidak Sesuai"),
				// "response" => null
				// ));
			// exit;
// }
// if($req > 2) {
	// echo json_encode(
            // array(
                // "metadata" => array("code" => 201, "message" => "Mohon MaafJenis Request Tidak Sesuai"),
				// "response" => null
				// ));
			// exit;
// }



 $headers = array();
    foreach($_SERVER as $key => $value) {
		if ($key == 'HTTP_X_TOKEN') {
			$headers[0] = $value;
			break;
        }
    }
$authHeader = trim($headers[0]);
//echo json_encode(array("message" => $authHeader));
$arr = explode(" ", $authHeader);


/* echo json_encode(array(
    "message" => "sd" .$arr[1]. "/". $authHeader
)); */

$jwt = $arr[0];

if($jwt){


    try {
// Access is granted. Add code of the operation here 
        $decoded = JWT::decode($jwt, $secret_key, array('HS256'));
     /*
		$query2 = "DELETE FROM antrian where kartu = :kartu and kodedokter = :dokter and tglperiksa =:tgl"
		$stmt = $conn->prepare( $query2 );
		//$stmt->bindParam(':poly', $kodepoli, PDO::PARAM_STR, 50);
		//$stmt->execute();
		$stmt->bindParam(':kartu', $kartu, PDO::PARAM_STR, 50);
		$stmt->bindParam(':dokter', $kodedokter, PDO::PARAM_STR, 50);
		$stmt->bindParam(':tgl', $tglperiksa, PDO::PARAM_STR, 50);
		$stmt->execute();
		*/
		
		$query2 = "DELETE FROM antrian where kartu = '$kartu' and kodedokter = '$kodedokter' and tglperiksa = '$tglperiksa'";
		$stmt = $conn->prepare( $query2 );
		$stmt->execute();
		//echo "OK1";
		//$num = $stmt->rowCount();
		
		//$querycount="(select max(cast(nomorantrean as int)) as jml, max(estimasidilayani) as estimasidilayani from antrian where kodepoli = :poly and tglperiksa = :tgl)";
		//$querycount="(select count(kartu) as jml, max(estimasidilayani) as estimasidilayani from antrian where kodepoli = :poly and tglperiksa = :tgl)";
		$querycount="select max(cast(angkaantrean as int)) as jml, max(estimasidilayani) as estimasidilayani from antrian where kodepoli = :poly and tglperiksa = :tgl";
		$stmt = $conn->prepare( $querycount );
		$stmt->bindParam(':poly', $kodepoli, PDO::PARAM_STR, 50);
		$stmt->bindParam(':tgl', $tglperiksa, PDO::PARAM_STR, 50);
		$stmt->execute();
		$num = $stmt->rowCount();
		//echo "OK2";
		if($num > 0){
			$row = $stmt->fetch(PDO::FETCH_ASSOC);
			$jml = $row['jml'] + 1;
			$jampraktekT = $row['estimasidilayani'];
			if($jml == 1) {
				//$jampraktekF=$jampraktek;
				$jampraktekF=$tglperiksa . ' ' . substr(str_replace(' ', '', $jampraktek), 0, 5);
				
			}
			else {
				//$minutes_to_add = 6;
				//$time = new DateTime($jampraktekT);
				//$time->add(new DateInterval('PT' . $minutes_to_add . 'M'));
				//$stamp = $time->format('Y-m-d H:i');
				//$jampraktekF=$stamp;
				$minutes_to_add = 6 * $jml;
				if (strlen($tglperiksa) > 10) {
				$tg = str_replace(substr($tglperiksa, -8), substr($jampraktek, 0, 5), $tglperiksa);
				}
				else {
				$tg = $tglperiksa . ' ' . substr($jampraktek, 0, 5);
				}
				//echo $tg . "<br>";
				$time = new DateTime($tg);
				$time->add(new DateInterval('PT' . $minutes_to_add . 'M'));
				$stamp = $time->format('Y-m-d H:i:ss');
				$jampraktekF=$stamp;
			}
		}
		else {
			echo json_encode(
            array(
                "metadata" => array("code" => 201, "message" => "Gagal Dapat Jumlah Pasien."),
				"response" => null
				));
				exit;
		}
		//$iniall = $ini . $jml;
		$ini22 = strtotime("now");
		$iniall = $ini . $ini22;
		//echo "OK3";
		$query1 = "insert into antrian(kartu,nik,telp,tglperiksa,kodepoli,referensi,
					jenreferensi,req,eks, nomorantrean, inisial, kodebooking, jenisantrean, 
					estimasidilayani, upd, upddaftar, kodedokter) 
					values('$kartu', '$nik', '$telp', '$tglperiksa', '$kodepoli', '$referensi', 
					'$jenreferensi', '$req','$eks', '$jml', '$ini', '$iniall', '$req', 
					'$jampraktekF', 'N', 'N', '$kodedokter'
					)";
		$stmt = $conn->prepare( $query1 );
		//$stmt->bindParam(':poly', $kodepoli, PDO::PARAM_STR, 50);
		$stmt->execute();
		$num = $stmt->rowCount();
		//echo "OK4";
		if($num > 0){
			$row = $stmt->fetch(PDO::FETCH_ASSOC);
		}
		else {
			echo json_encode(
            array(
                "metadata" => array("code" => 201, "message" => "Tidak Berhasil Simpan Data."),
				"response" => null
				));
				exit;
		}

//delay 5 detik
sleep(7);

$querycount="(select max(cast(right(nomorantrean, 3) as int)) as jml, max(estimasidilayani) as estimasidilayani from antrian where kodepoli = :poly and tglperiksa = :tgl)";
		$stmt = $conn->prepare( $querycount );
		$stmt->bindParam(':poly', $kodepoli, PDO::PARAM_STR, 50);
		$stmt->bindParam(':tgl', $tglperiksa, PDO::PARAM_STR, 50);
		$stmt->execute();
		$num = $stmt->rowCount();
		if($num > 0){
			$row = $stmt->fetch(PDO::FETCH_ASSOC);
			$jml = $row['jml'] ;
			$jampraktekT = $row['estimasidilayani'];
			if($jml == 1) {
				//$jampraktekF=$jampraktek;
				$jampraktekF=$tglperiksa . ' ' . substr(str_replace(' ', '', $jampraktek), 0, 5);
			}
			else {
				$jml1 = $jml - 1;
				$minutes_to_add = $jml1 * 6;
				//$time = new DateTime($jampraktekT);
				$time = new DateTime($jampraktek);
				$time->add(new DateInterval('PT' . $minutes_to_add . 'M'));
				$stamp = $time->format('Y-m-d H:i');
				$jampraktekF=$stamp;
			}
		}
		else {
			echo json_encode(
            array(
                "metadata" => array("code" => 201, "message" => "Gagal Dapat Jumlah Edit Pasien."),
				"response" => null
				));
				exit;
		}
		$iniall = $ini . $jml . strtotime(date('Y-m-d'));
		//$query1 = "update antrian set inisial='$ini', kodebooking='$iniall', estimasidilayani='$jampraktekF' where kartu = '$kartu' and kodepoli = '$kodepoli' and tglperiksa='$tglperiksa'";
		
		//$query1 = "update antrian set inisial='$ini', kodebooking='$iniall' where kartu = '$kartu' and kodepoli = '$kodepoli' and tglperiksa='$tglperiksa'";
		
		//values('$kartu', '$nik', '$telp', '$tglperiksa', '$kodepoli', '$referensi', '$jenreferensi', '$req','$eks'
		//			, '$jml', '$ini', '$iniall', '$req', '$jampraktekF', 'N'
		
		//$stmt = $conn->prepare( $query1 );
		
		//$stmt->bindParam(':kartu', $kartu, PDO::PARAM_STR, 50);
		//$stmt->bindParam(':tgl', $tglperiksa, PDO::PARAM_STR, 50);
		//$stmt->bindParam(':poli', $kodepoli, PDO::PARAM_STR, 50);
		
		//$stmt->execute();
		//$num = $stmt->rowCount();
		
		//if($num > 0){
		
		//$row = $stmt->fetch(PDO::FETCH_ASSOC);
		
		//}
		//else {
		//	echo json_encode(
        //    array(
        //        "metadata" => array("code" => 201, "message" => "Tidak Berhasil Edit Data."),
		//		"response" => null
		//		));
		//		exit;
		//}
		
		$query = "SELECT a.id, kartu,nik,telp,tglperiksa,kodepoli,referensi,jenreferensi,req,eks 
				, NoMR, nomorantrean, kodebooking, jenisantrean, estimasidilayani, namapoli, namadokter
				, inisial
				, UNIX_TIMESTAMP(estimasidilayani) * 1000 as est
				, p.polyname, a.angkaantrean
				FROM antrian a inner join poly p on a.kodepoli = p.polybpjs 
				WHERE kartu = :kartu and kodepoli = :poli and tglperiksa=:tgl
				
				";
				//WHERE kartu = :kartu and polycode = :poli 
				//";
				//and tglperiksa=:tgl" ;
		$stmt = $conn->prepare( $query );
		//$stmt->bindParam(1, $kartu);
		
		$stmt->bindParam(':kartu', $kartu, PDO::PARAM_STR, 50);
		$stmt->bindParam(':tgl', $tglperiksa, PDO::PARAM_STR, 50);
		$stmt->bindParam(':poli', $kodepoli, PDO::PARAM_STR, 50);
		$stmt->execute();
		$num = $stmt->rowCount();

		if($num > 0){
			$row = $stmt->fetch(PDO::FETCH_ASSOC);
			$id = $row['id'];
			// $NoMR = $row['NoMR'];
			$inisial =$row['inisial']; 
			$nomorantrean =$row['nomorantrean']; 
			$kodebooking = $row['kodebooking'];
			$jenisantrean = $row['jenisantrean'];
			$estimasidilayani = $row['est'];
			$namapoli = $row['polyname'];
			$nomr = $row['NoMR'];
			$angkaantrean = $row['angkaantrean'];
			$namadokter = $row['namadokter']; 
/*
 "nomorantrean": "A-12",
      "angkaantrean": 12,
      "kodebooking": "16032021A001",
      "norm": "123345",
      "namapoli": "Anak",
      "namadokter": "Dr. Hendra",
      "estimasidilayani": 1615869169000,
      "sisakuotajkn": 5,
      "kuotajkn": 30,
      "sisakuotanonjkn": 5,
      "kuotanonjkn": 30,
      "keterangan": "Peserta harap 60 menit lebih awal guna pencatatan administrasi."
	  */
			http_response_code(200);

			echo json_encode(
            array(
                "response" => array("nomorantrean" => $nomorantrean, //$inisial.$nomorantrean,
									"angkaantrean" => intval($angkaantrean),
									"kodebooking" => $kodebooking, 
									"norm" => $nomr,
									"namapoli" => $namapoli,
									"namadokter" => $namadokter,
									"estimasidilayani" => intval($estimasidilayani),
									"sisakuotajkn" => intval($kuo) - intval($angkaantrean),//0,
									"kuotajkn" => intval($kuo), //0,
									"sisakuotanonjkn" => intval($kuon),//0,
									"kuotanonjkn" => intval($kuon),//0,
									"keterangan" => "Peserta harap 60 menit lebih awal guna pencatatan administrasi. Untuk Registrasi Via Online Mohon Mengambil Nomor Pendaftaran Via Online Pada Loket Antrian."
									//,id" => $id
									),
                //"token" => $jwt,
                "metadata" => array("message" => "Ok", "code" => 200),
                //"expireAt" => $expire_claim
            ));
				
				
		}
			else{

				http_response_code(201);
				echo json_encode(array("message" => "Tidak Berhasil Ambil Data Antrian.", "kartu" => $kartu, "poli" => $kodepoli, "tglperiksa" => $tglperiksa));
			}
		

        /* echo json_encode(array(
            "message" => "Access granted:",
         //   "error" => $e->getMessage()
        )); */

    }catch (Exception $e){
echo json_encode(
            array(
                "metadata" => array("code" => 201, "message" => "Access denied. " . $e->getMessage()),
				"response" => null
				));
    //http_response_code(401);

    //echo json_encode(array(
    //    "message" => "Access denied.",
    //    "error" => $e->getMessage()
    //));
}

}
?>