<?php

include '../managers/menu.php';

if (!(UserHasPerm('user_read_perm') || UserHasPerm('user_edit_perm'))) {
  StopAndDie();
}

if (isset($_POST["func"])) {
  if (htmlspecialchars($_POST["func"]) == "table") {
    $maxperpage = intval(htmlspecialchars($_POST["perpage"]));
    $cpage = intval(htmlspecialchars($_POST["cpage"]));

    $orderby = htmlspecialchars($_POST["orderby"]);
    $name = htmlspecialchars($_POST["name"]);

    $addquery = "";
    $isfirst = true;

    if ($cpage == 0) {
      $cpage = 1;
    }
    setcookie("maxperpage", $maxperpage, time() + (86400 * 90), "/");

    if ($name != "") {
      $namelength = strlen($name);
      $newNameLength = $namelength - ($namelength % 3);
      $name = substr($name, 0, $newNameLength);

      $name = $coderclass->encode($name, 'S1TU');
      $addquery = $addquery." WHERE uname LIKE '%".$name."%'";
      $isfirst = false;
    }

    $sql = mysqli_query($conn,"SELECT COUNT(*) FROM users".$addquery);
    $count = mysqli_fetch_array($sql)[0];

    $maxpage = ceil($count / $maxperpage);
    if (!($cpage >= 1 && $cpage <= $maxpage)) {$cpage = 1;}

    $UserItems = [];
    $query = "SELECT * FROM users".$addquery;
    if ($result = $conn->query($query)) {
      while ($cuser = $result->fetch_assoc()) {

        $Current_full_name = $coderclass->decode($cuser['full_name'], 'TIT4');
        $Current_position = $coderclass->decode($cuser['position'], 'SWI2');
        $Current_perms = $coderclass->decode($cuser['perms'], 'AFDG');

        $Current_perms_List = explode(', ', $Current_perms);
        $CurrentUserPermList = array();
        for ($i=0; $i < count($Current_perms_List); $i++) {
          $cpid = $Current_perms_List[$i];
          $sql = mysqli_query($conn,"SELECT risk_factor, perm_status FROM perm_database WHERE perm_id = '$cpid'");
          $tempSQL = mysqli_fetch_array($sql);
          if ($tempSQL != null) {
            if ($tempSQL[1] != "0") {
              array_push($CurrentUserPermList, $tempSQL[0]);
            }
          }
        }

        sort($CurrentUserPermList);

        if (empty($CurrentUserPermList)) {
          array_push($CurrentUserPermList, null);
        }

        if (!($CurrentUserPermList[0] == 0 && !UserHasPerm('god_profile')) || $Current_perms == "") {
          $UserItems[] = [
            'uid' => $cuser['uid'],
            'full_name' => $Current_full_name,
            'position' => $Current_position,
            'risk_factor' => $CurrentUserPermList[0]
          ];
        }
      }
    }

    if ($orderby != "") {
      usort($UserItems, function ($a, $b) {
        global $orderby;
        return strcoll($a[$orderby], $b[$orderby]);
      });
    } else {
      usort($UserItems, function ($a, $b) {
        return strcoll($a['full_name'], $b['full_name']);
      });
    }

    $PrintableUserItems = getItemsSlice($UserItems, $cpage, $maxperpage);

    $responseStr = '';
    for ($i=0; $i < count($PrintableUserItems); $i++) {
      if ($responseStr != "") {
        $responseStr = $responseStr."%";
      }

      $responseStr = $responseStr.$PrintableUserItems[$i]['uid'].'|'.$PrintableUserItems[$i]['full_name'].'|'.$PrintableUserItems[$i]['position'].'|'.$PrintableUserItems[$i]['risk_factor'];
    }

    echo '{"result": "ok", "data": "'.$responseStr.'", "maxpage": "'.$maxpage.'", "cpage": "'.$cpage.'"}';
  } else if (htmlspecialchars($_POST["func"]) == "filter") {

    $name = array();
    $query = "SELECT uname FROM users";
    if ($result = $conn->query($query)) {
      while ($cuser = $result->fetch_assoc()) {
        array_push($name, $coderclass->decode($cuser['uname'], "S1TU"));
      }
    }

    sort($name);
    $names = "";
    for ($i=0; $i < count($name); $i++) {
      $names = $names."<option>".$name[$i]."</option>";
    }

    if (!isset($_COOKIE['maxperpage'])) {
      setcookie("maxperpage", "25", time() + (86400 * 90), "/");
      $maxperpage = "25";
    } else {
      $maxperpage = $_COOKIE['maxperpage'];
    }

    setcookie("maxperpage", strval($maxperpage), time() + (86400 * 90), "/");

    $perpageselect = "<option value='25'>25 db / oldal</option>
    <option value='50'>50 db / oldal</option>
    <option value='100'>100 db / oldal</option>
    <option value='250'>250 db / oldal</option>
    <option value='500'>500 db / oldal</option>
    <option value='1000'>1000 db / oldal</option>";
    $perpageselect = str_replace("value='".$maxperpage."'", "value='".$maxperpage."' selected", $perpageselect);

    $json = json_encode(array(
        'name' => $names,
        'perpage' => $perpageselect,
        'result' => 'ok'
    ));

    echo $json;
  } else if (htmlspecialchars($_POST["func"]) == "createuser") {
    if (UserHasPerm('user_edit_perm')) {
      $tempID = bin2hex(random_bytes(24));
      $sql = mysqli_query($conn,"INSERT INTO users(full_name, perms, status) VALUES ('564946704637584974726d6975623239564c7179462b652f61594655', '$tempID', -1)");

      $sql = mysqli_query($conn,"SELECT uid FROM users WHERE perms = '$tempID' and status = -1");
      $user = mysqli_fetch_array($sql);

      $CreatedUserID = $user[0];

      $json = json_encode(array(
          'uid' => $CreatedUserID,
          'result' => 'ok'
      ));

      $sql = mysqli_query($conn,"UPDATE users SET perms='' WHERE uid = '$CreatedUserID'");
    } else {
      $json = json_encode(array(
          'result' => 'Jogosultság megtagadva! Önnek nincsen joga felhasználót létrehozni!'
      ));
    }

    echo $json;
  } else if (htmlspecialchars($_POST["func"]) == "openuser") {
    $uid = intval(htmlspecialchars($_POST["uid"]));
    $toedit = htmlspecialchars($_POST["toedit"]);
    if ($toedit == "true") {
      $toedit = true;
    } else {
      $toedit = false;
    }

    $sql = mysqli_query($conn,"SELECT * FROM users WHERE uid = $uid");
    $user = mysqli_fetch_array($sql);

    if ($user == null) {
      echo json_encode(array('result' => 'Ilyen felhasználói azonosítóval nem létezik fiók! Próbálja újra!'));
      exit();
    }

    $PermsList = $coderclass->decode($user["perms"], 'AFDG');
    $PermListArr = explode(", ", $PermsList);
    $CurrentPermList = array();
    $CurrentPermRisk = array();
    for ($i=0; $i < count($PermListArr); $i++) {
      $cpid = $PermListArr[$i];
      $sql = mysqli_query($conn,"SELECT short_name, risk_factor, perm_status FROM perm_database WHERE perm_id = '$cpid'");
      $tempSQL = mysqli_fetch_array($sql);
      $name = $coderclass->decode($tempSQL['short_name'] ?? '', "HA98");
      array_push($CurrentPermList, $tempSQL[1]."|".$name."|".$tempSQL[2]);

      array_push($CurrentPermRisk, $tempSQL[1]);
    }
    sort($CurrentPermList);
    sort($CurrentPermRisk);

    $Perms = '';
    $PermListToJS = $PermsList;
    if ($toedit && UserHasPerm('user_edit_perm')) {
      $Perms = "<tbody>";

      $permlist = array();
      $query = "SELECT perm_category, perm_id, short_name FROM perm_database WHERE perm_status != 2";
      if ($result = $conn->query($query)) {
        while ($cperm = $result->fetch_assoc()) {

          $name = $coderclass->decode($cperm['short_name'], 'HA98');
          array_push($permlist, $cperm['perm_category']."|".$cperm['perm_id']."|".$name);

        }
      }
      sort($permlist);
      $printedCat = array();

      for ($i=0; $i < count($permlist); $i++) {
        $TempArr = explode("|", $permlist[$i]);

        if (!in_array($TempArr[0], $printedCat)) {
          array_push($printedCat, $TempArr[0]);
          $Perms .= "<tr><td style='font-weight: bold; text-align: center;' colspan='2'>".$TempArr[0]."</td></tr>";
        }

        if (str_contains($PermsList, $TempArr[1])) {
          $Perms .= "<tr style='background-color: unset;'><td>".$TempArr[2]." <span style='opacity: 0.6; font-size: 14px;'> - ".$TempArr[1]."</span></td><td><div class='checkbox-wrapper'><input type='checkbox' id='".$TempArr[1]."_checkbox' checked><label onclick='EditUserPerm(\"".$TempArr[1]."\");' for='".$TempArr[1]."_checkbox' class='saved'>Igen</label></div></td></tr>";
        } else {
          $Perms .= "<tr style='background-color: unset;'><td>".$TempArr[2]." <span style='opacity: 0.6; font-size: 14px;'> - ".$TempArr[1]."</span></td><td><div class='checkbox-wrapper'><input type='checkbox' id='".$TempArr[1]."_checkbox'><label onclick='EditUserPerm(\"".$TempArr[1]."\");' for='".$TempArr[1]."_checkbox'>Igen</label></div></td></tr>";
        }

      }

      $Perms .= "</tbody>";
    } else {
      $Perms = "<ul style='margin: 5px 0px;'>";
      for ($x=0; $x < count($CurrentPermList); $x++) {
        $templist = explode("|", $CurrentPermList[$x]);
        if ($templist[2] == "1") {
          $Perms .= '<li><span style="color: var(--panelcolor);">'.$templist[1].'</span> <span style="opacity: 0.5;">- '.$templist[0].'. oszt</span></li>';
        } else if ($templist[0] == "0") {
          $Perms .= '<li><span class="redtext">'.$templist[1].'</span> <span style="opacity: 0.5;">- '.$templist[0].'. oszt</span></li>';
        } else {
          $Perms .= '<li><span style="opacity: 0.8;">'.$templist[1].'</span> <span style="opacity: 0.5;">- '.$templist[0].'. oszt</span></li>';
        }
      }
      $Perms .= "</ul>";
    }

    $can_edit = false;
    if (UserHasPerm('user_edit_perm') && ($CurrentPermRisk[0] != 0 || $PermsList == "")) {
      $can_edit = true;
    } else if (UserHasPerm('god_profile')) {
      $can_edit = true;
    }

    if ($user != null) {
      $otp = "";
      if ($user["otphash"] != "") {
        $otp = $user["otptype"];
      }

      $json = json_encode(array(
        'uname' => $coderclass->decode($user["uname"], 'S1TU'),
        'full_name' => $coderclass->decode($user["full_name"], 'TIT4'),
        'mail' => $coderclass->decode($user["mail"], 'A7SO'),
        'position' => $coderclass->decode($user["position"], 'SWI2'),
        'note' => $coderclass->decode($user["note"], 'AH1K'),
        'perms' => $Perms,
        'PermListToJS' => $PermListToJS,
        'status' => $user["status"],
        'can_edit' => $can_edit,
        'otp' => $otp,
        'result' => 'ok'
      ));
    } else {
      $json = json_encode(array('result' => 'A felhasználó azonosítója hibás! Próbálja újra.'));
    }

    echo $json;
  } else if (htmlspecialchars($_POST["func"]) == "saveuser") {
    $uid = intval(htmlspecialchars($_POST["uid"]));
    if (htmlspecialchars($_POST["status"]) == "true") {$status = "1";} else {$status = "0";}

    if ($status == "0" && $uid == $userID) {
      echo json_encode(array('result' => 'A saját fiókodat nem tudod deaktiválni!'));
      exit();
    }

    $uname = $coderclass->encode(htmlspecialchars($_POST["uname"]), "S1TU");
    if ($uname == "") {
      echo json_encode(array('result' => 'Kötelező megadni egy felhasználó nevet!'));
      exit();
    }
    $sql = mysqli_query($conn,"SELECT uid FROM users WHERE uname = '$uname'");
    $tempSQL = mysqli_fetch_array($sql);
    if ($tempSQL != null && $tempSQL[0] != $uid) {
      echo json_encode(array('result' => 'Ilyen felhasználónévvel már létezik fiók! Adjon meg mást!'));
      exit();
    }

    $full_name = $coderclass->encode(htmlspecialchars($_POST["full_name"]), "TIT4");
    if (filter_var(htmlspecialchars($_POST["mail"]), FILTER_VALIDATE_EMAIL) !== false) {
      $mail = $coderclass->encode(htmlspecialchars($_POST["mail"]), "A7SO");
    } else if($_POST["mail"] == "") {
      $mail = "";
    } else {
      echo json_encode(array('result' => 'Az email cím nem felel meg a formai követelményeknek!'));
      exit();
    }
    $position = $coderclass->encode(htmlspecialchars($_POST["position"]), "SWI2");
    $note = $coderclass->encode(htmlspecialchars($_POST["note"]), "AH1K");
    if (!UserHasPerm('god_profile')) {
      $perms = $coderclass->encode(str_replace('god_profile', '', str_replace(', god_profile', '', htmlspecialchars($_POST["perms"]))), "AFDG");
    } else {
      $perms = $coderclass->encode(htmlspecialchars($_POST["perms"]), "AFDG");
    }

    $userpass = htmlspecialchars($_POST["upass"]);
    if (!(strlen($userpass) >= 6 && preg_match('/[a-z]/', $userpass) && preg_match('/[A-Z]/', $userpass) && preg_match('/[0-9]/', $userpass)) && $userpass != "") {
      echo json_encode(array('result' => 'A megadott jelszó nem felel meg a formai követelményeknek!'));
      exit();
    } else if($userpass != "") {
      $md5_userpass = md5($userpass);
    }

    if (UserHasPerm('user_edit_perm')) {
      if ($userpass != "") {
        $sql = mysqli_query($conn,"UPDATE users SET uname='$uname',upass='$md5_userpass',full_name='$full_name',mail='$mail',position='$position',note='$note',perms='$perms',status=$status WHERE uid = $uid");
      } else {
        $sql = mysqli_query($conn,"UPDATE users SET uname='$uname',full_name='$full_name',mail='$mail',position='$position',note='$note',perms='$perms',status=$status WHERE uid = $uid");
      }
      $json = json_encode(array('result' => 'ok'));
    } else {
      $json = json_encode(array('result' => 'Jogosultság megtagadva! Önnek nincsen joga felhasználót módosítani!'));
    }

    echo $json;
  } else if (htmlspecialchars($_POST["func"]) == "DeactivateOTP") {
    $uid = intval(htmlspecialchars($_POST["uid"]));
    if (!UserHasPerm('user_edit_perm')) {
      $json = json_encode(array('result' => 'Jogosultság megtagadva! Önnek nincsen joga felhasználót módosítani!'));
    } else if ($uid == $userID) {
      $json = json_encode(array('result' => 'A saját kétlépcsős hitelesítésének deaktiválását a fiók menupont alatt teheti meg!'));
    } else {
      $sql = mysqli_query($conn,"UPDATE users SET otphash = '' WHERE uid = '$uid'");
      $json = json_encode(array('result' => 'ok'));
    }

    echo $json;
  }

  exit();
}

