<?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'];
 //========== Files needed for email =====================================
include_once $pathRoot ."/saia/api/v1/sendmail/customMailSender.php";
 //  $pathDatabase ."/saia/api/v1/config/database.php";
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/appUser.php";
 
// get database connection
$database = new Database();
$db = $database->getConnection();
 
// instantiate consultant object
$user = new AppUser($db);
 
// get posted data
$dataUser = json_decode(file_get_contents("php://input"));
 
// set product property values
$data = $dataUser ->user;

$user->email = $data->email;
$email_exists = $user->emailExists();
 
// 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;

$verificationCode =0;
 
// check if email exists and if password is correct
if($email_exists && password_verify($data->password, $user->password)){
 
    $token = array(
       "iss" => $iss,
       "aud" => $aud,
       "iat" => $iat,
       "nbf" => $nbf,
       "data" => array(
           "id" => $user->id,
           "email" => $user->email
       )
    );
     
    if($user->accountVerification == "No" ){
        if(strcmp($user->verificationCode,"") == 0){
            $verificationCode = mt_rand(100000,999999);
            $user->verificationCode = strval($verificationCode);
            $user->updateVerificationCode();
        }else{
            $verificationCode = $user->verificationCode;
        }
        //===Generate Verification Code ===================
         
        
       // $user -> sendEmail($verificationCode,$user->email);
       sendEmail("",$verificationCode,$user->email,$user->name);
    }
 
    // set response code
    http_response_code(200);
 
    // generate jwt
    $jwt = JWT::encode($token, $key);
    echo json_encode(
            array(
               "responseCode"=>200,
               "jwt" => $jwt,
                "auth" => "success",
                "confirmationCode" => strval($verificationCode),
                "versionControl" => $user->versionControl
               //  "duration" => 24,
            //    "exp"=> 1586621900
            )
        );
 
}
 
// login failed
else{
 
    // set response code
    http_response_code(401);
 
    // tell the user login failed
    echo json_encode(array(
        "responseCode"=>401,
        "jwt" => "0",
        "auth" => "Not Authorized",
        "confirmationCode" => "0",
        "versionControl" => 0
        ));
}

 function sendEmail($additionalEmail,$code,$emailAddress,$name){
     $msg = " PocketStylist Email Confirmation Code: " . $code ;
      $msg = wordwrap($msg,70);
    $headers = "From: authenticator@pocketstylists.com";
    // send email
  //  $mailResults = mail($emailAddress,"PocketStylist Registration Confirmation //Code",$msg,$headers);
    $subject = "PocketStylist Registration Confirmation Code";
    $mailResults = sendCustomMail($additionalEmail,"helpdesk@saimage-apps.co.za","Helpdesk", $emailAddress ,$name,$subject, $msg,"");
    if($mailResults){
        return "Email send";
    }else{
        return $mailResults;
    }
 }


?>