<?php   

ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);  

include './assets/functions.php';
include './settings/settings_redirector.php';
include './settings/config_redirector.php';

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.'_login.css') ? './custom/'.$domain.'/style/'.$domain.'_login.css' : './style/admin_login.css');
  
// 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 = '';
$retry = 0;

// Process submitted form data
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

  // Check if username is empty
  if(empty(trim($_POST['username']))){
    $username_err = $username_enter ?? 'Please enter username' ;
  } else{
    $username = trim($_POST['username']);
  }

  // Check if password is empty
  if(empty(trim($_POST['password']))){
    $password_err = $password_enter ?? 'Please enter your password';
  } else{
    $password = trim($_POST['password']);
  }

  // Validate credentials
  if (empty($username_err) && empty($password_err) && $retry < 3) {
    $data = json_encode(array("username" => $username, "password" => $password), 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'){
          $retry++;
          $password_err = $password_err_1 ?? 'Not authorized, please retry';
        } elseif ($responses == '1'){
          $password_err = $password_err_2 ?? 'Too many login attempts. User blocked, please contact your administrator';
        } else {
        // Start a new session
        session_start();
      
        // Store data in sessions
        $_SESSION['loggedin'] = true;
        $_SESSION['id'] = $responses->id;
        $_SESSION['username'] = $responses->username;
        $_SESSION['email'] = $responses->email;
        $_SESSION['salesID'] = $responses->salesID;
        $_SESSION['partnerhierarchy'] = $responses->partnerhierarchy; //clean;
        $_SESSION['permission'] = $responses->permission;
        $_SESSION['profile_name'] = $responses->profile_name;
        $_SESSION['profile'] = $responses->profile;
        $_SESSION['userkey'] = $responses->userkey;
        $_SESSION['language'] = $responses->language;
        $_SESSION['token'] = $responses->token;

        $language_user = trim($responses->language) ?? 'US';
        if($responses->profile == 'firmwaretool,products_software,application'){
          header('location: index.php?page=firmwaretool');
          exit();

        } else {
          header('location: index.php?language='.$language_user.'');
          exit();
        }
      }
  }
  else {
    // Display an error for passord mismatch
    $password_err = $password_err_3 ?? 'Not authorized';
  }
} 
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_h1 ?? 'Login to your account').'</h1>
                <p>'.($login_p ?? 'Enter your details to login.').'</p>
            </div>
            <form action="'.$_SERVER['PHP_SELF'].'" method="POST">
                <div class="input-group">
                    <input type="text" id="username" name="username" placeholder="'.($User_username ?? 'Username').'" value="'.$username.'" autofocus>
                </div>
                
                <div class="input-group">
                    <input type="password" id="password" name="password" placeholder="'.($account_create_password ?? 'Password').'" value="'.$password.'">
                    <a href="reset.php'.(isset($_GET['language'])? '?language='.$_GET['language'].'' : '').'" class="forgot-password">'.($button2 ?? 'Forgot password?').'</a>
                </div>
            
                <div class="remember-me">
                    <label for="remember-me"></label>
                </div>

                <button type="submit" class="login-btn">'.($button1 ?? 'Login').'</button>
            </form>';
            }

            if($password_err !='' || $username_err != ''){
              echo'            
                <div class="message"><p>'.$username_err.''.$password_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>';

?>