?>

<!DOCTYPE html>
<html lang="hu" dir="ltr">
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="../css/panel.css">
    <title>Kezelőfelület</title>
  </head>
  <body>
    <?php echo $menuhtml;?>
    <div class="window closed" id="win">
      <div class="topbar">
        <p id="wintitle">Title</p>
        <div class="btn fullscrn" onclick="fullscrn();" id="fullscrnbtn"></div>
        <div class="btn close" onclick="closewin();"></div>
      </div>
      <div class="wapp" id="winapp"><div id="errorDIV"></div></div>
      <div class="loading" id="winloading"></div>
    </div>
    <div class="loadingBG" id="loadingBG"><img src="../img/loading.gif"></div>
    <div class="content">
      <div id="errorDIV" style="z-index: 100; top: 50px; position: fixed; width: calc(100% - 260px);"></div>

      <!-- Tartalmi rész kezdete -->

      <h1>Felhasználók</h1>

      <div style="width: 100%; min-height: 85px;">
        <div style="display: inline; float: left;">
          <p>Felhasználónév: </p>
          <input type="text" id="filter-name" placeholder="Felhasználónév..." onkeydown="if (event.keyCode == 13) {SendFilter();}" autocomplete="off" style="width: 147px; height: 17px;" list="namelist">
          <datalist id="namelist" role="listbox">
          </datalist>
        </div><div style="display: inline; float: left; padding-left: 15px;">
          <p>Oldalanként: </p>
          <select id="filter-perpage" onchange="SendFilter();"><option value="25">25 db / oldal</option></select>
        </div><div style="display: inline; float: left; padding-left: 15px;">
          <p style="color: #f5f5f5;">: </p>
          <button onclick="SendFilter();">Szűrés</button>
        </div>
        <?php if (UserHasPerm('user_edit_perm')) {echo '<div style="display: inline; float: right; padding-right: 15px;"><p style="color: #f5f5f5;">: </p><button onclick="CreateUser();">Hozzáadás</button></div>';}?>
      </div>

      <br clear="all">
        <div style="border-top: solid 1px rgb(211,220,228); width: calc(100% - 15px); height: 0px; margin-top: 15px;"></div>
      <br clear="all">

      <div style="width: 100%; margin-left: 10px; margin-top: 10px; display: inline; float: left;">
        <div class="tables" style="width: 100%">
          <table id="table">
            <thead>
              <tr style="top: 0px; position: sticky; z-index: 1;">
                <th id="table_head_name" onclick="orderby_filter('full_name');" style="cursor: pointer;">Teljes neve</th>
                <th id="table_head_position" onclick="orderby_filter('position');" style="cursor: pointer;">Beosztása</th>
                <th id="table_head_risk_factor" onclick="orderby_filter('risk_factor');" style="cursor: pointer;">Kockázati tényező</th>
                <th style="width: 100px;">Adatlap</th>
              </tr>
            </thead>

            <tbody>
            </tbody>
          </table>
        </div>
      </div>

      <br clear="all">
      <div>
        <p style="text-align: center; padding-bottom: 50px; color: #333333;"><span onclick="left();" style="cursor: pointer;"><&nbsp;&nbsp;&nbsp;&nbsp;</span><span id="cpage">0</span> / <span id="maxpage">0</span><span onclick="right();" style="cursor: pointer;">&nbsp;&nbsp;&nbsp;&nbsp;></span></p>
      </div>

      <br clear="all"><br><br>

      <!-- Tartalmi rész vége -->

    </div>
    <script src="../js/default.js" type="text/javascript"></script>
    <script type="text/javascript">
    Loading();

    var orderby = 'full_name';

    function LoadFilter() {
      const body = 'func=filter';
      get_POST_information("usereditor.php", body, function(text) {
        let response = JSON.parse(text);
        if (response.result == "ok") {
          document.getElementById('namelist').innerHTML = response.name;
          document.getElementById('filter-perpage').innerHTML = response.perpage;

          orderby_filter();
        } else {
          GenerateAlerts("error", response.result);
        }
      }, function() {
        GenerateAlerts("error", "Hálózati hiba!");
      });
    }
    function SendFilter() {
      document.getElementById('cpage').innerHTML = '1';
      LoadTable();
    }
    function LoadTable() {
      Loading();
      var name = document.getElementById("filter-name").value;
      var perpage = document.getElementById("filter-perpage").value;
      var cpage = document.getElementById("cpage").innerHTML;

      const body = 'func=table&perpage=' + perpage + '&cpage=' + cpage + '&name=' + encodeURIComponent(name).replace(/%20/g, '+') + '&orderby=' + orderby;
      get_POST_information("usereditor.php", body, function(text) {
        Loading(false);
        let response = JSON.parse(text);
        if (response.result == "ok") {
          var table = document.getElementById('table').getElementsByTagName('tbody')[0];
          table.innerHTML = "";
          document.getElementById("cpage").innerHTML = response.cpage;
          document.getElementById("maxpage").innerHTML = response.maxpage;

          var tableresponse = response.data;
          if (tableresponse != "") {
            if (tableresponse.includes("%")) {
              var tablearr = tableresponse.split("%");
            } else {
              var tablearr = [tableresponse];
            }
            for (var i = 0; i < tablearr.length; i++) {
              var datas = tablearr[i].split("|");

              var newRow = table.insertRow();
              var newCell_1 = newRow.insertCell(0);
              var newCell_2 = newRow.insertCell(1);
              var newCell_3 = newRow.insertCell(2);
              var newCell_4 = newRow.insertCell(3);
              newCell_1.innerHTML = datas[1];
              newCell_2.innerHTML = datas[2];
              if (datas[3] == "0") {
                newCell_3.innerHTML = '<span class="redtext">Kritikus</span>';
              } else if (datas[3] == "") {
                newCell_3.innerHTML = '<span style="color: #27ae60">Nincsen</span>';
              } else {
                newCell_3.innerHTML = datas[3] + '. osztály';
              }
              newCell_4.innerHTML = '<a style="cursor: pointer;" onclick="OpenUser(' + datas[0] + ')">Megnyitás</button>';
            }
          }
        } else {
          GenerateAlerts("error", response.result);
        }
      }, function() {
        Loading(false);
        GenerateAlerts("error", "Hálózati hiba!");
      });
    }

    function left() {
      var cpage = document.getElementById("cpage").innerHTML;
      if ((parseInt(cpage) - 1) >= 1) {
        document.getElementById("cpage").innerHTML = parseInt(cpage) - 1;
        LoadTable();
      }
    }
    function right() {
      var cpage = document.getElementById("cpage").innerHTML;
      var maxpage = document.getElementById("maxpage").innerHTML;
      if ((parseInt(cpage) + 1) <= parseInt(maxpage)) {
        document.getElementById("cpage").innerHTML = parseInt(cpage) + 1;
        LoadTable();
      }
    }
    function orderby_filter(by = 'full_name') {
      orderby = by;
      document.getElementById('cpage').innerHTML = '1';

      document.getElementById('table_head_name').innerHTML = "Teljes neve";
      document.getElementById('table_head_position').innerHTML = "Beosztása";
      document.getElementById('table_head_risk_factor').innerHTML = "Kockázati tényező";

      if (by == "position") {
        document.getElementById('table_head_position').innerHTML = "Beosztása <small><small style='opacity: 0.6;'>(Rendezés eszerint)</small></small>";
      } else if (by == "risk_factor") {
        document.getElementById('table_head_risk_factor').innerHTML = "Kockázati tényező <small><small style='opacity: 0.6;'>(Rendezés eszerint)</small></small>";
      } else {
        document.getElementById('table_head_name').innerHTML = "Teljes neve <small><small style='opacity: 0.6;'>(Rendezés eszerint)</small></small>";
      }

      LoadTable();
    }

    LoadFilter();

    function CreateUser() {
      Loading();
      const body = 'func=createuser';
      get_POST_information("usereditor.php", body, function(text) {
        let response = JSON.parse(text);
        if (response.result == "ok") {
          LoadFilter();
          LoadTable();
          OpenUser(response.uid);
        } else {
          Loading(false);
          GenerateAlerts("error", response.result);
        }
      }, function() {
        Loading(false);
        GenerateAlerts("error", "Hálózati hiba!");
      });
    }

    var OpenedUserPermList = '';
    var editormode = false;
    function OpenUser(uid, toedit = false) {
      Loading();
      openwin();
      wintitle.innerHTML = "Adatlap";
      const body = 'func=openuser&uid=' + uid + '&toedit=' + toedit;
      get_POST_information("usereditor.php", body, function(text) {
        winapp.innerHTML = '<div id="errorDIV"></div>';
        let response = JSON.parse(text);
        Loading(false);
        if (response.result == "ok") {

          if (response.can_edit) {
            if (toedit) {
              editormode = true;
              winapp.innerHTML += '<div style="display: inline; float: right; padding-right: 10px;"><button onclick="SaveUser(\''+uid+'\');">Mentés</button></div>';
              winapp.innerHTML += '<input type="hidden" id="winapp_uid" value="'+uid+'">';
            } else {
              winapp.innerHTML += '<div style="display: inline; float: right; padding-right: 10px;"><button onclick="OpenUser(\''+uid+'\', true);">Szerkesztés</button></div>';
            }
          }

          if (response.can_edit && toedit) {
            OpenedUserPermList = response.PermListToJS;
            wintitle.innerHTML = "Szerkesztés";

            winapp.innerHTML += '<p class="label">Felhasználó teljes neve:</p>';
            winapp.innerHTML += '<input id="winapp_full_name" type="text" class="nameInput" autocomplete="off" spellcheck="false" placeholder="Felhasználó teljes neve..." value="'+response.full_name+'"><br>';

            winapp.innerHTML += '<p class="label">Felhasználónév:</p>';
            winapp.innerHTML += '<input id="winapp_uname" type="text" class="nameInput" autocomplete="off" spellcheck="false" placeholder="Felhasználónév..." value="'+response.uname+'"><br>';

            winapp.innerHTML += '<p class="label" style="display: inline-block; margin-right: 15px;">Felhasználó jelszava:</p><div class="helpcursor"><span class="helptext" style="left: 0; right: unset;">Csak akkor töltse ki, ha módosítani szeretné!</span><span>&#9432;</span></div><br>';
            winapp.innerHTML += '<input style="margin-right: 15px;" id="winapp_upass" type="password" autocomplete="off" spellcheck="false" placeholder="Jelszó..." >';
            winapp.innerHTML += '<input id="winapp_upass2" type="password" autocomplete="off" spellcheck="false" placeholder="Jelszó ismét..." ><br><br>';

            winapp.innerHTML += '<p class="label">Felhasználó email címe:</p>';
            winapp.innerHTML += '<input id="winapp_mail" type="text" class="nameInput" autocomplete="off" spellcheck="false" placeholder="Email cím..." value="'+response.mail+'"><br>';

            winapp.innerHTML += '<p class="label">Beosztása:</p>';
            winapp.innerHTML += '<input id="winapp_position" type="text" class="nameInput" autocomplete="off" spellcheck="false" placeholder="Beosztása..." value="'+response.position+'"><br>';

            winapp.innerHTML += '<p class="label">Megjegyzés:</p>';
            winapp.innerHTML += '<textarea autocomplete="off" spellcheck="false" placeholder="Megjegyzés..." id="winapp_note" style="width: calc(100% - 16px); min-height: 60px; resize: vertical; margin-bottom: 15px;">'+response.note+'</textarea><br>';

            winapp.innerHTML += '<p class="label">Jogai:</p>';
            winapp.innerHTML += '<div style="width: 100%; margin-left: 10px; margin-top: 10px; display: inline; float: left;"><div class="tables" style="width: 100%"><table id="table"><thead><tr style="top: 0px; position: sticky; z-index: 1;"><th>Megnevezés</th><th style="width: 100px;">Hozzárendelés</th></tr></thead>'+response.perms+'</table></div></div>';

            winapp.innerHTML += '<br clear="all"><br><p class="label">Fiók állapota:</p>';
            if (response.status == "1") {winapp.innerHTML += '<div class="checkbox-wrapper"><input type="checkbox" id="winapp_status" checked><label for="winapp_status" class="saved">Aktív fiók</label></div>';
            } else {winapp.innerHTML += '<div class="checkbox-wrapper"><input type="checkbox" id="winapp_status"><label for="winapp_status">Aktív fiók</label></div>';}

          } else {
            winapp.innerHTML += '<h1 style="margin-bottom: 0px;">'+response.full_name+'</h1>';

            if (response.status == "1") {
              winapp.innerHTML += '<p style="opacity: 0.8; margin-top: 0px;">'+response.uname+' - <span style="color: var(--panelcolor);">Aktív fiók</span></p>';
            } else if (response.status == "-1") {
              winapp.innerHTML += '<p style="opacity: 0.8; margin-top: 0px;">'+response.uname+' - <span style="color: var(--panelcolor);">Átmeneti fiók</span></p>';
            } else {
              winapp.innerHTML += '<p style="opacity: 0.8; margin-top: 0px;">'+response.uname+' - <span style="color: var(--panelcolor);">Inaktív fiók</span></p>';
            }

            winapp.innerHTML += '<p class="label">Email: <span style="color: var(--panelcolor); font-weight: normal;">'+response.mail+'</span></p>';
            winapp.innerHTML += '<p class="label">Beosztása: <span style="color: var(--panelcolor); font-weight: normal;">'+response.position+'</span></p>';
            if (response.otp == "") {
              winapp.innerHTML += '<p class="label">Kétlépcsős hitelesítés: <span style="color: #c0392b; font-weight: normal;">Deaktiválva!</span></p>';
            } else if (response.can_edit) {
              winapp.innerHTML += '<p class="label">Kétlépcsős hitelesítés: <span style="color: #66A182; font-weight: normal;">Aktív!</span><span style="opacity: 0.7; font-style: italic; font-weight: normal; cursor: pointer;" onclick="DeactivateOTP('+uid+', \''+response.full_name+'\');"> - Deaktiválás</span></p>';
            } else {
              winapp.innerHTML += '<p class="label">Kétlépcsős hitelesítés: <span style="color: #66A182; font-weight: normal;">Aktív!</span></p>';
            }

            winapp.innerHTML += '<p class="label">Megjegyzés:</p><p class="label" style="color: var(--panelcolor); padding-left: 15px; border-left: 3px solid #80808052; font-weight: normal;">'+response.note+'</p>';
            winapp.innerHTML += '<p class="label">Jogai:</p>' + response.perms;
          }

        } else {
          GenerateAlerts("error", response.result);
        }
      }, function() {
        Loading(false);
        GenerateAlerts("error", "Hálózati hiba!");
      });
    }
    function EditUserPerm(permid) {
      var element = document.getElementById(permid+'_checkbox');
      var UserPermList = OpenedUserPermList.split(', ');

      if (!element.checked && !UserPermList.includes(permid)) {
        UserPermList.push(permid);
      } else if (element.checked && UserPermList.includes(permid)){
        UserPermList = UserPermList.filter(elem => elem !== permid);
      }

      OpenedUserPermList = "";
      for (var i = 0; i < UserPermList.length; i++) {
        if (OpenedUserPermList != "") {
          OpenedUserPermList += ", ";
        }
        OpenedUserPermList += UserPermList[i];
      }
    }
    function DeactivateOTP(uid, name, text = 'DefaultText') {
      if (text == "igen") {
        Loading();
        const body = 'func=DeactivateOTP&uid=' + uid;
        get_POST_information("usereditor.php", body, function(text) {
          let response = JSON.parse(text);
          Loading(false);
          if (response.result == "ok") {
            OpenUser(uid);
            GenerateAlerts("success", "Sikeresen deaktiválta a kétlépcsős hitelesítését a felhasználónak!");
          } else {
            GenerateAlerts("error", response.result);
          }
        }, function() {
          Loading(false);
          GenerateAlerts("error", "Hálózati hiba!");
        });
      } else if (text == 'DefaultText') {
        var html = `
        <p><b>Kérjük, amennyiben biztos abban, hogy deaktiválni szeretné '${name}' kétlépcsős hitelesítését, írja be, hogy 'igen'</b><br><br>Bármikor visszakapcsolhatja ezt a szolgáltatást a felhasználó a saját profiljában!</p><br>
        <input type="text" id="AlertTextInput" placeholder="Indoklás..." autocomplete="off" autocapitalize="off" spellcheck="false" autocorrect="off">
        <br clear="all"><br>
        <button id="AlertBtnNo" style="float: right; margin-left: 15px; width: 80;">Mégsem</button>
        <button id="AlertBtnYes" style="float: right; width: 60px; background: var(--panelcolor); color: #f5f5f5; border: unset;">Mentés</button>
        `;
        const overlay = CreateAlertBox('Kétlépcsős hitelesítés!', html, false);
        document.getElementById('AlertBtnYes').onclick = function () { DeactivateOTP(uid, name, (document.getElementById("AlertTextInput").value).toLowerCase()); CloseAlertBox(overlay); };
        document.getElementById('AlertBtnNo').onclick = function () { CloseAlertBox(overlay); FeedbackButtonStatus('failed', Statement_id + '_button'); };
        return;
      }
    }
    function SaveUser(uid) {
      Loading();

      var uname = document.getElementById('winapp_uname').value;
      var full_name = document.getElementById('winapp_full_name').value;
      var mail = document.getElementById('winapp_mail').value;
      var position = document.getElementById('winapp_position').value;
      var note = document.getElementById('winapp_note').value;
      var perms = OpenedUserPermList;
      var status = document.getElementById('winapp_status').checked;

      var upass = document.getElementById('winapp_upass').value;
      var upass2 = document.getElementById('winapp_upass2').value;

      if (upass != "") {
        if (upass !== upass2) {
          GenerateAlerts("error", "A két megadott jelszó nem egyezik!");
          Loading(false);
          return;
        } else if (upass.length < 6) {
          GenerateAlerts("error", "A megadott jelszó nem lehet rövidebb 6 karakternél!");
          Loading(false);
          return;
        } else if (!(/[a-z]/.test(upass) && /[A-Z]/.test(upass) && /[0-9]/.test(upass))) {
          GenerateAlerts("error", "A megadott jelszónak tartamaznia kell egy kis és nagy karaktert, és legalább egy számot!");
          Loading(false);
          return;
        }
      }

      const body = 'func=saveuser&uid=' + uid + '&status=' + status + '&uname=' + encodeURIComponent(uname).replace(/%20/g, '+') + '&full_name=' + encodeURIComponent(full_name).replace(/%20/g, '+') + '&mail=' + encodeURIComponent(mail).replace(/%20/g, '+') + '&position=' + encodeURIComponent(position).replace(/%20/g, '+') + '&note=' + encodeURIComponent(note).replace(/%20/g, '+') + '&perms=' + encodeURIComponent(perms).replace(/%20/g, '+') + '&upass=' + encodeURIComponent(upass).replace(/%20/g, '+');
      get_POST_information("usereditor.php", body, function(text) {
        let response = JSON.parse(text);
        Loading(false);
        if (response.result == "ok") {
          LoadFilter();
          LoadTable();
          OpenUser(uid);

          GenerateAlerts("success", "Sikeresen elmentve!");
        } else {
          GenerateAlerts("error", response.result);
        }
      }, function() {
        Loading(false);
        GenerateAlerts("error", "Hálózati hiba!");
      });
    }

    isCtrl = false;
    document.onkeydown=function(e){
        if(e.keyCode == 17) isCtrl=true;
        if(e.keyCode == 83 && isCtrl == true) {
          if (!win.classList.contains("closed") && editormode) {
            SaveUser(document.getElementById("winapp_uid").value);
            return false;
          }
        }
    }
    document.onkeyup = function(e) {
      if (e.keyCode == 17) isCtrl = false;
    }

    </script>
  </body>
</html>
