<?php
// required headers
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
include_once '../config/database.php';
include_once '../objects/consultant.php';
 
// get database connection
$database = new Database();
$db = $database->getConnection();
 
// instantiate consultant object
$consultant = new Consultant($db);
 
// get posted data
$data = json_decode(file_get_contents("php://input"));
 
// set product property values
$consultant->email = $data->email;
$email_exists = $consultant->emailExists();
$pathRoot = $_SERVER['DOCUMENT_ROOT'];
 
// generate json web token
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;
 
// check if email exists and if password is correct
if($email_exists && password_verify($data->password, $consultant->password)){
 
    $token = array(
       "iss" => $iss,
       "aud" => $aud,
       "iat" => $iat,
       "nbf" => $nbf,
       "data" => array(
           "id" => $consultant->id,
           "firstname" => $consultant->firstname,
           "surname" => $consultant->surname,
           "email" => $consultant->email
       )
    );
 
    // set response code
    http_response_code(200);
 
    // generate jwt
    $jwt = JWT::encode($token, $key);
    echo json_encode(
            array(
                "id" => $consultant->id,
                "firstname" => $consultant->firstname,
                "surname" => $consultant->surname,
                "celnr" => $consultant->celnr,
                "email" => $consultant->email,
                "town" => $consultant->town,
                "province" => $consultant->province,
                "country" => $consultant->country,
                "biography" => $consultant->biography,
           
                "authToken" => $jwt
            )
        );
 
}
 
// login failed
else{
 
    // set response code
    http_response_code(401);
 
    // tell the user login failed
    //echo json_encode(array("message" => "Login failed."));
    echo json_encode(array("message" => $data->email));
}
?>