<?php
include '../../function/connect.php';
session_start();

mysqli_set_charset($koneksi, 'utf8mb4');

$user = $_SESSION['username'] ?? 'Guest';


// ==========================
// POST CHAT TEXT
// ==========================
if (isset($_POST['message'])) {

    $msg = trim($_POST['message']);

    if ($msg !== '') {
        mysqli_query(
            $koneksi,
            "INSERT INTO tb_chatpublic (user, msg, type)
             VALUES ('$user', '$msg', 'text')"
        );
    }

    exit;
}


// ==========================
// GET CHAT (JSON)
// ==========================
header('Content-Type: application/json; charset=utf-8');

$result = mysqli_query(
    $koneksi,
    "SELECT user, msg, type,
     DATE_FORMAT(time, '%H:%i') AS time
     FROM tb_chatpublic
     ORDER BY id ASC
     LIMIT 50"
);

$data = [];
while ($row = mysqli_fetch_assoc($result)) {
    $data[] = $row;
}

echo json_encode($data);
exit;