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

$tanggalawal = '';
$tanggalakhir = '';

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

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

$tanggalawal = $data->tanggalawal;
$tanggalakhir = $data->tanggalakhir;

//if ( strtotime($tanggalakhir) < strtotime($tanggalawal()) ) {
	if ( $tanggalakhir < $tanggalawal ) {
	echo json_encode(
            array(
                "metadata" => array("code" => 201, "message" => "Tanggal Akhir Tidak Boleh Lebih Kecil dari Tanggal Awal"),
				"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 a.id,
					nopeserta,
					kodebooking,
					tanggaloperasi,
					jenistindakan,
					kodepoli,
					p.polyname as namapoli,
					terlaksana,
					lastupdate
				, UNIX_TIMESTAMP(NOW()) * 1000 as lu
				FROM operasi a inner join poly p on a.kodepoli = p.polybpjs 
				WHERE tanggaloperasi between :tglawal and :tglakhir";
		
		$stmt = $conn->prepare( $query );
		$stmt->bindParam(':tglawal', $tanggalawal, PDO::PARAM_STR, 50);
		$stmt->bindParam(':tglakhir', $tanggalakhir, PDO::PARAM_STR, 50);
		$stmt->execute();
		$num = $stmt->rowCount();

		if($num > 0){
						
			$response = array();
			$response["list"] = array();
			while($x = $stmt->fetch(PDO::FETCH_ASSOC)){
			$h['kodebooking'] = $x["kodebooking"];
			//$h['tanggaloperasi'] = $x["tanggaloperasi"];
			$h['tanggaloperasi'] = date('Y-m-d', strtotime($x["tanggaloperasi"]));
			$h['jenistindakan'] = $x["jenistindakan"];
			$h['kodepoli'] = $x["kodepoli"];
			$h['namapoli'] = $x["namapoli"];
			$h['terlaksana'] = $x["terlaksana"];
			$h['nopeserta'] = $x["nopeserta"];
			//$h['lastupdate'] = $x["lu"]; 
			$h['lastupdate'] = intval($x["lu"]); 
			array_push($response["list"], $h);
			}
			
			http_response_code(200);
			echo json_encode(
            array(
                "response" => $response
									,
                "metadata" => array("message" => "Ok", "code" => 200),
            ));
		}
			else{
			echo json_encode(
            array(
                "metadata" => array("code" => 201, "message" => "Gagal Get Jadwal Operasi"),
				"response" => null
				));
			exit;
			//	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()
    //));
}

}
?>