<?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: *");
/*
nama": "sumarsono",
   "jeniskelamin": "L",
   "tanggallahir": "1985-03-01",
   "nohp": "085635228888",
   "alamat": "alamat yang muncul merupakan alamat lengkap",
   "kodeprop": "11",
   "namaprop": "Jawa Barat",
   "kodedati2": "0120",
   "namadati2": "Kab. Bandung",
   "kodekec": "1319",
   "namakec": "Soreang",
   "kodekel": "D2105",
   "namakel": "Cingcin",
   "rw": "001",
   "rt
  */ 
$nomorkartu = '';
$nik = '';
$nomorkk='';
$nama='';
$jeniskelamin='';
$tanggallahir='';
$nohp = '';
$alamat = '';
$kodeprop = '';
$namaprop = '';
$kodedati2 = '';
$namadati2 = '';
$kodekec = '';
$namakec = '';
$kodekel = '';
$namakel = ''; 
$rw = '';
$rt = '';


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

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

	
$nomorkartu = $data->nomorkartu;
$nik = $data->nik;
$nomorkk = $data->nomorkk;
$nama = $data->nama;
$jeniskelamin = $data->jeniskelamin;
$tanggallahir= $data->tanggallahir;
$nohp = $data->nohp;
$alamat= $data->alamat;
$kodeprop= $data->kodeprop;
$namaprop= $data->namaprop;
$kodedati2 = $data->kodedati2;
$namadati2 = $data->namadati2;
$kodekec = $data->kodekec;
$namakec =$data->namakec;
$kodekel =$data->kodekel;
$namakel =$data->namakel;
$rw =$data->rw;
$rt =$data->rt;
echo json_encode(
            array(
                "metadata" => array("code" => 201, "message" => "Mohon Maaf Untuk Pendaftaran Baru Silahkan Datang Ke Rumah Sakit Untuk Mendapatkan Nomor Rekam Medik"),
				"response" => null
				));
			exit;
