<?php
error_reporting(E_ALL & ~E_DEPRECATED);

ini_set('display_errors', 0);
ini_set('log_errors', 1);
$log_dir = __DIR__ . '/storage/logs';
if (!is_dir($log_dir)) {
    @mkdir($log_dir, 0775, true);
}
ini_set('error_log', $log_dir . '/debug_log.txt');

include_once __DIR__ . "/settings/values.php";
include_once __DIR__ . '/settings/jdf.php';
include_once __DIR__ . '/baseInfo.php';

include_once __DIR__ . '/settings/config_telegram.php';
include_once __DIR__ . '/settings/config_keyboards.php';
include_once __DIR__ . '/settings/config_utils.php';
include_once __DIR__ . '/settings/config_xui_api.php';
include_once __DIR__ . '/settings/config_marzban_api.php';

$connection = new mysqli('127.0.0.1', $dbUserName, $dbPassword, $dbName);
if ($connection->connect_error) {
    exit("error " . $connection->connect_error);
}
$connection->set_charset("utf8mb4");

// ✨ Self-healing migration for agent quota columns
$check_vol = $connection->query("SHOW COLUMNS FROM `users` LIKE 'agent_volume'");
if ($check_vol && $check_vol->num_rows == 0) {
    $connection->query("ALTER TABLE `users` ADD COLUMN `agent_volume` DOUBLE NOT NULL DEFAULT 0");
}
$check_lim = $connection->query("SHOW COLUMNS FROM `users` LIKE 'agent_limit'");
if ($check_lim && $check_lim->num_rows == 0) {
    $connection->query("ALTER TABLE `users` ADD COLUMN `agent_limit` INT NOT NULL DEFAULT 0");
}
$check_test = $connection->query("SHOW COLUMNS FROM `users` LIKE 'agent_test_limit'");
if ($check_test && $check_test->num_rows == 0) {
    $connection->query("ALTER TABLE `users` ADD COLUMN `agent_test_limit` INT NOT NULL DEFAULT 0");
}
$check_notified = $connection->query("SHOW COLUMNS FROM `users` LIKE 'join_notified'");
if ($check_notified && $check_notified->num_rows == 0) {
    $connection->query("ALTER TABLE `users` ADD COLUMN `join_notified` INT(1) NOT NULL DEFAULT 0");
}

function getCookieFilePathLocal($server_id, $is_cert = false) {
    $dir = __DIR__ . '/storage/cookies';
    if (!is_dir($dir)) {
        @mkdir($dir, 0775, true);
    }
    $prefix = $is_cert ? 'cookie_cert_' : 'cookie_';
    return $dir . '/' . $prefix . $server_id . '.txt';
}


$range = [
    '149.154.160.0/22',
    '149.154.164.0/22',
    '91.108.4.0/22',
    '91.108.56.0/22',
    '91.108.8.0/22',
    '95.161.64.0/20',
];


$update = json_decode(file_get_contents("php://input"));

if (isset($update->message)) {
    $from_id = $update->message->from->id ?? 0;
    $text = $update->message->text ?? "";
    $first_name = htmlspecialchars($update->message->from->first_name ?? "");
    $caption = $update->message->caption ?? ""; // فیکس خطای caption
    $chat_id = $update->message->chat->id ?? 0;
    $last_name = htmlspecialchars($update->message->from->last_name ?? "");
    $username = $update->message->from->username ?? "ندارد";
    $message_id = $update->message->message_id ?? 0;

    // فیکس خطاهای Reply
    $forward_from_name = $update->message->reply_to_message->forward_sender_name ?? null;
    $forward_from_id = $update->message->reply_to_message->forward_from->id ?? null;
    $reply_text = $update->message->reply_to_message->text ?? null;
}
if (isset($update->callback_query)) {
    $callbackId = $update->callback_query->id;
    $data = $update->callback_query->data ?? ""; // فیکس دیتا
    $text = $update->callback_query->message->text ?? "";
    $message_id = $update->callback_query->message->message_id;
    $chat_id = $update->callback_query->message->chat->id;
    $chat_type = $update->callback_query->message->chat->type;
    $username = htmlspecialchars($update->callback_query->from->username ?? "ندارد");
    $from_id = $update->callback_query->from->id;
    $first_name = htmlspecialchars($update->callback_query->from->first_name ?? "");
    $markup = json_decode(json_encode($update->callback_query->message->reply_markup->inline_keyboard), true);
}
if (($from_id ?? 0) < 0)
    exit();
