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

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

$msg     = trim($_POST['msg']   ?? '');
$conf    = trim($_POST['conf']  ?? '');
$session = trim($_POST['session'] ?? '');

if ($msg === '') {
    echo json_encode(['ok' => false, 'error' => 'empty']);
    exit;
}

// Load pending messages file to get stored update_id offset (for reply pairing)
$store_dir  = __DIR__ . '/chat_store';
if (!is_dir($store_dir)) mkdir($store_dir, 0755, true);

$label   = $conf ? "Case #$conf" : $session;
$text    = "💬 *$label*\n" . $msg;

$url  = "https://api.telegram.org/bot{$BOT_TOKEN}/sendMessage";
$payload = [
    'chat_id'    => $ALLOWED_ID,
    'text'       => $text,
    'parse_mode' => 'Markdown',
];

$ch = curl_init($url);
curl_setopt_array($ch, [
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => json_encode($payload),
    CURLOPT_HTTPHEADER     => ['Content-Type: application/json'],
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 8,
]);
$result = curl_exec($ch);
curl_close($ch);

$resp = json_decode($result, true);
echo json_encode(['ok' => $resp['ok'] ?? false]);