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


$email = '';
$password = '';

$databaseService = new DatabaseService();
$conn = $databaseService->getConnection();



$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 " . $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))
    {
        $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 + 60; // 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
        ));

        http_response_code(200);

        $jwt = JWT::encode($token, $secret_key);
		
		//$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{

        http_response_code(401);
        echo json_encode(array("message" => "Login failed.", "password" => $password));
    }
}
	else
	{
		echo json_encode(array("message" => "Tidak Ada Data Di Database"));
}
?>