<?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");

$tanggalperiksa = '';
$kodepoli = '';
$polieksekutif = '';
$namapoli = '';
$totalantrean = '';
$jumlahterlayani = '';
$lastupdate = '';

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

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

$tanggalperiksa = $data->tanggalperiksa;
$kodepoli = $data->kodepoli;
$polieksekutif = $data->polieksekutif;

$pecah = explode("-", $tanggalperiksa);
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" => "Tgl Periksa Tidak Valid"),
				"response" => null
				));
			exit;
}
if (strlen($pecah[0])> 4) {
	echo json_encode(
            array(
                "metadata" => array("code" => 201, "message" => "Tgl Periksa Tidak Valid"),
				"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" => "Kode Poli Tidak Sama"),
				"response" => null
				));
				exit;
		}

$querycek="(select kartu from antrian where tglperiksa = :tgl and kodepoli = :kodepoli)";
		$stmt = $conn->prepare( $querycek );
		$stmt->bindParam(':kodepoli', $kodepoli, PDO::PARAM_STR, 50);
		$stmt->bindParam(':tgl', $tanggalperiksa, PDO::PARAM_STR, 50);
		$stmt->execute();
		$num = $stmt->rowCount();
		if($num < 1){
			echo json_encode(
            array(
                "metadata" => array("code" => 201, "message" => "Tidak Ada Pasien Di Jadwal Ini"),
				"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 p.polyname, count(a.kodepoli) as tot, 0 as terlayani
				, UNIX_TIMESTAMP(NOW()) * 1000 as lu
				FROM antrian a inner join poly p on a.kodepoli = p.polybpjs 
				WHERE kodepoli = :poli and tglperiksa=:tgl ";
				//and tglperiksa = :tgl";
		
		$stmt = $conn->prepare( $query );
		$stmt->bindParam(':poli', $kodepoli, PDO::PARAM_STR, 50);
		$stmt->bindParam(':tgl', $tanggalperiksa, PDO::PARAM_STR, 50);
		$stmt->execute();
		$num = $stmt->rowCount();

		if($num > 0){
			$row = $stmt->fetch(PDO::FETCH_ASSOC);
			$namapoli = $row['polyname'];
			$totalantrean = $row['tot'];
			$jumlahterlayani = $row['terlayani'];
			$lastupdate = intval($row['lu']);
			//$h['lastupdate'] = intval($x["lu"]); 
			http_response_code(200);

			echo json_encode(
            array(
                "response" => array("namapoli" => $namapoli,
									"totalantrean" => $totalantrean, 
									"jumlahterlayani" => $jumlahterlayani, 
									"lastupdate" => $lastupdate
									//, "p" => $kodepoli
									//, "t" => $tglperiksa
									),
                "metadata" => array("message" => "Ok", "code" => 200),
            ));
				
				
		}
			else{

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

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

}
?>