<?php 

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

$baseDir = $_SERVER['DOCUMENT_ROOT'];

require_once $baseDir . '/../scripts/session_functions.php';

ini_wkvs_session(true);

$csrf_token = $_SESSION['csrf_token'] ?? '';

$access_granted_wkl = check_user_permission('wk_leitung', true) ?? false;

if ( ! $access_granted_wkl ) :

    $logintype = 'wk_leitung';
    
    require $baseDir . '/../scripts/login/login.php';

    $logintype = '';

else : 
?>

<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" type="png" href="/intern/img/icon.png">
    <title>Intern - Displaycontrol</title>

    <link rel="stylesheet" href="/intern/css/displaycontrol.css">
    <link rel="stylesheet" href="/intern/css/custom-msg-display.css">
    <script src="/intern/js/jquery/jquery-3.7.1.min.js"></script>
    <script src="/intern/js/custom-msg-display.js"></script>


    <link rel="stylesheet" href="/files/fonts/fonts.css">
    <link rel="stylesheet" href="/intern/css/sidebar.css">
    <link rel="stylesheet" href="/intern/css/user.css">
    
</head>
<body class="displaycontrol">

<?php

$type = 'wkl';

$dbconnection = require $baseDir . '/../scripts/db/db-verbindung-script.php';

if ($dbconnection['success'] !== true){
    echo 'Critical DB Error.';
    exit;
}

require $baseDir . '/../scripts/websocket/ws-create-token.php';
require $baseDir . '/../scripts/db/db-tables.php';

$stmt = $mysqli->prepare("SELECT `name` FROM $db_tabelle_disziplinen ORDER BY start_index ASC");

if (!$stmt->execute()) {
  http_response_code(500);
  exit;
}

$result = $stmt->get_result();
$disciplines = $result->fetch_all(MYSQLI_ASSOC);

$stmt->close();

$currentPage = 'displaycontrol';
require $baseDir . '/../scripts/sidebar/sidebar.php';

$WSaccesstype = "wk_leitung";
$WSaccess = "displaycontrol";
$WSaccessPermission = "W";

?>

  <script>
    let ws;
    let firstConnect = true;
    const RETRY_DELAY = 2000;
    const csrf_token = "<?= $csrf_token ?>";

    const WSaccesstype = "<?= $WSaccesstype ?>";
    const WSaccess = "<?= $WSaccess ?>";
    const WSaccessPermission = "<?= $WSaccessPermission ?>"

    const urlAjaxNewWSToken = '/intern/scripts/ajax-create-ws-token.php';

    async function fetchNewWSToken(accesstype, access, accessPermission) {
        try {
            const response = await fetch(urlAjaxNewWSToken, {
                method: "POST",
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({ 
                    csrf_token,
                    accesstype, 
                    access, 
                    accessPermission 
                })
            });

            if (response.status === 403) {
                console.warn("Please Re-Autenithicate. Reloading page...");
                location.reload(); 
                return null;
            }

            if (!response.ok) return null;

            const data = await response.json();
            return data.success ? data.token : null;
        } catch (error) {
            console.error("Token fetch failed:", error);
            return null;
        }
    }

    async function startWebSocket() {
        console.log("Attempting WebSocket connection...");

        let token;
        if (firstConnect) {
            token = '<?= generateWSAdminToken($WSaccesstype, $WSaccess) ?>';
        } else {
            token = await fetchNewWSToken(WSaccesstype, WSaccess, WSaccessPermission);
        }

        if (!token) {
            console.error("No valid token available. Retrying...");
            scheduleRetry();
            return;
        }

        try {
            ws = new WebSocket(`wss://${window.location.hostname}/ws/?access=token&token=${token}`);
        } catch (err) {
            console.error("Malformed WebSocket URL", err);
            scheduleRetry();
            return;
        }

        ws.onopen = () => {
            console.log("WebSocket connected!");
            if (!firstConnect) {
                displayMsg(1, "Live Syncronisation wieder verfügbar");
            }
            firstConnect = true;
        };

        ws.onerror = (event) => {
            console.error("WebSocket error observed.");
        };

        ws.onclose = (event) => {
            displayMsg(0, "Live Syncronisation verloren");
            firstConnect = false;

            scheduleRetry();
        };
    }

    function scheduleRetry() {
        console.log(`Retrying in ${RETRY_DELAY}ms...`);
        setTimeout(startWebSocket, RETRY_DELAY);
    }

    startWebSocket();
  </script>

  <div class="headerDivTrainer">
    <div class="headingPanelDiv">
      <h2 class="headingPanel">Anzeigesteuerung</h2>
    </div>
    <div class="menuWrapper">
      <?php sidebarRender('button'); ?>
    </div>
  </div>

  <?php sidebarRender('modal'); ?>

  <section class="bgSection">

    <div class="controls-wrapper">
      <span>Anzeigeoptionen</span>
      <div>
        <button class="change-type" value="logo">Logo + WK-Name</button>
        <button class="change-type" value="scoring">WK-Betrieb</button>
      </div>
      <form class="change-type-form" data-type="ctext">
        <button type="submit">Individueller Text</button>
        <textarea placeholder="Individuellen Text eingeben..."></textarea>
      </form>
    </div>

    <div class="iframe-grid">
      <?php
      foreach ($disciplines as $dis){
        echo '<div class="iframeWithTitle"><h1>Display '.ucfirst($dis['name']).'</h1>';
        echo '<iframe
              id="inlineFrame-'.$dis['name'].'"
              title="Display '.$dis['name'].'"
              src="/externe-geraete/display/'. strtolower($dis['name']).'">
              </iframe></div>';
      }
      ?>
    </div>
  </section>

  <script>

  jQuery(document).ready(function($) {

    const changeTypes = document.querySelectorAll('.change-type');
    changeTypes.forEach(btn => {
      btn.addEventListener("click", function() {
        const $input = $(this);
        const typeValue = $input.val();
        sendType(typeValue, $input, '');
      });
    });

    $('.change-type-form').on('submit', function(event) {
      event.preventDefault();
      const $form = $(this);
      const typeValue = $form.data('type');
      const ctext = $form.find('textarea').val() || '';
      sendType(typeValue, $form.find('textarea'), ctext);
    });

    function sendType(typeValue, $element, ctext) {
      const url = `/intern/scripts/displaycontrol/ajax-update_display_config_json.php`;

      fetch(url,{
          method: 'POST',
          headers: {'Content-Type': 'application/x-www-form-urlencoded'},
          body: new URLSearchParams({
              csrf_token,
              type: typeValue,
              ctext
          })
      })
        .then(res => res.json())
        .then(response => {

          if (response.success) {
            ws.send(JSON.stringify({
              type: "DISPLAY_CONTROL",
              payload: {
                type: typeValue,
                ctext: ctext
              }
            }));
            displayMsg(1, "Erfolgreich aktualisiert");
          } else {
            alert('Error: ' + response.message);
          }
        })
        .catch(err => {
          $element.css('background-color', '#f8d7da');
          console.error('AJAX fetch error:', err);
        });
    }

  });

  </script>
</body>
</html>
<?php $mysqli->close();
endif;