$stmt = $connection->prepare("SELECT * FROM `users` WHERE `userid`=?");
$stmt->bind_param("i", $from_id);
$stmt->execute();
$uinfo = $stmt->get_result();
$userInfo = $uinfo->fetch_assoc();
if (is_null($userInfo)) {
    $userInfo = ['step' => 'none', 'isAdmin' => false, 'wallet' => 0, 'is_agent' => 0, 'agent_date' => 0, 'date' => time()];
} else {
    // بروزرسانی نام و یوزرنیم در صورت تغییر در تلگرام
    $currentName = !empty($first_name) ? $first_name : '';
    $currentUsername = !empty($username) && $username !== 'ندارد' ? $username : '';
    if ($currentName !== $userInfo['name'] || $currentUsername !== $userInfo['username']) {
        $updUsr = $connection->prepare("UPDATE `users` SET `name` = ?, `username` = ? WHERE `userid` = ?");
        if ($updUsr) {
            $updUsr->bind_param("ssi", $currentName, $currentUsername, $from_id);
            $updUsr->execute();
            $updUsr->close();
            $userInfo['name'] = $currentName;
            $userInfo['username'] = $currentUsername;
        }
    }
}
$stmt->close();

$stmt = $connection->prepare("SELECT * FROM `setting` WHERE `type` = 'PAYMENT_KEYS'");
$stmt->execute();
$paymentKeys = $stmt->get_result()->fetch_assoc()['value'];
if (!is_null($paymentKeys))
    $paymentKeys = json_decode($paymentKeys, true);
else
    $paymentKeys = array();
$stmt->close();

$stmt = $connection->prepare("SELECT * FROM `setting` WHERE `type` = 'BOT_STATES'");
$stmt->execute();
$botState = $stmt->get_result()->fetch_assoc()['value'];
if (!is_null($botState))
    $botState = json_decode($botState, true);
else
    $botState = array();
$stmt->close();

$channelLock = $botState['lockChannel'];

// درخواست بررسی عضویت
$checkMember = bot('getChatMember', [
    'chat_id' => $channelLock,
    'user_id' => $from_id
]);

// بررسی امن: آیا نتیجه معتبر است؟
if (isset($checkMember->result) && isset($checkMember->result->status)) {
    $joniedState = $checkMember->result->status;
}
else {
    // اگر نتوانست چک کند (مثلاً تلگرام قطع بود)، فرض می‌کنیم کاربر عضو نیست یا رد می‌کنیم
    // 'left' باعث می‌شود ربات قفل شود، که امن‌تر است
    $joniedState = 'left';
}

if (isset($update->message->document)) {
    $filetype = 'document';
    $fileid = $update->message->document->file_id;
}
elseif (isset($update->message->audio)) {
    $filetype = 'music';
    $fileid = $update->message->audio->file_id;
}
elseif (isset($update->message->photo)) {
    $filetype = 'photo';
    $photo_array = $update->message->photo;
    $fileid = end($photo_array)->file_id;
}

$cancelKey = json_encode(['keyboard' => [
        [['text' => $buttonValues['cancel']]]
    ], 'resize_keyboard' => true]);
$removeKeyboard = json_encode(['remove_keyboard' => true]);












// 🛠 تابع مکمل کمکی جهت ایمن‌سازی لوپ دیتای دریافتی زنده از API پنل

// ======================================================
// 0. تابع کمکی لاگ‌گیری (این باعث رفع ارور Fatal می‌شود)
// ======================================================
if (!function_exists('logToDebug')) {
}

// ======================================================
// 1. تابع اصلی مدیریت خرید (نسخه کامل و بدون ارور)
// ======================================================

// ======================================================
// 2. تابع کمکی ساخت اکانت (هوشمند: تشخیص پروتکل و اصلاح دیتا)
// ======================================================
