<?php

include './assets/functions.php';
include './settings/settings_redirector.php';
include './settings/config_redirector.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();
}

if (session_status() == PHP_SESSION_NONE) {
  session_start();
}

//=========================================
//GET Language
//=========================================
if (isset($_GET['language']) && $_GET['language'] !=''){
  //INCLUDE LANGUAGE FILE
  $api_file_language = './settings/translations/translations_'.strtoupper($_GET['language']).'.php';
  if (file_exists($api_file_language)){   
      include $api_file_language; //Include the code
      //DEFINE LANGUAGE
      $_SESSION['country_code'] = trim($_GET['language']);
  }
  else {
      include './settings/translations/translations_US.php';
      //DEFINE LANGUAGE
      $_SESSION['country_code'] = 'US';
  }
}

if(isset($_SESSION['country_code'])){
  $api_file_language = './settings/translations/translations_'.strtoupper($_SESSION['country_code']).'.php';
  if (file_exists($api_file_language)){   
      include $api_file_language; //Include the code
  }
  else {
      include './settings/translations/translations_US.php';
  }
} 

//=========================================
//GET DOMAIN FOR CORRECT STYLING AND SETTINGS
$domain = getDomainName($_SERVER['SERVER_NAME']);
$custom_css = (file_exists(dirname(__FILE__).'/custom/'.$domain.'/style/'.$domain.'_reset.css') ? './custom/'.$domain.'/style/'.$domain.'_reset.css' : './style/admin_reset.css');
  
// 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 = $username_enter ?? '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'){
          $username_err = $password_err_1 ?? '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 = htmlspecialchars(trim($_POST["password"]), ENT_QUOTES);
    $confirm_password = htmlspecialchars(trim($_POST["password_update"]), ENT_QUOTES);

    //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'){
                    $username_err = $password_err_1 ?? 'Not authorized, please retry';
                  } else {
                    // success
                    $username_err = $redirect_succes ?? 'You will be redirected';
                    //redirect to login page
                    header("Refresh:2; url=index.php");
                  }
          }
          //$username_err = 'You will be redirected';
        }
        else {
          $username_err = $password_err_3 ?? 'Passwords do not match';
          $reset_id_valid = 1;   
      }
    } 


}

//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:3; 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" />
  <link href="'.$custom_css.'" rel="stylesheet" type="text/css">
</head>
<body>
';

        //Logon view
echo'
    <div class="login-container">
        <div class="login-form">
            <div class="logo"></div>
            <a href="#" class="register-link"></a>';
            
            if (maintenance_mode)
            {
              //Maintenance mode is on => Show maintenance mode text
              echo '
               <div class="message">
                  <p>'.maintenance_mode_text.'</p>
                </div>
              ';

            }   
            else {
            //Maintenance mode is off => Show login
            echo '
            <div class="header">
                <h1>'.($login_reset_h1 ?? 'Forgot your password').'</h1>
                <p>'.($login_reset_p ?? 'Enter your username to reset password.').'</p>
            </div>
            <form action="'.$_SERVER['PHP_SELF'].'" method="POST">';

            if ($reset_id_valid != 1){
              echo'
                <div class="input-group">
                    <input type="text" id="username" name="username" placeholder="'.($User_username ?? 'Username').'" value="'.$username.'" autofocus>
                </div>
                
                <div class="input-group">
                    <a href="index.php" class="forgot-password">'.($button_back_to_login ?? 'Back to login').'</a>
                    <input type="hidden" name="submit" value="Reset">
                </div>';
            } else {
              echo '
                <div class="input-group">
                  <input type="hidden" id="resetkey" name="resetkey" value="'.$resetkey.'">
                  <input type="password" id="password_new" name="password" min="8" max="20" placeholder="'.($password_new ?? 'New Password').'" autofocus>
                </div>
                <div class="input-group">
                  <input type="password" id="password_update" name="password_update" min="8" max="20" placeholder="'.($password_check ?? 'Repeat password').'"> 
                </div>';   
            }
            
            echo'
                <div class="remember-me">
                    <label for="remember-me"></label>
                </div>';

              if ($reset_id_valid != 1){
                echo '
                  <button type="submit" class="login-btn">'.($button_reset ?? 'Request reset').'</button>
                ';
              } else {
                echo '
                  <button type="submit" name="submit" class="login-btn">'.($button_password_update ?? 'Update password').'</button>
                ';
              }
            echo '    
            
            </form>';
            }

            if($username_err != ''){
              echo'            
                <div class="message"><p>'.$username_err.'</p></div>
              ';
            }
            //Maintenance mode notification message
            if (maintenance_mode_communication){
              echo'
              <div class="maintenance">
                <p style="text-align: center;">
                    <small>'.maintenance_mode_notification.'</small> 
                </p>
              </div>';
            }

            echo'
            <div class="trademark">'.site_title.'</div>
            <div class="language-selector">
                <span>🌐</span>
                <select id="language-selector">';
                foreach ($supportedLanguages as $language){
                  echo ' <option value="'.$language.'" '.((isset($_SESSION['country_code']) && $_SESSION['country_code'] == $language) ? 'selected' : '').'>'.$language.'</option>';
                } 
            echo'
                </select>
            </div>
        </div>

        <div class="login-visual">
           
        </div>
    </div>
</body>
 <script>
        document.getElementById(\'language-selector\').addEventListener(\'change\', function() {
            if (this.value) {
                // Get the current URL
                let currentUrl = window.location.pathname;
                
                // Append the selected value as a query parameter
                window.location.href = `${currentUrl}?language=${this.value}`;
            }
        });
    </script>
</html>';

?>
