<?php
//ini_set('display_errors', '1');
//ini_set('display_startup_errors', '1');
//error_reporting(E_ALL);

include './assets/functions.php';
include './settings/settings.php';
include './settings/config.php';
include_once './settings/translations/translations_US.php';

// Check if the user is already logged in, if yes then redirect him to welcome page
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){
	header("location: index.php");
	exit;
}

// Define variables and initialize with empty values
$username = $password = '';
$username_err = $password_err = '';

// Process submitted form data
if ($_POST['submit'] === 'Reset' && $_POST['username'] !='EMP-updater') {
  // Check if username is empty
  if(empty(trim($_POST['username']))){
    $username_err = 'Please enter username.';
  } else{
    $username = trim($_POST['username']);
  }
  // Validate credentials
  if (empty($username_err)){
    $data = json_encode(array("username" => $username, "resetkey" => ''), JSON_UNESCAPED_UNICODE);
    //Secure data
    $payload = generate_payload($data);
    //API call
    $responses = ioServer('/v1/authorization', $payload);
    //Decode Payload
    if (!empty($responses)){$responses = decode_payload($responses);}else{$responses = '400';}   
    
      if ($responses === 'NOK'){
          $usernameerr = 'Not authorized, please retry';
        } else {
        
        $username_err = $reset_message;

        header("Refresh:5; url=index.php");
      }
  }
  else {
    // Display an error for passord mismatch
    $username_err = 'Unknown error';
  }
} 

//IF POST RESETKEY & PASSWORD 
if (isset($_POST['resetkey']) && $_POST['resetkey'] !='' && $_POST['password_update']) {
  

  //check if resetkey is still valid
  $is_resetkey_valid = is_jwt_valid($_POST['resetkey']);

  if($is_resetkey_valid) {
    $resetkey = $_POST['resetkey'];

    //Clean up passwords
    $password = trim($_POST["password"]);
    $confirm_password = trim($_POST["password_update"]);

    //Check if passwords are equal
    if ($password == $confirm_password){
        if (strlen(trim($password)) < 6){
            $username_err = $reset_message3;
            $reset_id_valid = 1;      
          } 
          else {
            //UPDATE PASSWORD
            $data = json_encode(array("password" => $password, "resetkey" => $resetkey), JSON_UNESCAPED_UNICODE);
            //Secure data
            $payload = generate_payload($data);
            //API call
            $responses = ioServer('/v1/authorization', $payload);
            if (!empty($responses)){$responses = decode_payload($responses);}else{$responses = '400';}   
      
                if ($responses === 'NOK'){
                    $usernameerr = 'Not authorized, please retry';
                  } else {
                    // success
                    $username_err = 'You will be redirected';
                    //redirect to login page
                    header("Refresh:2; url=index.php");
                  }
          }
        }
    }


}

//CHECK IF RESETKEY IS SEND AND VALID
if (isset($_GET['resetkey']) && $_GET['resetkey'] !=''){

  //Check if key is valid
  $is_jwt_valid = is_jwt_valid($_GET['resetkey']);
      if($is_jwt_valid) {
        $resetkey = $_GET['resetkey'];
        $reset_id_valid = 1;
      }
      else {
  
        //Token not valid => display error and redirect to loginpage
        $username_err = $reset_message2 ;
        
        //redirect to login page
        header("Refresh:5; url=index.php");
      }
  
}
echo' 
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=UTF-8" />
<title>'.site_title.'</title>
<link rel="shortcut icon" href="'.icon_image.'" type="image/x-icon" />
<style>
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  font-family: "Open Sans", Helvetica, sans-serif;
  accent-color: '.color.';
}

body {
  background-color: #fff;
  font-family: sans-serif;
}

.logon {
  margin: 0;
  position: absolute;
  top: 40%;
  left: 50%;
  transform: translate(-50%, -50%)
}

