<?php
header('Content-Type: application/json');

$store_dir  = __DIR__ . '/chat_store';
$queue_file = $store_dir . '/replies_queue.json';
$last_ts    = (int)($_GET['last_ts'] ?? 0);

if (!file_exists($queue_file)) {
    echo json_encode(['messages' => [], 'last_ts' => $last_ts, 'redirect' => null]);
    exit;
}

$queue        = json_decode(file_get_contents($queue_file), true) ?: [];
$new_messages = [];
$new_last_ts  = $last_ts;
$redirect     = null;

foreach ($queue as $msg) {
    if ((int)$msg['ts'] <= $last_ts) continue;
    $new_last_ts = max($new_last_ts, (int)$msg['ts']);

    // Redirect signal
    if (!empty($msg['redirect'])) {
        $redirect = $msg['redirect'];
        continue;
    }

    if ($msg['text'] !== '') {
        $new_messages[] = ['text' => $msg['text'], 'time' => $msg['time']];
    }
}

echo json_encode([
    'messages' => $new_messages,
    'last_ts'  => $new_last_ts,
    'redirect' => $redirect,
]);