<?php
http_response_code(200);

$BALE_TOKEN = '1355872301:axCKRD_1jafdaTKo67YgzSDZxuCIJ6g44mU';
$BALE_CHAT_ID = '@kasbedaramad_1405';

$raw = file_get_contents('php://input');
$update = json_decode($raw, true);
$post = $update['channel_post'] ?? null;

if (!$post) exit('OK');

$chat = $post['chat'] ?? [];

if (strtolower($chat['username'] ?? '') !== 'kasbedaramad_1405') {
    exit('OK');
}

$text = $post['text'] ?? $post['caption'] ?? '';

if ($text === '') exit('OK');

$url = "https://tapi.bale.ai/bot{$BALE_TOKEN}/sendMessage";

$payload = [
    'chat_id' => $BALE_CHAT_ID,
    'text' => $text
];

$ch = curl_init($url);
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => json_encode($payload, JSON_UNESCAPED_UNICODE),
    CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CONNECTTIMEOUT => 10,
    CURLOPT_TIMEOUT => 20
]);

$result = curl_exec($ch);
$error = curl_error($ch);
$http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

file_put_contents(
    __DIR__ . '/forwarder_log.txt',
    date('Y-m-d H:i:s') .
    " BALE_HTTP: $http | ERROR: $error | RESPONSE: " .
    ($result === false ? 'FAILED' : $result) . PHP_EOL,
    FILE_APPEND | LOCK_EX
);

echo 'OK';