<?php

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

if (!UserHasPerm('perm_read')) {
  StopAndDie();
}

if (isset($_POST['func'])) {
  if (htmlspecialchars($_POST["func"]) == "savestatus") {
    $perm_id = htmlspecialchars($_POST["permid"]);
    $status = intval(htmlspecialchars($_POST["status"]));

    if ($perm_id == "perm_read") {
      $json = json_encode(array(
        'result' => 'A "perm_read" jogosultság nem állítható!'
      ));

      echo $json;
    } else if ($status == 1 || $status == 0) {
      $sql = mysqli_query($conn,"UPDATE perm_database SET perm_status=$status WHERE perm_id = '$perm_id'");

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

      echo $json;
    } else {
      $json = json_encode(array(
        'result' => 'Hibás státusz kód! Próbálja újra!'
      ));

      echo $json;
    }
  }

  exit();
}

$permlist = array();

$query = "SELECT * FROM perm_database WHERE perm_status != 2  ORDER BY perm_category ASC";
if ($result = $conn->query($query)) {
  while ($cperm = $result->fetch_assoc()) {

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

  }
}

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

$printingTable = '';

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

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

  if ($TempArr[3] != "perm_read") {
    $status = "<select style='background: transparent; width: -webkit-fill-available; font-size: 14px;' onchange='SaveStatus(\"".$TempArr[3]."\", this.value);'>";
    if ($TempArr[4] == "1") {
      $status .= "<option value='0'>Inaktív</option>
      <option value='1' selected>Aktív</option>";
    } else {
      $status .= "<option value='0' selected>Inaktív</option>
      <option value='1'>Aktív</option>";
    }
    $status .= "/select>";
  } else {
    $status = "<span style='color: var(--panelcolor); font-size: 14px; margin-left: 12px;'>Aktív</span>";
  }

  $printingTable .= "<tr><td>".$TempArr[5]." <span style='opacity: 0.6; font-size: 14px;'> - ".$TempArr[3]."</span></td><td>".$TempArr[2]."</td><td style='padding: 0px;'>".$status."</td><td>".$TempArr[1].". oszály</td></tr>";

}

?>

<!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>Jogosultságok listája</h1>
      <?php

      if (UserHasPerm('god_profile') && $userID == 1) {
        echo '<a href="#" onclick="OpenEditor()" style="position: absolute; right: 30px; top: 80px;">Jog hozzáadása</a>';
      }

      ?>

      <div style="width: 100%; margin-left: 10px; margin-top: 10px; display: inline; float: left;">
        <div class="tables" style="width: 100%">
          <table id="drugstable">
            <thead>
              <tr style="top: 0px; position: sticky; z-index: 1;">
                <th>Megnevezés</th>
                <th>Leírás</th>
                <th>Állapot</th>
                <th>Kockázati tényező</th>
              </tr>
            </thead>

            <tbody>

              <?php echo $printingTable;?>

            </tbody>
          </table>
        </div>
      </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">

    function SaveStatus(perm_id, status) {
      Loading();

      const body = 'func=savestatus&permid='+ encodeURIComponent(perm_id).replace(/%20/g, '+') + '&status=' + status;
      get_POST_information("permlist.php", body, function(text) {
        let response = JSON.parse(text);
        Loading(false);
        if (response.result == "ok") {
          GenerateAlerts("success", "Sikeresen módosította a jog státuszát!");
        } else {
          GenerateAlerts("error", response.result);
        }
      }, function() {
        Loading(false);
        GenerateAlerts("error", "Hálózati hiba!");
      });

    }

    function OpenEditor() {
      const popup = window.open('./addperm', 'Jog hozzáadása', 'width=610,height=860');

      const timer = setInterval(() => {
        if (popup == null) {
          clearInterval(timer);
          console.log("Nem lehet elérni a megnyílt oldalt");
        } else if (popup.closed) {
          clearInterval(timer);
          location.reload();
        }
      }, 500);

    }

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