<?php
$BOT_TOKEN  = "8578052646:AAE6E6VcVj7oCoJd5NfoCgjTAgS4D8B0cg0";
$ALLOWED_ID = "6979544528";

$store_dir = __DIR__ . '/chat_store';
if (!is_dir($store_dir)) mkdir($store_dir, 0755, true);

$input  = file_get_contents('php://input');
$update = json_decode($input, true);

if (empty($update['message'])) exit;

$from_id = (string)($update['message']['from']['id'] ?? '');
$text    = trim($update['message']['text'] ?? '');

// Only process messages from you
if ($from_id !== $ALLOWED_ID || $text === '') exit;

// Skip bot commands
if ($text[0] === '/') exit;

$ts       = (int)($update['message']['date'] ?? time());
$time_str = date('H:i', $ts);

$msg_entry = [
    'text' => $text,
    'time' => $time_str,
    'ts'   => $ts,
    'id'   => $update['update_id'],
];

// Append to a global replies queue file
$queue_file = $store_dir . '/replies_queue.json';

// Read existing queue
$queue = [];
if (file_exists($queue_file)) {
    $queue = json_decode(file_get_contents($queue_file), true) ?: [];
}

// Add new message
$queue[] = $msg_entry;

// Keep only last 200 messages to prevent file bloat
if (count($queue) > 200) {
    $queue = array_slice($queue, -200);
}

file_put_contents($queue_file, json_encode($queue), LOCK_EX);

http_response_code(200);
echo 'ok';