<?php
include_once './config/database.php';
require "../vendor/autoload.php";
//require('https').globalAgent.options.ca = require('ssl-root-cas/latest').create();
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");
//echo time() . '.';
date_default_timezone_set('Asia/Jakarta');
//echo time() * 1000 . '.';
//echo date('d-m-Y H:i:s');
//echo strtotime(date('Y-m-d H:i:s'));// * 1000;
//echo date_default_timezone_get();
//echo date('Y-m-d H:i:s', time() );
//echo date('Y-m-d H:i:s', microtime(true));
$email = '';
$password = '';

$databaseService = new DatabaseService();
$conn = $databaseService->getConnection();
function getRequestHeaders() {
    $headers = array();
    foreach($_SERVER as $key => $value) {
        if (substr($key, 0, 5) <> 'HTTP_') {
            continue;
        }
        $header = str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))));
        $headers[$header] = $value;
    }
    return $headers;
}

$headers = getRequestHeaders();

foreach ($headers as $header => $value) {
   // echo "$header: $value <br />\n";
	if ($header == 'X-Username') {
			$email = $value;
			//break;
        }
		if ($header == 'X-Password') {
			$password  = $value;
			//break;
        }
}
/*
//$headers = array();
    foreach($_SERVER as $key => $value) {
		echo $key;
		echo $value;
		if ($key == 'HTTP_X_USERNAME') {
			$email = $value;
			break;
        }
		if ($key == 'HTTP_X_PASSWORD') {
			$password  = $value;
			break;
        }
		
    }
	*/
//echo $email;
//echo $password;
//$data = json_decode(file_get_contents("php://input"));

//$email = $data->email;
//$email = $data->username;
//$password = $data->password;

$table_name = 'users';
//echo "Connection ok: ";
//echo json_encode(array("message" => "Login failed.", "password" => $password));
$query = "SELECT id, first_name, last_name, password FROM " . $table_name . " WHERE email = ? LIMIT 0,1";
//$query = "SELECT id, first_name, last_name, password FROM users";
//$query = "SELECT id, first_name, last_name, password FROM " . $table_name . " WHERE email = " . $email;

//$query = "SELECT id, first_name, last_name, password FROM [users]";

$stmt = $conn->prepare( $query );
$stmt->bindParam(1, $email);
$stmt->execute();
$num = $stmt->rowCount();

if($num > 0){
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    $id = $row['id'];
    $firstname = $row['first_name'];
    $lastname = $row['last_name'];
    $password2 = $row['password'];

    if(password_verify($password, $password2))
		
    {
		/*
		 global $username, $password;
        $header = json_encode(['typ' => 'JWT', 'alg' => 'HS256']);
        $payload = json_encode(['username' => $email, 'password' => $password, 'date' => strtotime(date('Y-m-d H:')) * 1000]);
        $base64UrlHeader = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($header));
        $base64UrlPayload = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($payload));
        $signature = hash_hmac('sha256', $base64UrlHeader . "." . $base64UrlPayload, 'b155m1774H', true);
        $base64UrlSignature = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($signature));
        $jwt = $base64UrlHeader . "." . $base64UrlPayload . "." . $base64UrlSignature;
        //return $jwt;
		*/
		
        $secret_key = "HOSMIS";
        $issuer_claim = "HOSMIS_ONLINE"; // this can be the servername
        $audience_claim = "BPJS";
        $issuedat_claim = time(); // issued at
        $notbefore_claim = $issuedat_claim + 10; //not before in seconds
        $expire_claim = $issuedat_claim + 600; // expire time in seconds
		//$notbefore_claim = $issuedat_claim + 0; //not before in seconds
		//$expire_claim = $issuedat_claim + 600; // expire time in seconds
        $token = array(
            "iss" => $issuer_claim,
            "aud" => $audience_claim,
            "iat" => $issuedat_claim,
           // "nbf" => $notbefore_claim,
            "exp" => $expire_claim,
            "data" => array(
                //"id" => $id,
                //"firstname" => $firstname,
                //"lastname" => $lastname,
                "username" => $email
        )
		);
		
		
//echo date(DateTime::ISO8601, time());
//echo time();
        http_response_code(200);
//$jwt = new JWT();
//Waktu yang dimaklumi.
//$jwt::$leeway += 14;

        $jwt = JWT::encode($token, $secret_key);
		
		//$jwt::$leeway = 1.5;
//try {
//	$decoded == JWT::decode($jwt, $secret_key, array('HS256'));
//$refresh_token=$decoded->data->refresh_token;
//}
//catch (Exception $exception) {
//	 echo "error: " . $exception->getMessage();
//}		
		//$json = {"response":{"token":$jwt}, "metadata":{"message":"Ok","code":"200"}};

//$data = json_decode($json, true);
//print_r($data);
//echo json_encode($data);
        echo json_encode(
            array(
                "response" => array("token" => $jwt),
                //"token" => $jwt,
                "metadata" => array("message" => "Ok", "code" => 200),
               // "expireAt" => $expire_claim
            ));
    }
    else{
		echo json_encode(
            array(
                "metadata" => array("code" => 201, "message" => "Username atau Password Tidak Sesuai"),
				"response" => null
				));
    }
}
	else
	{
		echo json_encode(
            array(
                "metadata" => array("code" => 201, "message" => "Tidak Ada Data Di Database"),
				"response" => null
				));
		//echo json_encode(array("message" => "Tidak Ada Data Di Database"));
}
?>