<?php
$file = 'chat.txt';

// 1. Spracovanie novej správy
if (isset($_POST['m']) && !empty(trim($_POST['m']))) {
    $msg = htmlspecialchars($_POST['m']) . " (" . date("H:i") . ")\n";

    // Načítame existujúce správy do poľa
    $messages = file_exists($file) ? file($file) : [];
    $messages[] = $msg;

    // Ponecháme len posledných 20 a uložíme späť
    $messages = array_slice($messages, -20);
    file_put_contents($file, implode("", $messages));

    header("Location: chat.php"); // Refresh po odoslaní
    exit;
}
?>

<!-- 2. Jednoduché UI -->
<form method="post" style="position:fixed; bottom:0; background:white; width:100%; padding:10px;">
    <input type="text" name="m" autofocus required placeholder="Napíš niečo...">
    <button type="submit">Poslať</button>
</form>

<div id="chat" style="padding-bottom: 50px; font-family: sans-serif;">
    <?php
    if (file_exists($file)) {
        echo nl2br(file_get_contents($file));
    }
    ?>
</div>

<script>
    // Automatický scroll nadol
    window.scrollTo(0, document.body.scrollHeight);
    // Refresh každé 3 sekundy pre nové správy
    setTimeout(() => location.reload(), 3000);
</script>
