<?php
header("X-Robots-Tag: noindex", true);
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_set_cookie_params('54000');
session_start();
include_once ($_SERVER['DOCUMENT_ROOT'] . '/_config/functions.php');
spl_autoload_register('my_autoload');

if (isset($_COOKIE["secToken"])) {
  $secToken                             = $_COOKIE["secToken"];
} else {
  $secToken                             = security::createSecToken();
}

$login                                  = new login();
if($_SERVER["REQUEST_METHOD"]           == "POST") {
  
  $loginOK                              = $login->checkLogin($_POST);
  
  if ($loginOK                          == '0') {
    security::saveUnauthorizedLogins($_POST['username'], $_POST['password'], $_SERVER['REMOTE_ADDR']);
    echo '<meta http-equiv="refresh" content="0; URL=' . HOME_DIR_HTML . TEMPLATE_DIR . '/Auth/access-denied.php">';
  } else {
    $_SESSION[ALLOW]                    = $loginOK;
    $userData                           = $login->getUserData($loginOK);
    $_SESSION['username']               = $userData['username'];
    $_SESSION['complete_name']          = $userData['first_name'] . ' ' . $userData['last_name'];
    $_SESSION['role']                   = $userData['role'];
    security::saveAuthorizedLogins($loginOK, $_SESSION['complete_name'], $_SERVER['REMOTE_ADDR'], 0);
    
    if ($_POST['auto_login']            == 1) {
      security::setLoginCookie("sectoken", $_POST['sec_token']);
      security::setLoginCookie("identifier", $loginOK);
      security::setLoginCookie("hostIP", security::encode($_SERVER['REMOTE_ADDR']));
      $login->saveCookieLogin($loginOK, $_POST['sec_token']);
    }
    
    echo '<meta http-equiv="refresh" content="0; URL=' . HOME_DIR_HTML . '/main.php">';
  }
  
} else {
  
  $getFailedLogins                      = security::getAmountUnauthorizedLoginsByIP($_SERVER['REMOTE_ADDR']);
  
  if ($getFailedLogins                  >= MAX_FAILED_LOGINS) {
    echo '<meta http-equiv="refresh" content="0; URL=' . HOME_DIR_HTML . TEMPLATE_DIR . '/Auth/access-denied-blocked.php">';
    exit();
  }
  
  $checkAutoLogin                       = $login->checkAutoLogin($_COOKIE["identifier"], $_COOKIE["sectoken"], $_COOKIE["hostIP"]);
  if ($checkAutoLogin                   >= 1) {
    echo '<meta http-equiv="refresh" content="0; URL=Auth/chk-login-cookie.php">';
  } else {
    include($_SERVER['DOCUMENT_ROOT'] . HOME_DIR . TEMPLATE_DIR . '/Auth/login.php');
  }
}