<?php
include_once './config/database.php';
//include_once './config/koneksi.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");

//"kodepoli": "ANA",
//   "kodedokter": 12346,
//   "tanggalperiksa": "2020-01-28",
//   "jampraktek": "08:00-16:00"
   
$kodebooking = '';
$totp="";
$kuo="";
$kuon="";

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

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

$kodebooking = $data->kodebooking;

	//cek antrian
$querycek="(select kodebooking from antrian where kodebooking = :kodebooking)";
		$stmt = $conn->prepare( $querycek );
		$stmt->bindParam(':kodebooking', $kodebooking, PDO::PARAM_STR, 50);
		$stmt->execute();
		$num = $stmt->rowCount();
		if($num < 1){
			echo json_encode(
            array(
                "metadata" => array("code" => 201, "message" => "Antrean Tidak Ditemukan"),
				"response" => null
				));
				exit;
		}

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


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

$jwt = $arr[0];

if($jwt){

    try {

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

        // Access is granted. Add code of the operation here 
		$query = "SELECT nomorantrean,
s.namapoli,
s.namadokter,
sisaantrean,
antreanpanggil,
0 as waktutunggu,
keterangan
, i.TotKapasitas
,i.KuotaJKN
,i.KuotaNJKN
, a.angkaantrean
, i.spm
, s.totalantrean
, s.sudahdipanggil
				FROM antrian a inner join status s on s.kodedokter = a.kodedokter and a.tglperiksa = s.tanggalperiksa
				inner join inisial i on i.kdoksep = a.kodedokter
				WHERE kodebooking = :kodebooking";
		
		$stmt = $conn->prepare( $query );
		$stmt->bindParam(':kodebooking', $kodebooking, PDO::PARAM_STR, 50);
		$stmt->execute();
		$num = $stmt->rowCount();

		if($num > 0){
						
			$response = array();
			//$response["list"] = array();
			while($x = $stmt->fetch(PDO::FETCH_ASSOC)){
			$totp=intval($x["TotKapasitas"]);
			$kuo=intval($x["KuotaJKN"]);
			$kuon=intval($x["KuotaNJKN"]);
			
			$h['nomorantrean'] = $x["nomorantrean"];
			//$h['tanggaloperasi'] = $x["tanggaloperasi"];
			//$h['tanggaloperasi'] = date('Y-m-d', strtotime($x["tanggaloperasi"]));
			$h['namapoli'] = $x["namapoli"];
			$h['namadokter'] = $x["namadokter"];
			$h['sisaantrean'] = intval($x["totalantrean"]) - intval($x["sudahdipanggil"]);
			$h['antreanpanggil'] = $x["antreanpanggil"];
			$h['waktutunggu'] = intval((intval($x["angkaantrean"]) - 1) * (intval($x["spm"])) * 60); //"0";
			$h['keterangan']= "";
			
			//$h['lastupdate'] = $x["lu"]; 
			//array_push($response["list"], $h);
			array_push($response, $h);
			}
			
			http_response_code(200);
			echo json_encode(
            array(
                "response" => $response
									,
                "metadata" => array("message" => "Ok", "code" => 200),
            ));
		}
			else{

				http_response_code(401);
				//echo json_encode(array("message" => "Tidak Ada Data.", "poli" => $kodepoli, "Tgl" => $tanggalperiksa));
				echo json_encode(array("message" => "Tidak Ada Data."));
			}
		

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

}
?>