<?php
header("Access-Control-Allow-Origin: http://localhost/rest-api-authentication-example/");
//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");

// files needed to connect to database
 $pathRoot = $_SERVER['DOCUMENT_ROOT'];
include_once  $pathRoot ."/saia/api/v1/config/database.php";
 include_once  $pathRoot ."/saia/api/v1/objects/token.php";
// required to decode jwt
include_once $pathRoot ."/saia/api/v1/config/core.php";

include_once $pathRoot ."/saia/api/v1/libs/php-jwt-master/src/BeforeValidException.php";
include_once $pathRoot ."/saia/api/v1/libs/php-jwt-master/src/ExpiredException.php";
include_once $pathRoot ."/saia/api/v1/libs/php-jwt-master/src/SignatureInvalidException.php";
include_once $pathRoot ."/saia/api/v1/libs/php-jwt-master/src/JWT.php";
use \Firebase\JWT\JWT;


//$jwt = getBearerToken();

//echo $jwt;
$jsonData = json_decode(file_get_contents("php://input"));
$sucessUpdate = false;

//----------------- Get JWT from Header ----------------------
$jwtAuth =  getBearerToken();

//echo $jwtAuth;
//echo "1";
// get jwt
$jwt=isset($jwtAuth) ? $jwtAuth : "";
// if jwt is not empty
if($jwt){
 
    // if decode succeed, show user details
    try {
        // decode jwt
        $decoded = JWT::decode($jwt, $key, array('HS256'));

        // show user details
        $jwtDta = $decoded->data;
        $jwtUserId = $jwtDta -> id;

    }catch (Exception $e){
         http_response_code(200);
        echo json_encode(array(
            "status" => "Access denied.",
            "error" => $e->getMessage()
        ));
    }
    
   
}
 
// show error message if jwt is empty
else{
    http_response_code(401);
 
    // tell the user access denied
    echo json_encode(array( "status" => "Access denied."));
    return;
}
//================= check if user is authorized================================
 $user_id =  $jsonData->user_id;
 if($jwtUserId == $user_id ){
    tokenValidation($db, $jsonData);

 }
 else{
    echo json_encode(array("error" => "Failed to Login"));
    return;
}


//==============================================================================

function tokenValidation($jwtUserId,$jsonData){
    
    
      $database = new Database();
        $db = $database->getConnection();
        // instantiate token object
        $tokenObject = new Token($db);
        $tokenObject->token = $jsonData ->token_val;
        $tokenObject->fkeyAppUser = $jsonData ->user_id;
        
        if($tokenObject->isTokenValid()){
             $sucessUpdate = $tokenObject->updateValidToken();
             echo $sucessUpdate;
            
        }
        if($sucessUpdate){
         // set response code
            http_response_code(200);
            echo json_encode(array(
                "status" => "ok",
                "token" => array("token"=>$tokenObject->token,"duration"=>$tokenObject->duration,"activated_on"=>$tokenObject->activatedOn,"expiry_date"=>$tokenObject->expiryDate,"id"=>$tokenObject->id,"created_at"=>$tokenObject->createdAt,"updated_at"=>$tokenObject->updatedAt,"user_id"=>$tokenObject->fkeyAppUser)
            ));
            return;
        
        }else{
            
             // set response code
            http_response_code(200);
             echo json_encode(array(
                "status" => "err",
                "msg" => "Invalid Token Value",
                
            ));
            return;
            
        }
    
}



 

/** 
 * Get header Authorization
 * */
function getAuthorizationHeader(){
        $headers = null;
        if (isset($_SERVER['Authorization'])) {
            $headers = trim($_SERVER["Authorization"]);
        }
        else if (isset($_SERVER['HTTP_AUTHORIZATION'])) { //Nginx or fast CGI
            $headers = trim($_SERVER["HTTP_AUTHORIZATION"]);
        } elseif (function_exists('apache_request_headers')) {
            $requestHeaders = apache_request_headers();
            // Server-side fix for bug in old Android versions (a nice side-effect of this fix means we don't care about capitalization for Authorization)
            $requestHeaders = array_combine(array_map('ucwords', array_keys($requestHeaders)), array_values($requestHeaders));
            //print_r($requestHeaders);
            if (isset($requestHeaders['Authorization'])) {
                $headers = trim($requestHeaders['Authorization']);
            }
        }
       // $headers = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9leGFtcGxlLm9yZyIsImF1ZCI6Imh0dHA6XC9cL2V4YW1wbGUuY29tIiwiaWF0IjoxMzU2OTk5NTI0LCJuYmYiOjEzNTcwMDAwMDAsImRhdGEiOnsiaWQiOiIzIiwiZW1haWwiOiJlbWlsZUBpZGVhczRhcHBzLmNvLnphIn19.PsusjAZ10bdOtOuB0CCTv9O3D68-v_YRaCC48oYh_EI";
        return $headers;
    }
/**
 * get access token from header
 * */
function getBearerToken() {
    $headers = getAuthorizationHeader();
    // HEADER: Get the access token from the header
    if (!empty($headers)) {
        if (preg_match('/Bearer\s(\S+)/', $headers, $matches)) {
            return $matches[1];
        }
    }
    return "";
}
?>