<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

include 'includes/header.php';
include 'includes/nav.php';
?>
<!DOCTYPE html>
<html lang="de">
<head>
  <meta charset="UTF-8">
  <title>Globaler Chat</title>
  <style>
    body { font-family: sans-serif; margin: 0; padding: 0; }
    #chatfenster { height: 400px; overflow-y: scroll; border: 1px solid #ccc; padding: 10px; }
    #formular { display: flex; gap: 10px; padding: 10px; }
    input[type="text"] { flex: 1; padding: 10px; }
    button { padding: 10px 15px; }
    .nachricht { margin-bottom: 8px; }
    .zeit { color: gray; font-size: 0.8em; }
  </style>
</head>
<body>
<h2 style="padding: 10px;">💬 Globaler Chat</h2>
<div id="chatfenster"></div>

<form id="formular">
  <input type="text" id="eingabe" placeholder="Nachricht eingeben..." autocomplete="off">
  <button type="submit">Senden</button>
</form>

<script>
function ladeChat() {
  fetch("chat_laden.php")
    .then(response => response.text())
    .then(data => {
      document.getElementById("chatfenster").innerHTML = data;
      document.getElementById("chatfenster").scrollTop = 99999;
    });
}

document.getElementById("formular").addEventListener("submit", function(e) {
  e.preventDefault();
  const nachricht = document.getElementById("eingabe").value;
  if (nachricht.trim() === '') return;
  fetch("chat_senden.php", {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: "nachricht=" + encodeURIComponent(nachricht)
  }).then(() => {
    document.getElementById("eingabe").value = "";
    ladeChat();
  });
});

setInterval(ladeChat, 3000); // alle 3 Sekunden laden
ladeChat();
</script>

<? include 'includes/footer.php'; ?>
