<?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->notelp;
$tglperiksa = $data->tanggalperiksa;
$kodepoli = $data->kodepoli;
$referensi = $data->nomorreferensi;
$jenreferensi = $data->jenisreferensi;
$req = $data->jenisrequest;
$eks = $data->polieksekutif;

if($kartu == ""){
			http_response_code(201);
				echo json_encode(array("message" => "Kode Poli Tidak Ada / RS Tidak Menyediakan Layanan Poli Ini", "kodepoli" => $kodepoli));
		}
		else {
			
		}
	
 $headers = array();
    foreach($_SERVER as $key => $value) {
        //if (substr($key, 0, 5) == 'X-TOKEN') {
			//echo json_encode(array("message" => $key));
			//echo json_encode(array("message" => $value));
		if ($key == 'HTTP_X_TOKEN') {
			//echo json_encode(array("message" => "OK"));
			//$header = str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))));
			//$header = $key;
			
			//$headers[$header] = $value;
			$headers[0] = $value;
			//echo json_encode(array("message" => $headers));
			break;
           // continue;
        }
        //$header = str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))));
        //$headers[$header] = $value;
    }
	//echo json_encode(array("message" => $headers[0]));

//$authHeader = trim($_SERVER['HTTP_AUTHORIZATION']);
//$authHeader = trim($_SERVER['x-token']);
//$authHeader = trim($_REQUEST ['REQUEST_METHOD']);
$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){

$ini = "";
$iniall = "";
$jampraktek="";
$jampraktekT="";
$jampraktekF="";
    try {

        $decoded = JWT::decode($jwt, $secret_key, array('HS256'));

        // Access is granted. Add code of the operation here 
		$queryinisial="(select inisial 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'];
		}
		else {
			http_response_code(201);
				echo json_encode(array("message" => "Kode Poli Tidak Ada / RS Tidak Menyediakan Layanan Poli Ini", "kodepoli" => $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 {
			http_response_code(202);
				echo json_encode(array("message" => "Tidak Ada praktek poli pada hari ini.", "kodepoli" => $kodepoli));
		}
		
		$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 {
			http_response_code(203);
				echo json_encode(array("message" => "Gagal Dapat Jumlah Pasien.", "kodepoli" => $kodepoli));
		}
		$iniall = $ini . $jml;
		$query1 = "insert into antrian(kartu,nik,telp,tglperiksa,kodepoli,referensi,jenreferensi,req,eks, nomorantrean, inisial, kodebooking, jenisantrean, estimasidilayani) 
					values('$kartu', '$nik', '$telp', '$tglperiksa', '$kodepoli', '$referensi', '$jenreferensi', '$req','$eks'
					, '$jml', '$ini', '$iniall', '$req', '$jampraktekF'
					)";
		$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 {
			http_response_code(204);
				echo json_encode(array("message" => "Tidak Berhasil Simpan Data.", "inisial" => $ini));
		}


		$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" => $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(205);
				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){

    http_response_code(401);

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

}
?>