<?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/config/core.php";
include_once $pathRoot ."/saia/api/v1/objects/appUser.php";


// 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;

//========== Files needed for email =====================================
include_once $pathRoot ."/saia/api/v1/sendmail/customMailSender.php";

 
// get database connection
$database = new Database();
$db = $database->getConnection();
//==================Generate Verification Code =================================
 $verificationCode = mt_rand(100000,999999);


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

// instantiate AppUser object
$user = new AppUser($db);
// set product property values
$user->name = $data->name;
$user->email = $data->email;
$user->password = $data->password;
$user->celnr = $data->celnr;
 try{
    $country = $data->country;
 }catch(Exception $e){
    $country = "";
 }
if(is_null( $country)){
     $country = "";
}
$user->country = $country;

 $noData = "";
if(strcmp($user->verificationCode,$noData) == 0){
    $newCode = mt_rand(100000,999999);
    $verificationCode = strval($newCode);
    $user->verificationCode = $verificationCode;
}

$emailAddress =  $data->email;

    if(
        !empty($user->name) &&
        !empty($user->email) &&
        !empty($user->password) )
    {
       
        $emailExists = $user->emailExists();
        if($emailExists == true){
            http_response_code(409);
            echo json_encode(array("responseCode"=>409,"result" => "account exists","emailSend"=>"no","confirmationCode"=> "", "jwt"=> "0"));
            exit;
        }
    
        $results = $user->registerUser();

        if(strcmp($results,"true") ==0){
             http_response_code(200);
                
            $emailStatus = sendEmail("",$verificationCode,$emailAddress,$user->name);
            $jwt = generateJwt($iss,$aud, $iat,$nbf,$key,$user);
            if(strcmp($emailStatus , "Email send") == 0)
            {
                
                 echo json_encode(array("responseCode"=>200,"result" => "user registered","emailSend"=>"yes","confirmationCode"=>$verificationCode,"jwt"=> $jwt)); 
                
            }else{
                 echo json_encode(array("responseCode"=>200,"result" =>"user registered","emailSend"=>"no ".$emailStatus,"confirmationCode"=>$verificationCode,"jwt"=> $jwt)); 
            } 
        }else{
             http_response_code(400);
     
        // display message: unable to create user
           echo json_encode(array("responseCode"=>400,"result" => "user not registered","emailSend"=>"no","confirmationCode"=>"0","jwt"=> "" ));
        }
            
           
     
        // display message: AppUser was created
      
    
        
                                
    }
 
// message if unable to create consultant
    else{
     
        // set response code
        http_response_code(400);
        // display message: unable to create user
         echo json_encode(array("responseCode"=>400,"result" => "data not valid","email send"=>"no","confirmationCode"=>"0","jwt"=> "" ));
    }


//==============================================================================

 function generateJwt( $iss,$aud, $iat,$nbf,$key,$user){
     
    $token = array(
       "iss" => $iss,
       "aud" => $aud,
       "iat" => $iat,
       "nbf" => $nbf,
       "data" => array(
           "id" => $user->id,
           "email" => $user->email
       )
    );
     $jwt = JWT::encode($token, $key);
     json_encode(
            array(
               // "id" => $user->id,
               // "user"=> $user->email,
               "jwt" => $jwt,
                "auth" => "success"
               //  "duration" => 24,
            //    "exp"=> 1586621900
            )
    );
    
    return $jwt;
 }
 
 function sendEmail($additionalEmail,$code,$emailAddress,$name){
     $msg = "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;
    }
 }
 
/*
 function sendEmail($code,$emailAddress){
     $msg = "Confirmation Code: " . $code;
      $msg = wordwrap($msg,70);
    $headers = "From: authenticator@pocketstylists.com";
    // send email
    $mailResults = mail($emailAddress,"PocketStylist Registration Confirmation Code",$msg,$headers);
    if($mailResults){
        return "Email send";
    }else{
        return "Could not send";
    }
 }
 */
 
 function updateAppUser($verificationCode){
     // the message


    // use wordwrap() if lines are longer than 70 characters
    $msg = wordwrap($msg,70);
    $headers = "From: authenticator@pocketstylists.com";
    // send email
    $mailResults = mail("emile@ideas4apps.co.za","My subject",$msg,$headers);
    if($mailResults){
        echo "Email send";
    }else{
        echo "Could not send";
    }
     
 }
?> 