<?php

use Firebase\JWT\JWT;

class Authentication
{

    public function getJwtToken($username, $config)
    {

        $now = new DateTime();
        $future = new DateTime('+10 minutes');
        /* 'exp' => $future->getTimeStamp() */
        $payload = [
            'iss' => 'AEC',
            'iat' => $now->getTimeStamp(),
            'exp' => strtotime("+1 week"),
            'sub' => $username,
            'scope' => $username['scope']
        ];

        //$secret = getenv('MY_SECRET', true) ?: getenv('MY_SECRET');
        //$secret = (!empty($_SERVER['MY_SECRET'])) ? $_SERVER['MY_SECRET'] : getenv('MY_SECRET');
        //$secret = (!empty($_ENV['MY_SECRET'])) ? $_ENV['MY_SECRET'] : getenv('MY_SECRET');
        $secret = $config['MY_SECRET'];


        $token = JWT::encode($payload, $secret, 'HS256');

        return $token;
    }

    public function decodeJwtToken($token, $envs)
    {
        //$secret = getenv('MY_SECRET', true) ?: getenv('MY_SECRET');
        //$secret = (!empty($_SERVER['MY_SECRET'])) ? $_SERVER['MY_SECRET'] : getenv('MY_SECRET');
        //$secret = (!empty($_ENV['MY_SECRET'])) ? $_ENV['MY_SECRET'] : getenv('MY_SECRET');

        $secret = $envs['MY_SECRET'];

        $decoded = JWT::decode($token, $secret, array('HS256'));
        return $decoded;

    }

    public function getUsername($request, $config)
    {
        $headers = $request->getHeaders();
        $auth = $headers['HTTP_AUTHORIZATION'];
        $token = explode(' ', $auth[0]);
        $jwt = $token[1];

        $d = $this->decodeJwtToken($jwt, $config);
        $username = $d->jti;

        return $username;
    }
}
