<?php
session_start();
if (!isset($_SESSION['user_id'])) exit('Unauthorized');

$logFile = __DIR__ . '/data/simple_chat.log';
$action = $_GET['action'] ?? '';

if ($action == 'send' && $_SERVER['REQUEST_METHOD'] == 'POST') {
    $message = trim($_POST['message'] ?? '');
    if ($message !== '') {
        $user = getUserById($_SESSION['user_id']);
        $name = $user['full_name'];
        $entry = date('Y-m-d H:i:s') . "|" . $name . "|" . str_replace(["\n", "\r"], ' ', $message) . "\n";
        file_put_contents($logFile, $entry, FILE_APPEND);
    }
    exit;
}

if ($action == 'fetch') {
    $messages = [];
    if (file_exists($logFile)) {
        $lines = file($logFile, FILE_IGNORE_NEW_LINES);
        $messages = array_reverse(array_slice(array_reverse($lines), -50));
    }
    header('Content-Type: application/json');
    echo json_encode(['messages' => $messages]);
    exit;
}
?>