<?php
setlocale(LC_COLLATE, 'hu_HU.UTF-8');
date_default_timezone_set('Europe/Budapest');
header('X-Frame-Options: SAMEORIGIN');

include 'code.php';
include 'dbconn.php';
include 'log.php';

$coderclass = new coder;
$loggerclass = new Logger;

$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://";
$host = $_SERVER['HTTP_HOST'];
$currentUrl = $protocol . $host;
$currentAdvancedUrl = str_replace('.php', '', $currentUrl.$_SERVER['REQUEST_URI']);

ini_set('session.cookie_httponly', 1);
ini_set('session.cookie_secure', 1);
session_set_cookie_params([
    'lifetime' => 0,
    'path' => '/',
    'domain' => $_SERVER['HTTP_HOST'],
    'secure' => true,
    'httponly' => true,
    'samesite' => 'Strict'
]);
session_start();

$auth_cookie = htmlspecialchars($_COOKIE['auth_token'] ?? '');
$userID = $coderclass->decode($auth_cookie, $coderclass->today_private_key());

$userName = "User";

$sql = mysqli_query($conn,"SELECT full_name, perms, status FROM users WHERE uid = '$userID'");
$userSQL = mysqli_fetch_array($sql);

if (!UserHasPerm()) {
  die('|$6b4ea69e17243db95f7b46c384d40370$|!<script type="text/javascript">window.location="'.$currentUrl.'/managers/logout.php";</script>');
} else {
  setcookie("auth_token", $_COOKIE['auth_token'], [ 'expires' => time() + 3600, 'path' => "/", 'domain' => $_SERVER['SERVER_NAME'], 'secure' => true, 'httponly' => true, 'samesite' => 'Strict' ]);
  setcookie('auth_timer', time() + 3600, ['expires' => time() + 3610, 'path' => '/', 'domain' => $_SERVER['SERVER_NAME'],'secure' => true,'httponly' => false, 'samesite' => 'Strict']);
  $userName = $coderclass->decode($userSQL[0], "TIT4");

  $loggerclass->init($userID);
}

setcookie("lastURL", urlencode($currentAdvancedUrl), time() + 3600, "/");

$userPermsList = $coderclass->decode($userSQL[1], 'AFDG');
function UserHasPerm($the_perm = "log_in") {
  global $userSQL, $userPermsList, $conn;
  $the_perm = htmlspecialchars($the_perm);

  if ($the_perm == "log_in") {
    if ($userSQL == null) {
      return false;
    } else if ($userSQL[2] == 1) {
      return true;
    }
  } else {

    if (str_contains($userPermsList, 'god_profile')) {
      $permsql = mysqli_query($conn, "SELECT perm_status FROM perm_database WHERE perm_id = 'god_profile'");
      $permsqlfetch = mysqli_fetch_array($permsql);

      if ($permsqlfetch == null) {
        return false;
      } else if ($permsqlfetch[0] != 2) {

      } else {
        return true;
      }
    }

    if (str_contains($userPermsList, $the_perm)) {
      $permsql = mysqli_query($conn, "SELECT perm_status FROM perm_database WHERE perm_id = '$the_perm'");
      $permsqlfetch = mysqli_fetch_array($permsql);

      if ($permsqlfetch == null) {
        return false;
      } else if ($permsqlfetch[0] == 0) {
        return false;
      } else {
        return true;
      }
    }


  }

  return false;
}

?>
