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


 $pathRoot = $_SERVER['DOCUMENT_ROOT'];
include_once  $pathRoot ."/saia/api/v1/config/database.php";
include_once $pathRoot ."/saia/api/v1/objects/appUser.php";
include_once $pathRoot ."/saia/api/v1/objects/token.php";


//================= JWT Library ==========================================
     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;

   $jwtDta = "";
   $jwtUserId = 0;
   $jwtUserEmail = "";

//================= Verify JWT =======================================
   try{
        $jwtAuth =  getBearerToken();
        $jwt=isset($jwtAuth) ? $jwtAuth : "";
        if(strcmp($jwt, "") == 0){
             http_response_code(401);
              echo json_encode(array("responseCode"=>401));
            return;
        }
    }catch (Exception $e){
         http_response_code(401);
          echo json_encode(array("responseCode"=>401));
         return;

    }
	
	 //============== Decode JWT =============================
    try{
        $decoded = JWT::decode($jwt, $key, array('HS256'));
    }catch(Exception $e){
        http_response_code(401);
         echo json_encode(array("responseCode"=>401));
        $jwtDta = "";
        $jwtUserId = 0;
        $jwtUserEmail = "";
        $saveResults = "error: Verification" ;
        return;
    }
	
//==================== Get JSON data ========================================
	$data = json_decode(file_get_contents("php://input"));
	$action = $data->action;
	
//==================== Check if valid Action ==============================
	if(strcmp($action, "") == 0){
    http_response_code(400);
    echo json_encode(array("responseCode"=>400));
    return ;
}
//======================= get Database connection =====================================
	$database = new Database();
	$db = $database->getConnection();
//======================= get action =====================================

	switch ($action){
		
		case "activate":
		    $tokenObject = new Token($db);
			tokenValidation($data,$db, $decoded,$tokenObject);
		break;
	}
	
//======================= Activate Token ===================================	

function tokenValidation($jsonData,$database,$decoded,$tokenObject){
	
	$jwtDta = $decoded->data;
    $jwtUserId = $jwtDta -> id;
    $jwtUserEmail = $jwtDta -> email;
	$user = new AppUser($database);

    if(!$user->verifyJwtIdEmail($jwtUserEmail,$jwtUserId)){
        http_response_code(401);
        echo json_encode(array("responseCode"=>401));
        return;
    }

    $tokenObject->phoneOs = $jsonData ->phoneOs;
    $tokenObject->phoneModel = $jsonData ->phoneModel;
    $tokenObject->activationEmail = $jsonData ->email;
    $tokenObject->activationIpAddress = $jsonData ->ipAddress;
    $tokenObject->activationCountry = $jsonData ->country;
    
    $tokenObject->tokenValue = $jsonData ->tokenValue;
    $tokenObject->fkeyAppUser = $jwtUserId;
    $sucessUpdate = false;
        
    if($tokenObject->isTokenValid()){
		$tokenType = $tokenObject-> tokenType;
        $sucessUpdate = $tokenObject->updateValidToken();
        tokenFeedback($sucessUpdate,$tokenType,"");
		/*
		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)
            ));
			*/
            
    }else{
		tokenFeedback($sucessUpdate,"",$tokenObject->validationMessage);
		
	}
       
    
}

function tokenFeedback($sucessUpdate,$tokenType,$error){
	
	 if($sucessUpdate){
         // set response code
            http_response_code(200);
            echo json_encode(array(
                "responseCode"=>200,
                "result" => "ok",
                "tokenType" => $tokenType,
				"message" => $error,
				"edit" => 1
            ));
            return;
        
        }else{
            
             // set response code
            http_response_code(200);
             echo json_encode(array(
                 "responseCode"=>200,
                "result" => "error",
                "tokenType" => $tokenType,
				"message" => $error,
				"edit" => 0
                
            ));
            return;
            
        }
	
}

	

/** 
 * ================   Get header Authorizationn  =========================
 * */
 
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 "";
}
 

?>