<?php
session_start();
require_once __DIR__ . '/../includes/config.php';

if (!isset($_SESSION['admin_logged_in'])) exit;

$request_id = intval($_POST['request_id']);
$answer = trim($_POST['answer'] ?? '');

if ($answer === '') exit;


if(!empty($req['loading_message_id'])){
    file_get_contents(
        "https://api.telegram.org/bot".BOT_TOKEN."/editMessageText?".
        http_build_query([
            'chat_id' => $req['telegram_id'],
            'message_id' => $req['loading_message_id'],
            'text' => "✅ آماده شد!\n\n100% ▓▓▓▓▓▓▓▓▓▓"
        ])
    );
}




// تبدیل [Enter_LF] به اینتر واقعی
$answer = str_replace('[Enter_LF]', "\n\n", $answer);





/* ===================== اطلاعات درخواست ===================== */
$stmt = $pdo->prepare("
    SELECT 
        r.text_content,
        r.user_message_id,
        u.telegram_id,
        u.first_name,
        u.last_name,
        u.username
    FROM requests r
    JOIN users u ON r.user_id = u.id
    WHERE r.id = ?
");
$stmt->execute([$request_id]);
$info = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$info) exit;

/* ===================== نام کاربر ===================== */
$full_name = trim($info['first_name'].' '.$info['last_name']);
$user_line = "👤 {$full_name}";
if (!empty($info['username'])) {
    $user_line .= " (@{$info['username']})";
}

/* ===================== ارسال پاسخ به کاربر ===================== */
$inline_keyboard = [
    'inline_keyboard' => [
        [

            ['text' => '👎 ', 'callback_data' => 'dislike_'.$request_id],
            ['text' => '👍 ', 'callback_data' => 'like_'.$request_id],
            
            
            
        ],
        [
            ['text' => '💬 ادامه چت', 'callback_data' => 'continue_'.$request_id],
            ['text' => '➕ چت جدید', 'callback_data' => 'newchat'],
        ]
    ]
];

file_get_contents(
    "https://api.telegram.org/bot".BOT_TOKEN."/sendMessage?" .
    http_build_query([
        'chat_id' => $info['telegram_id'],
        'text' => $answer,
        'reply_to_message_id' => $info['user_message_id'],
        'reply_markup' => json_encode($inline_keyboard, JSON_UNESCAPED_UNICODE)
    ])
);



/* ===================== پیام کانال ===================== */
$channel_text =
"🧠 پاسخ چت هوش مصنوعی
📌 درخواست #{$request_id}
{$user_line}

🗨 متن کاربر:
{$info['text_content']}

✍️ پاسخ:
{$answer}";

/* ===================== تقسیم امن متن ===================== */
$parts = [];
$max = 3900;
$len = mb_strlen($channel_text, 'UTF-8');

for ($i = 0; $i < $len; $i += $max) {
    $parts[] = mb_substr($channel_text, $i, $max, 'UTF-8');
}

/* ===================== ارسال به کانال + لاگ خطا ===================== */
foreach ($parts as $part) {
    $url = "https://api.telegram.org/bot".BOT_TOKEN."/sendMessage";
    $res = file_get_contents($url . "?" . http_build_query([
        'chat_id' => PRIVATE_CHANNEL_ID,
        'text' => $part
    ]));

    // اگر خطا داشت لاگ کن
    if ($res === false) {
        file_put_contents(__DIR__.'/channel_error.log', date('Y-m-d H:i:s')." ERROR\n", FILE_APPEND);
    }
}

/* ===================== ذخیره پاسخ ===================== */
$pdo->prepare("
    UPDATE requests
    SET 
        answer_text = ?,
        status = 'done',
        completed_at = NOW()
    WHERE id = ?
")->execute([$answer, $request_id]);

header("Location: request_view.php?id=".$request_id);
exit;
