<?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/adminUser.php";
    include_once $pathRoot ."/saia/api/v1/ps_office/user_data.php";
    include_once $pathRoot ."/saia/api/v1/objects/token.php";
	
	  //========== Files needed for email =====================================
    include_once $pathRoot ."/saia/api/v1/sendmail/customMailSender.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 = "";
   
    //========================================================================
	$data = json_decode(file_get_contents("php://input"));
	if(is_null($data)){
		http_response_code(400);
         echo json_encode(array("responseCode"=>400,"results"=>"no valid action"));
        return ;
	}
	
	try{
		$action = $data->action;
	}catch(Exception $e){
		http_response_code(400);
         echo json_encode(array("responseCode"=>400,"results"=>"no valid action"));
        return ;
    }
	
	
	$emptyData= "";
    if(strcmp($action, $emptyData) == 0){
        http_response_code(400);
         echo json_encode(array("responseCode"=>400,"results"=>"no valid action"));
        return ;
    }
     
    // get database connection
    $database = new Database();
    $db = $database->getConnection();
	
	if(strcmp($action, "userlist") == 0)
    {
        $adminUser = new AdminUser($db);
		$jwtAuth = verifyJWT($db,$key,$adminUser);
		if(strcmp($jwtAuth,"unauthorized")==0){
			http_response_code(401);
                 echo json_encode(array("responseCode"=>401));
                return;
			
		}

		$userData = new UserData($db);
		$listUserData = $userData->getAppUserList();
		echo $listUserData;
	}
	
	if(strcmp($action, "resetPassword") == 0)
	{
	     $adminUser = new AdminUser($db);
	    $jwtAuth = verifyJWT($db,$key,$adminUser);
		if(strcmp($jwtAuth,"unauthorized")==0){
			http_response_code(401);
                 echo json_encode(array("responseCode"=>401));
                return;
			
		}
		$userId = $data->id;
		$userEmail = $data->email;
		$userPassword = $data->password;
		$userData = new UserData($db);
		$results = $userData->resetUserPassword($userId,$userEmail,$userPassword,$adminUser->email);
		if(strcmp($results,"ok") ==0){
		 http_response_code(200);
         echo json_encode(array("responseCode"=>200,"results"=>"saved"));
         return;
		}
		http_response_code(200);
         echo json_encode(array("responseCode"=>200,"results"=>"error"));
         return;
		
	}
	
	if(strcmp($action, "verifyUser") == 0)
	{
	     $adminUser = new AdminUser($db);
	    $jwtAuth = verifyJWT($db,$key,$adminUser);
		if(strcmp($jwtAuth,"unauthorized")==0){
			http_response_code(401);
                 echo json_encode(array("responseCode"=>401));
                return;
			
		}
		$userId = $data->id;
		$userEmail = $data->email;
		$userData = new UserData($db);
		$results = $userData->verifyUser($userId,$userEmail);
		if(strcmp($results,"ok") ==0){
		 http_response_code(200);
         echo json_encode(array("responseCode"=>200,"results"=>"saved"));
         return;
		}
		http_response_code(200);
         echo json_encode(array("responseCode"=>200,"results"=>"error"));
         return;
		
	}
	
	function verifyJWT($db,$key,$adminUser){
		  //----------------- Get JWT from Header ----------------------
		   $emptyString = "";
        try{
            $jwtAuth =  getBearerToken();
            $jwt=isset($jwtAuth) ? $jwtAuth : "";
           
            if(strcmp($jwt, $emptyString) == 0){
                
                return "unauthorized";
            }
        }catch (Exception $e){
             return "unauthorized";
    
        }

        if(strcmp($jwt, $emptyString) != 0){
    

            try {
            // decode jwt
            $decoded = JWT::decode($jwt, $key, array('HS256'));
            // show user details
               $jwtDta = $decoded->data;
               $jwtUserId = $jwtDta -> id;
               $jwtUserEmail = $jwtDta -> email;
    
               //$adminUser = new AdminUser($db);

               $adminUser->email =$jwtUserEmail;
               $adminUser->id =  $jwtUserId;
               $callResponse = array();      
               //echo $jwtUserEmail . " ". $jwtUserId;
    
               if($adminUser->verifyJwtIdEmail($jwtUserEmail,$jwtUserId)){
                   
                   return "authorized";
               }
              
               return "unauthorized";
    
    
             }catch (Exception $e){
                return "unauthorized";
                 
            }
        }
		
	}
	
	/** 
 * 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 "";
}
