<?php
// required headers
//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 SITE_ROOT .'/api/v1/config/database.php';
include_once $pathRoot ."/saia/api/v1/objects/consultant.php";
 
// get database connection
$database = new Database();
$db = $database->getConnection();
 

 
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;
 
//----------------- Get JWT from Header ----------------------
$jwtAuth =  getBearerToken();

// 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(401);
        // tell the user access denied
        echo json_encode(array("error" =>"Failed to Login"));
        return;
    }
    
   
}
 
// show error message if jwt is empty
else{
    http_response_code(401);
 
    // tell the user access denied
    echo json_encode(array("error" => "Failed to Login"));
    return;
}

//======================= Get JSON Data ======================================


// get posted data
$jsonData = json_decode(file_get_contents("php://input"));

populateConsultantObject($db,$jsonData,$jwtUserId);


//====================== Populate Consultant Data ============================

function populateConsultantObject($db,$jsonData,$recId ){
    // instantiate consultant object

    $consultant = new Consultant($db);
    $consultant->id = $recId;
    $consultant->firstname = $jsonData->firstname;

    $consultant->surname =$jsonData->surname;
    $consultant->celnr =$jsonData->celnr;
    $consultant->email =$jsonData->email;
    $consultant->town =$jsonData->town;
    $consultant->province =$jsonData->province;
    $consultant->country =$jsonData->country;
    $consultant->biography =$jsonData->biography;
    
     $noPhoto="NO PHOTO";
    if(strcmp($jsonData->photo,$noPhoto)==0){
        $consultant->photo =$jsonData->photo;

    }else{
        $consultant->photo = base64_decode($jsonData->photo);
    }
    $resultsTrue = "true";
    $updateSuccess = $consultant -> updateConsultant();

    if(strcmp($updateSuccess,$resultsTrue)==0){
        http_response_code(200);
        echo json_encode(array("message" => "Success"));
           return;
    }else{
        http_response_code(200);
        echo json_encode(array( "message" =>"Error: Could not save data"));
        return;
    }
          
    /*
     $firstName = $jsonData-> firstName;
     $surname = $jsonData-> surname;
     $celnr = $jsonData-> celnr;
     $email = $jsonData-> email;
     $town = $jsonData-> town;
     $province = $jsonData-> province;
     $country = $jsonData-> country;
     $biography = $jsonData-> biography;
        $photo = $jsonData-> photo;
    */
    
    
    
}


/** 
 * 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 "";
}
?>