#imagelogon {
background-image: url('.icon_image.');
background-repeat: no-repeat;
opacity: inherit;
width: 85px;
height: 150px;
margin: 0 auto;
position: relative;
top: 87px;
-webkit-filter: drop-shadow(5px 5px 5px #222);
filter: drop-shadow(5px 5px 5px #222);
}

.login-box{
    width: 350px;
    height: 320px;
    background-color:#005655;
    padding: 55px 30px;
    border-radius: 10px;
    text-align: center;
    -webkit-box-shadow: 10px 10px 5px -4px rgba(0,0,0,0.75);
    -moz-box-shadow: 10px 10px 5px -4px rgba(0,0,0,0.75);
    box-shadow: 10px 10px 5px -4px rgba(0,0,0,0.75);
  
  }
  
  .login-box h1{
    font-weight: 500;
    color: #fff;
  }
  
  .login-box input[type="text"],
  .login-box input[type="password"]{
    width: 75%;
    margin-bottom: 10px;
  }
  
  .login-box input[type="text"],
  .login-box input[type="password"]{
    border-radius: 10px;
    //background: transparent;
    border: none;
    outline: none;
    border: 2px solid #2FAC66;
    font-size: 13px;
    height: 40px;
    text-align: center;
    transition: 0.27s;
  }
  .login-box input[type="text"]:focus,
  .login-box input[type="password"]:focus{
  width: 80%;
  border-color:#6fd653;
  }
  
  .login-box input[type="submit"]{
    width: 60%;
    border: none;
    outline: none;
    background: #2FAC66;
    padding: 10px 0;
    border-radius: 10px;
    color: #ffffff;
    font-weight: 500;
    text-transform: uppercase;
    cursor: pointer;
    margin-bottom: 20px;
    position: relative;
    bottom: -12px;
    font-style: italic;
  }
  
  .login-box input[type="submit"]:hover{
    background:#6FD653;
   transition: .2s;
  }
  
  .login-box input[type="submit"]:focus{
    transform: scaleX(1.1);
  }
  
  .login-box a {
    text-decoration: none;
    font-size: 12px;
    color: #00bcd4;
  }
  
  .login-box a:hover{
    color: #6FD653;
  }

  #reset a {
    text-decoration: none;
    font-size: 10px;
    color: #00bcd4;
  }

  #reset {
  margin-top: -10px;
  }

  #message p {
    font-size: 15px;
    color: #ffffff;;
  }

</style>
</head>
<body style="background-color:#2FAC66;">
';

//Maintenance mode notification message
if (maintenance_mode){
echo'
<p style="text-align: center;">
    <small>'.maintenance_mode_notification.'</small> 
</p>';
}

//Logon view
echo'
<div class="logon">
    <div class="logon_center" style="position: static;">
      <div id="imagelogon"></div>
      <div class="login-box">   
        <small style="color:#fff;">'.site_title.'</small>  
        <h1>Customer Portal</h1>
        ';

        if (maintenance_mode)
        {
          //Maintenance mode is on => Show maintenance mode text
          echo '
          <p style="margin-top: 10%;color: white;">'.maintenance_mode_notification.'</p>
          ';
        } else {
          //Maintenance mode is off => Show login
          echo '
          <form style="margin-top:15px;" action="'.$_SERVER['PHP_SELF'].'" method="POST">
        ';
          if ($reset_id_valid != 1){
            echo'
          <input type="text" id="username" name="username" placeholder="Username" value="'; echo $username; echo '" autofocus>
          <div id="reset"><a href="index.php">Back to login</a></div>
          <input type="hidden" name="submit" value="Reset">
          <input type="submit" value="Request reset">
          ';
          } else {
            echo '
            <input type="hidden" id="resetkey" name="resetkey" value="'.$resetkey.'">
            <input type="password" id="password_new" name="password" min="8" max="20" placeholder="New Password" autofocus>
            <input type="password" id="password_update" name="password_update" min="8" max="20" placeholder="Repeat password"> 
            <input type="submit" name="submit" value="Update password">
            ';
          }

          echo'  </form>
          <div id="message"><p>'.$username_err.'<p></div>
          ';
        }
        echo '
          
      </div>
    </div>
</div>
</body>
</html>
';
?>