/*
if($nomorkartu == ""){
	echo json_encode(
            array(
                "metadata" => array("code" => 201, "message" => "Nomor Kartu Belum Diisi"),
				"response" => null
				));
			exit;
}

// cek 13 digit
if(strlen($nomorkartu) != 13){
echo json_encode(
            array(
                "metadata" => array("code" => 201, "message" => "Format Nomor Kartu Tidak Sesuai"),
				"response" => null
				));
			exit;
}
if($nik == ""){
	echo json_encode(
            array(
                "metadata" => array("code" => 201, "message" => "NIK Belum Diisi"),
				"response" => null
				));
			exit;
}
if(strlen($nik) != 16){
echo json_encode(
            array(
                "metadata" => array("code" => 201, "message" => "Format NIK Tidak Sesuai"),
				"response" => null
				));
			exit;
}
if($nomorkk == ""){
	echo json_encode(
            array(
                "metadata" => array("code" => 201, "message" => "Nomor KK Belum Diisi"),
				"response" => null
				));
			exit;
}
if($nama == ""){
	echo json_encode(
            array(
                "metadata" => array("code" => 201, "message" => "Nama Belum Diisi"),
				"response" => null
				));
			exit;
}
if($jeniskelamin == ""){
	echo json_encode(
            array(
                "metadata" => array("code" => 201, "message" => "Jenis Kelamin Belum Dipilih"),
				"response" => null
				));
			exit;
}
if($tanggallahir == ""){
	echo json_encode(
            array(
                "metadata" => array("code" => 201, "message" => "Tanggal Lahir Belum Diisi"),
				"response" => null
				));
			exit;
}

$pecah = explode("-", $tanggallahir);
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" => "Format Tanggal Lahir 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" => "Format Tanggal Lahir 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($tanggallahir) > strtotime(date('Y-m-d'))) {
	echo json_encode(
            array(
                "metadata" => array("code" => 201, "message" => "Tgl Lahir Tidak Boleh Lebih Dari Hari Ini"),
				"response" => null
				));
			exit;
}

if($alamat == ""){
	echo json_encode(
            array(
                "metadata" => array("code" => 201, "message" => "Alamat Belum Diisi"),
				"response" => null
				));
			exit;
}
if($kodeprop == ""){
	echo json_encode(
            array(
                "metadata" => array("code" => 201, "message" => "Kode Propinsi Belum Diisi"),
				"response" => null
				));
			exit;
}
if($namaprop == ""){
	echo json_encode(
            array(
                "metadata" => array("code" => 201, "message" => "Propinsi Belum Diisi"),
				"response" => null
				));
			exit;
}
if($kodedati2 == ""){
	echo json_encode(
            array(
                "metadata" => array("code" => 201, "message" => "Kode Dati 2 Belum Diisi"),
				"response" => null
				));
			exit;
}
if($namadati2 == ""){
	echo json_encode(
            array(
                "metadata" => array("code" => 201, "message" => "Dati 2 Belum Diisi"),
				"response" => null
				));
			exit;
}
if($kodekec == ""){
	echo json_encode(
            array(
                "metadata" => array("code" => 201, "message" => "Kode Kecamatan Belum Diisi"),
				"response" => null
				));
			exit;
}
if($namakec == ""){
	echo json_encode(
            array(
                "metadata" => array("code" => 201, "message" => "Kecamatan Belum Diisi"),
				"response" => null
				));
			exit;
}
if($kodekel == ""){
	echo json_encode(
            array(
                "metadata" => array("code" => 201, "message" => "Kode Kelurahan Belum Diisi"),
				"response" => null
				));
			exit;
}
if($namakel == ""){
	echo json_encode(
            array(
                "metadata" => array("code" => 201, "message" => "Kelurahan Belum Diisi"),
				"response" => null
				));
			exit;
}
if($rw == ""){
	echo json_encode(
            array(
                "metadata" => array("code" => 201, "message" => "RW Belum Diisi"),
				"response" => null
				));
			exit;
}
if($rt == ""){
	echo json_encode(
            array(
                "metadata" => array("code" => 201, "message" => "RT Belum Diisi"),
				"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);




$jwt = $arr[0];

if($jwt){


    try {
// Access is granted. Add code of the operation here 
        $decoded = JWT::decode($jwt, $secret_key, array('HS256'));
     
		$querycount="(select max(cast(nomorantrean 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'] + 1;
			$jampraktekT = $row['estimasidilayani'];
			if($jml == 1) {
				$jampraktekF=$jampraktek;
			}
			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;
			}
		}
		else {
			echo json_encode(
            array(
                "metadata" => array("code" => 201, "message" => "Gagal Dapat Jumlah Pasien."),
				"response" => null
				));
				exit;
		}
		$iniall = $ini . $jml;
		$query1 = "insert into antrian(kartu,nik,telp,tglperiksa,kodepoli,referensi,jenreferensi,req,eks, nomorantrean, inisial, kodebooking, jenisantrean, estimasidilayani, upd) 
					values('$kartu', '$nik', '$telp', '$tglperiksa', '$kodepoli', '$referensi', '$jenreferensi', '$req','$eks'
					, '$jml', '$ini', '$iniall', '$req', '$jampraktekF', 'N'
					)";
		$stmt = $conn->prepare( $query1 );
		//$stmt->bindParam(':poly', $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 Simpan Data."),
				"response" => null
				));
				exit;
		}

//delay 5 detik
sleep(5);

$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;
			}
			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;
		$query1 = "update antrian set inisial='$ini', kodebooking=nomorantrean, estimasidilayani='$jampraktekF' 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
				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'];
			//$namadokter = $row['namadokter']; 


			http_response_code(200);

			echo json_encode(
            array(
                "response" => array("nomorantrean" => $nomorantrean, //$inisial.$nomorantrean,
									"kodebooking" => $kodebooking, 
									"jenisantrean" => $jenisantrean, 
									"estimasidilayani" => $estimasidilayani,
									"namapoli" => $namapoli,
									"namadokter" => $namadokter
									//,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));
			}
		

      

    }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()
    //));
}

}
*/
?>