<?php

use Config\Services;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use App\Models\UsersModel;

function getJWTFromRequest($authenticationHeader): string
{
    if (is_null($authenticationHeader)) { //JWT is absent
        throw new Exception('Missing or invalid JWT in request');
    }
    //JWT is sent from client in the format Bearer XXXXXXXXX
    return explode(' ', $authenticationHeader)[1];
}

function validateJWTFromRequest(string $encodedToken)
{
    $key = Services::getJWTSecretKey();
    $decodedToken = JWT::decode($encodedToken, new Key($key, 'HS256'));
    $userModel = new UsersModel();
    $userModel->findUserByEmailAddress($decodedToken->email);
}

function getSignedJWTForUser(string $email, $user_id, $role)
{
    $issuedAtTime = time();
    $tokenTimeToLive = getenv('JWT_TIME_TO_LIVE');
    $tokenExpiration = $issuedAtTime + $tokenTimeToLive;
    $payload = [
        'user_id' => $user_id,
        'role' => $role,
        'email' => $email,
        'iat' => $issuedAtTime,
        'exp' => $tokenExpiration,
    ];

    $jwt = JWT::encode($payload, Services::getJWTSecretKey(),'HS256');
    return $jwt;
}

function getUserInfoFromJWTToken(string $property)
{
    $request = \Config\Services::request();
    $authenticationHeader = $request->getServer('HTTP_AUTHORIZATION');
    $encodedToken = getJWTFromRequest($authenticationHeader);
    $key = Services::getJWTSecretKey();
    $decodedToken = JWT::decode($encodedToken, new Key($key, 'HS256'));

    switch ($property) {
        case 'user_id':
            return $decodedToken->user_id;
        case 'role':
            return $decodedToken->role;
        case 'user_email':
            return $decodedToken->email;
        default:
            return null;
    }
}

function getSignedJWTForUserToLogout(string $email)
{
    $issuedAtTime = time();
    $tokenExpiration = time();
    $payload = [
        'email' => $email,
        'iat' => $issuedAtTime,
        'exp' => $tokenExpiration,
    ];
    $jwt = JWT::encode($payload, Services::getJWTSecretKey(),'HS256');
    return $jwt;
}
