<?php

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

$IsGlobalError = false;
$GlobalErrorText = "";

if (isset($_SESSION['error_message']) && $_SESSION['error_message'] != "") {
  $IsGlobalError = true;
  $GlobalErrorText = $_SESSION['error_message'];
  $_SESSION['error_message'] = '';
}

$sql = mysqli_query($conn,"SELECT otptype, otphash FROM users WHERE uid = '$userID'");
$user2Fa = mysqli_fetch_array($sql);

$Need2FAActivation = false;

$totpKey = '';
$totpQRCode = '';
$anticsrfid = '';

if (($user2Fa['otptype'] == 2 || $user2Fa['otptype'] == 3) && $user2Fa['otphash'] == "") {
  $Need2FAActivation = true;

  $totp = new TOTP();
  $totpKey = $totp->generateKey();
  $totpQRCode = 'otpauth://totp/Szaturnusz?secret='.$totpKey.'&issuer=saturn&algorithm=SHA1&digits=6&period=30';


  $anticsrfid = bin2hex(random_bytes(24));
  $_SESSION["anticsrfid"] = $anticsrfid;

  $menuhtml = str_replace('<script src="../js/bug_report.js"></script>', '', $menuhtml);
}

?>

<!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 -->

      <!--
      <div class="box">
        <p class="strong">Tervezett leállás!</p>
        <p><span style="color: var(--panelcolor);">2026.01.13. 22:00</span>-tól tervezett leállás várható rendszerkarbantartás miatt!</p>
      </div>
      -->

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

    </div>
    <script src="../js/default.js" type="text/javascript"></script>
    <?php if ($Need2FAActivation) {echo '<script src="../js/qrcode.js" type="text/javascript"></script>';}?>
    <script type="text/javascript">

    var GlobalAntiCSRFId = "<?php echo $anticsrfid;?>";

    if (<?php if ($IsGlobalError) {echo 'true';} else {echo 'false';}?>) {
      GenerateAlerts('error', '<?php echo $GlobalErrorText;?>', false);
    }

    if (<?php if ($Need2FAActivation) {echo 'true';} else {echo 'false';}?>) {

      html = `<?php

      echo '<p><b>Fiók aktiválás!</b></p><p>Scannelje be a QR kódot hitelesítő alkalmazásában,<br><i style="opacity: 0.8;">(pl: Google Authenticator, Authy, Microsoft Authenticator)</i><br>majd írja be a kapott kódot, hogy elkezdhesse használni fiókját.</p><br>';
      echo '<div style="display: flex; justify-content: center; align-items: center; height: 160px;"><div id="qrcode" style="width: 160px; height: 160px;"></div></div>';
      echo '<p style="text-align: center;">'.$totpKey.'</p>';
      echo '<input style="margin: auto;" type="text" id="otc" class="otc" maxlength="6" autocomplete="off">
      <div style="display: flex; justify-content: center; align-items: center; margin-top: 15px;">
      <input type="password" id="pass" placeholder="Jelenlegi jelszó..." autocomplete="off">
      <input type="hidden" id="otckey" value="'.$totpKey.'">
      <button style="margin-left: 15px;" onclick="Activate2fa();">Aktiválás</button></div>';

      ?>`;

      CreateAlertBox("Kétlépcsős hitelesítés", html, false);
    }

    function Activate2fa() {
      Loading();

      var otc = document.getElementById("otc").value;
      var otckey = document.getElementById("otckey").value;
      var pass = document.getElementById("pass").value;

      const body = 'f=Activate2fa&otc=' + encodeURIComponent(otc).replace(/%20/g, '+') + '&otckey=' + encodeURIComponent(otckey).replace(/%20/g, '+') + '&pass=' + encodeURIComponent(pass).replace(/%20/g, '+') + '&anticsrfid=' + GlobalAntiCSRFId;
      get_POST_information("profile.php", body, function(text) {
        Loading(false);

        if (text == "ok") {
          html = `<p><b>Sikeresen aktiválta a kétlépcsős hitelesítést!</b> Mostmár használhatja fiókját.</p>`;
          CreateAlertBox("Kétlépcsős hitelesítés", html, false);
          setTimeout(() => {window.location.reload();}, 2000);
        } else {
          html = `<p style="color: red;"><b>${text}</b></p>`;
          CreateAlertBox("HIBA", html);
        }
      }, function() {
        html = `<p style="color: red;"><b>Hálózati hiba történt, próbálja újra!</b></p>`;
        CreateAlertBox("HIBA", html);
        Loading(false);
      });
    }
    if (document.getElementById('qrcode')) {
      new QRCode(document.getElementById("qrcode"), {
        text: "<?php echo $totpQRCode;?>",
        width: 160,
        height: 160,
        colorDark : "#000000",
        colorLight : "#ffffff",
        correctLevel : QRCode.CorrectLevel.H
      });
    }

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