<?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"
   
$kodepoli = '';
$kodedokter = '';
$tanggalperiksa = '';
$jampraktek = '';

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

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

$kodepoli = $data->kodepoli;
$kodedokter = $data->kodedokter;
$tanggalperiksa = $data->tanggalperiksa;
$jampraktek = $data->jampraktek;
$namadokter = "";
$namapolibpjs= "";
$totp="";
$kuo="";
$kuon="";
$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;
		}

$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 {
			echo json_encode(
            array(
                "metadata" => array("code" => 201, "message" => "Mohon Maaf Poli Tidak Ditemukan"),
				"response" => null
				));
				exit;
		}

if ( strtotime($tanggalperiksa) < strtotime(date('Y-m-d'))) {
	echo json_encode(
            array(
                "metadata" => array("code" => 201, "message" => "Tanggal Periksa Tidak Berlaku"),
				"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 namapoli,
namadokter,
totalantrean,
sisaantrean,
antreanpanggil,
sisakuotajkn,
kuotajkn,
sisakuotanonjkn,
kuotanonjkn,
keterangan,
sudahdipanggil
				FROM status
				WHERE kodepoli = :kodepoli and kodedokter= :kodedokter and tanggalperiksa= :tanggalperiksa";
		
		$stmt = $conn->prepare( $query );
		$stmt->bindParam(':kodepoli', $kodepoli, PDO::PARAM_STR, 50);
		$stmt->bindParam(':kodedokter', $kodedokter, PDO::PARAM_STR, 50);
		$stmt->bindParam(':tanggalperiksa', $tanggalperiksa, PDO::PARAM_STR, 50);
		$stmt->execute();
		$num = $stmt->rowCount();
//echo $tanggalperiksa;
//echo $kodepoli;
//echo $kodedokter;
//echo $num;
		if($num > 0){
						
			//echo "test";
			$response = array();
			//$response["list"] = array();
			
			while($x = $stmt->fetch(PDO::FETCH_ASSOC)){
			/*	
			$h['namapoli'] = $x["namapoli"];
			//$h['tanggaloperasi'] = $x["tanggaloperasi"];
			//$h['tanggaloperasi'] = date('Y-m-d', strtotime($x["tanggaloperasi"]));
			$h['namadokter'] = $x["namadokter"];
			$h['totalantrean'] = intval($x["totalantrean"]);
			$h['sisaantrean'] = intval($x["totalantrean"]) - intval($x["sudahdipanggil"]); //intval($x["sisaantrean"]);//
			$h['antreanpanggil'] = $x["antreanpanggil"];
			$h['sisakuotajkn'] = intval($kuo) - intval($x["totalantrean"]); //0;
			$h['kuotajkn']= intval($kuo); //0;
			$h['sisakuotanonjkn']= intval($kuon);//0;
			$h['kuotanonjkn']= intval($kuon); //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
				array("namapoli" => $x["namapoli"],
								"namadokter" => $x["namadokter"],
				 "totalantrean" =>  intval($x["totalantrean"]),
      "sisaantrean" => intval($x["totalantrean"]) - intval($x["sudahdipanggil"]), //intval($x["sisaantrean"]);//,
      "antreanpanggil" => $x["antreanpanggil"],
      "sisakuotajkn" => intval($kuo) - intval($x["totalantrean"]),
      "kuotajkn" => intval($kuo),
      "sisakuotanonjkn" => intval($kuon),
      "kuotanonjkn" => intval($kuon),
      "keterangan"=> ""
						)			,
                "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."));
				*/
				$response = array();
			//$response["list"] = array();
			//while($x = $stmt->fetch(PDO::FETCH_ASSOC)){
				
			$h['namapoli'] = $namapolibpjs;
			//$h['tanggaloperasi'] = $x["tanggaloperasi"];
			//$h['tanggaloperasi'] = date('Y-m-d', strtotime($x["tanggaloperasi"]));
			$h['namadokter'] = $namadokter;
			$h['totalantrean'] = 0;//intval($x["totalantrean"]);
			$h['sisaantrean'] = 0;//intval($totp);//60; //intval($x["sisaantrean"]);
			$h['antreanpanggil'] = "";//$x["antreanpanggil"];
			$h['sisakuotajkn'] = intval($kuo); //48;
			$h['kuotajkn']= intval($kuo); //0;
			$h['sisakuotanonjkn']= intval($kuon); //12;
			$h['kuotanonjkn']= intval($kuon); //0;
			$h['keterangan']= "";
			//$h['lastupdate'] = $x["lu"]; 
			//array_push($response["list"], $h);
			array_push($response, $h);
			//}
			
			http_response_code(200);
			echo json_encode(
            array(
			/*
			 "namapoli": "Anak",
      "namadokter": "Dr. Hendra",
     
	  */
                "response" => array("namapoli" => $namapolibpjs,
								"namadokter" => $namadokter,
				 "totalantrean" => 0,
      "sisaantrean" => 0,
      "antreanpanggil" => "",
      "sisakuotajkn" => intval($kuo),
      "kuotajkn" => intval($kuo),
      "sisakuotanonjkn" => intval($kuon),
      "kuotanonjkn" => intval($kuon),
      "keterangan"=> ""
							)
									,
                "metadata" => array("message" => "Ok", "code" => 200),
            )
			)
			;
			}
		

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

}
?>