<?php
function BaleRequest(string $method, array $data)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://tapi.bale.ai/bot' . API_KEY . '/' . $method);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept: application/json']);
    $response = curl_exec($ch);
    return json_decode($response);
}


function sendMessage($chat_id, $text, $reply_markup = null, $message_id = null)
{
    return BaleRequest('sendMessage', [
        'chat_id' => $chat_id,
        'text' => $text,
        'reply_markup' => $reply_markup,
        'reply_to_message_id' => $message_id
    ]);
}


function editMessage($chat_id, $message_id, $text, $reply_markup = null)
{
    return BaleRequest('editMessageText', [
        'chat_id' => $chat_id,
        'message_id' => $message_id,
        'text' => $text,
        'reply_markup' => $reply_markup
    ]);
}


function editMessageReplyMarkup($chat_id, $message_id, $reply_markup)
{
    return BaleRequest('editMessageReplyMarkup', [
        'chat_id' => $chat_id,
        'message_id' => $message_id,
        'reply_markup' => $reply_markup
    ]);
}


function deleteMessage($chat_id, $message_id)
{
    return BaleRequest(
        'deleteMessage',
        [
            'chat_id' => $chat_id,
            'message_id' => $message_id
        ]
    );
}


function forwardMessage($chat_id, $from_id, $message_id)
{
    return BaleRequest('ForwardMessage', [
        'chat_id' => $chat_id,
        'from_chat_id' => $from_id,
        'message_id' => $message_id
    ]);
}


function sendPhoto($chat_id, $photo, $caption = null, $reply_markup = null, $message_id = null)
{
    return BaleRequest('sendPhoto', [
        'chat_id' => $chat_id,
        'photo' => $photo,
        'caption' => $caption,
        'reply_markup' => $reply_markup,
        'reply_to_message_id' => $message_id
    ]);
}


function sendDocument($chat_id, $document, $caption = null, $reply_markup = null, $message_id = null)
{
    return BaleRequest('sendDocument', [
        'chat_id' => $chat_id,
        'document' => $document,
        'caption' => $caption,
        'reply_markup' => $reply_markup,
        'reply_to_message_id' => $message_id
    ]);
}


function answerCallbackQuery($callback_query_id, $text = null, $show_alert = false)
{
    return BaleRequest('answerCallbackQuery', [
        'callback_query_id' => $callback_query_id,
        'text' => $text,
        'show_alert' => $show_alert
    ]);
}


function getChat($chat_id)
{
    return BaleRequest('getChat', [
        'chat_id' => $chat_id
    ]);
}


function saveSetting($key, $value)
{
    global $pdo;
    $stmt = $pdo->prepare("SELECT * FROM `bot_settings` WHERE `setting_key` = ?");
    $stmt->execute([$key]);

if($stmt->fetch()) {
        $stmt = $pdo->prepare("UPDATE `bot_settings` SET `setting_value` = ? WHERE `setting_key` = ?");
        $stmt->execute([$value, $key]);
} else {
        $stmt = $pdo->prepare("INSERT INTO `bot_settings` (`setting_key`, `setting_value`) VALUES (?, ?)");
        $stmt->execute([$key, $value]);
}

}


function getChatMember($chat_id, $user_id)
{
    return BaleRequest('getChatMember', [
        'chat_id' => $chat_id,
        'user_id' => $user_id
    ]);
}


function promoteChatMember($chat_id, $user_id, $permissions = [])
{
    $data = [
        'chat_id' => $chat_id,
        'user_id' => $user_id
    ];
    $data = array_merge($data, $permissions);
    return BaleRequest('promoteChatMember', $data);
}


function getUser($chat_id)
{
    global $pdo;
    $query = "SELECT * FROM `users` WHERE `user_id` = ?";
    $stmt = $pdo->prepare($query);
    $stmt->execute([$chat_id]);
    return $stmt->fetch();
}


function syncUserInfo($chat_id, $first_name, $user_name)
{
    global $pdo;

if(!$pdo || !$chat_id || $chat_id === 'none') return;
    try {
        $stmt = $pdo->prepare("INSERT INTO `users` (`user_id`, `full_name`, `username`) VALUES (?, ?, ?) 
                               ON DUPLICATE KEY UPDATE 
                               `full_name` = IF(? != '' AND ? != `full_name`, ?, `full_name`),
                               `username` = IF(? != '' AND ? != `username`, ?, `username`)");
        $stmt->execute([$chat_id, $first_name, $user_name, $first_name, $first_name, $first_name, $user_name, $user_name, $user_name]);
} catch (PDOException $e) {
        $lockName = "user_sync_" . intval($chat_id);
        try { $pdo->query("SELECT GET_LOCK('$lockName', 2)"); } catch (Exception $_) {}

        $stmt = $pdo->prepare("SELECT `full_name`, `username` FROM `users` WHERE `user_id` = ? LIMIT 1");
        $stmt->execute([$chat_id]);
        $u = $stmt->fetch();

if(!$u) {
            $stmtIns = $pdo->prepare("INSERT INTO `users` (`user_id`, `full_name`, `username`) VALUES (?, ?, ?)");
            $stmtIns->execute([$chat_id, $first_name, $user_name]);
} else {
            $needUpdate = false;
            $newName = $u->full_name;
            $newUser = $u->username;

if($first_name && $first_name !== $u->full_name) {
                $newName = $first_name;
                $needUpdate = true;
}


if($user_name && $user_name !== $u->username) {
                $newUser = $user_name;
                $needUpdate = true;
}


if($needUpdate) {
                $stmtUpd = $pdo->prepare("UPDATE `users` SET `full_name` = ?, `username` = ? WHERE `user_id` = ?");
                $stmtUpd->execute([$newName, $newUser, $chat_id]);
}

}

        try { $pdo->query("SELECT RELEASE_LOCK('$lockName')"); } catch (Exception $_) {}

}

}


function setStep($chat_id, $step)
{
    global $pdo;

if(!$pdo) return false;
    $query = "UPDATE `users` SET `step` = ? WHERE `user_id` = ?";
    $stmt = $pdo->prepare($query);
    $stmt->execute([$step, $chat_id]);
}


function getMainMenuKeyboard($user)
{
    global $userKeyboard;
    $markup = $userKeyboard;

if($user && (!empty($user->is_admin) || !empty($user->is_owner))) {
        $kb = json_decode($userKeyboard, true);
        $kb['keyboard'][] = [['text' => 'پنل مدیریت 🛠']];
        $markup = json_encode($kb);
}

    return $markup;
}


function debug($from_id, $value)
{
    $update = print_r($value, true);
    sendMessage($from_id, $update);
}


function checkSpam($user_id) {
    global $pdo;
    $limit = 5; 
    $timeFrame = 2; 
    $now = time();
    try {
        $stmt = $pdo->prepare("INSERT INTO `spam_check` (`user_id`, `request_count`, `last_request`) 
                               VALUES (?, 1, ?) 
                               ON DUPLICATE KEY UPDATE 
                               `request_count` = IF((? - `last_request`) < ?, `request_count` + 1, 1),
                               `last_request` = ?");
        $stmt->execute([$user_id, $now, $now, $timeFrame, $now]);
        $stmt = $pdo->prepare("SELECT `request_count` FROM `spam_check` WHERE `user_id` = ? LIMIT 1");
        $stmt->execute([$user_id]);
        $data = $stmt->fetch();

if($data && $data->request_count > $limit) {
            return true; 
}

} catch (PDOException $e) {
        $stmt = $pdo->prepare("SELECT * FROM `spam_check` WHERE `user_id` = ? LIMIT 1");
        $stmt->execute([$user_id]);
        $data = $stmt->fetch();

if($data) {

if(($now - $data->last_request) < $timeFrame) {
                $newCount = $data->request_count + 1;
                $stmt = $pdo->prepare("UPDATE `spam_check` SET `request_count` = ?, `last_request` = ? WHERE `user_id` = ?");
                $stmt->execute([$newCount, $now, $user_id]);

if($newCount > $limit) {
                    return true;
}

} else {
                $stmt = $pdo->prepare("UPDATE `spam_check` SET `request_count` = 1, `last_request` = ? WHERE `user_id` = ?");
                $stmt->execute([$now, $user_id]);
}

} else {
            $stmt = $pdo->prepare("INSERT INTO `spam_check` (`user_id`, `request_count`, `last_request`) VALUES (?, 1, ?)");
            $stmt->execute([$user_id, $now]);
}

}

    return false; 
}


function convertPersianToEnglishNumbers($string)
{
    $persian = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
    $english = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
    return str_replace($persian, $english, $string);
}


function settings($key, $default = null)
{
    global $pdo;

if(!$pdo) return $default;
    static $cache = [];

if(array_key_exists($key, $cache)) {
        return $cache[$key];
}

    $query = "SELECT * FROM `bot_settings` WHERE `setting_key` = ?";
    $stmt = $pdo->prepare($query);
    $stmt->execute([$key]);
    $result = $stmt->fetch();
    $value = $result ? $result->setting_value : $default;
    $cache[$key] = $value;
    return $value;
}


function generateChannelsKeyboard($channels)
{
    $rows = [];

if(!empty($channels)) {

foreach($channels as $ch) {
            $label = $ch->channel_name ? $ch->channel_name : '@' . $ch->channel_username;
            $rows[] = [
                ['text' => $label, 'callback_data' => 'select-channel:' . $ch->channel_username],
                ['text' => '🗑 حذف', 'callback_data' => 'delete-channel:' . $ch->id]
            ];
}

}

    $rows[] = [['text' => '➕ اضافه کردن کانال جدید', 'callback_data' => 'add_channel']];
    return json_encode([
        "inline_keyboard" => $rows
    ]);
}


function calculateReward($order) {
    global $pdo;
    return calculateRewardWithUser($order);
}


function calculateRewardWithUser($order, $userId = null) {
    global $pdo, $from_id;
    $targetUserId = $userId ?? $from_id ?? null;
    $isUserVip = false;

if($targetUserId) {
        $u = getUser($targetUserId);

if($u && $u->is_vip && strtotime($u->vip_expire) > time()) {
            $isUserVip = true;
}

}


if($isUserVip) {
        return $order->coin_per_member;
}

    $isOrderVip = $order->is_vip;
    $isBoosted = isset($order->boost_manual) && $order->boost_manual > 0;
    $basePrice = $order->coin_per_member ?? 1;

if($isUserVip) {
        return $basePrice;
}

    return calculateRewardInternal($order, $isUserVip);
}


function calculateRewardInternal($order, $isUserVip) {

if($isUserVip) {
        return isset($order->coin_per_member) ? $order->coin_per_member : 1;
}

    $isOrderVip = $order->is_vip;
    $isBoosted = isset($order->boost_manual) && $order->boost_manual > 0;

if($isOrderVip && $isBoosted) {
        return 1.00;
} elseif ($isOrderVip) {
        return 0.90;
} elseif ($isBoosted) {
        return 0.85;
} else {
        return 0.75;
}

}


function sendPayment($chat_id, $title, $description, $payload, $provider_token, $prices, $photo_url = null)
{
    return BaleRequest('sendInvoice', [
        'chat_id' => $chat_id,
        'title' => $title,
        'description' => $description,
        'payload' => $payload,
        'provider_token' => $provider_token,
        'currency' => 'IRR',
        'prices' => json_encode($prices),
        'photo_url' => $photo_url
    ]);
}


function answerToPay($pre_checkout_query_id)
{
    return BaleRequest('answerPreCheckoutQuery', [
        'pre_checkout_query_id' => $pre_checkout_query_id,
        'ok' => true
    ]);
}


function formatCoins($amount)
{
    $amount = floatval($amount);
    $rounded = round($amount, 2);

if(abs($rounded - round($rounded)) < 0.00001) {
        return number_format((int) round($rounded), 0);
}

    $s = number_format($rounded, 2, '.', '');
    $s = rtrim(rtrim($s, '0'), '.');
    return $s;
}


function calcOrderExtraPaid($order)
{
    $membersCount = floatval($order->members_count ?? 0);

if($membersCount <= 0) return 0.0;
    $basePaid = floatval($order->coin_per_member ?? 0) * $membersCount;
    $totalPaid = floatval($order->total_cost ?? 0);
    $extra = $totalPaid - $basePaid;

if($extra < 0) $extra = 0;
    return $extra;
}


function calcOrderCancelRefund($order)
{
    $membersCount = floatval($order->members_count ?? 0);
    $membersDone = floatval($order->members_done ?? 0);
    $remaining = $membersCount - $membersDone;

if($remaining < 0) $remaining = 0;
    $baseRefund = $remaining * floatval($order->coin_per_member ?? 0);
    $extraPaid = calcOrderExtraPaid($order);
    $extraRefund = 0.0;

if($extraPaid > 0 && $membersCount > 0) {
        $extraRefund = $extraPaid * ($remaining / $membersCount);
}

    return [
        'remaining' => (int) $remaining,
        'base_refund' => $baseRefund,
        'extra_refund' => $extraRefund,
        'total_refund' => ($baseRefund + $extraRefund),
    ];
}


function showCoinHistory($chat_id, $page, $message_id = null) {
    global $pdo;
    $limit = 1;
    $offset = ($page - 1) * $limit;
    $stmt = $pdo->prepare("SELECT COUNT(*) as total FROM `coin_transactions` WHERE `user_id` = ? AND `status` = 'success'");
    $stmt->execute([$chat_id]);
    $total = $stmt->fetch()->total;

if($total == 0) {
        $msg = "📭 شما هنوز هیچ خرید سکه‌ای انجام نداده‌اید.";
        $keyboard = json_encode([
            "inline_keyboard" => [
                [['text' => '🔙 بازگشت به منو قبل', 'callback_data' => 'purchase_history']]
            ]
        ]);

if($message_id) {
            editMessage($chat_id, $message_id, $msg, $keyboard);
} else {
            sendMessage($chat_id, $msg, $keyboard);
}

        return;
}

    $stmt = $pdo->prepare("SELECT * FROM `coin_transactions` WHERE `user_id` = ? AND `status` = 'success' ORDER BY `created_at` DESC LIMIT $limit OFFSET $offset");
    $stmt->execute([$chat_id]);
    $transactions = $stmt->fetchAll();

if(empty($transactions)) {

if($page > 1) {
            showCoinHistory($chat_id, 1, $message_id);
            return;
}

}

    $trans = $transactions[0];
    $date = jdate("H:i  Y/m/d", strtotime($trans->created_at));
    $amount = number_format($trans->amount_coins);
    $price = number_format($trans->price_toman);
    $msg = "💎 *خرید سکه*\n\n" .
           "🔖 *کد سفارش:* *{$trans->order_number}*\n" .
           "💰 *تعداد:* *$amount* سکه\n" .
           "💵 *مبلغ:* *$price* تومان\n" .
           "📅 *تاریخ:* *$date*";
    $keyboard = [];
    $keyboard[] = [['text' => '📄 مشاهده جزئیات', 'callback_data' => "view_coin_details:{$trans->order_number}"]];
    $row2 = [];

if($page > 1) {
        $row2[] = ['text' => '➡️ قبلی', 'callback_data' => "history_coin_page:" . ($page - 1)];
}


if($page * $limit < $total) {
        $row2[] = ['text' => 'بعدی ⬅️', 'callback_data' => "history_coin_page:" . ($page + 1)];
}


if(!empty($row2)) {
        $keyboard[] = $row2;
}

    $keyboard[] = [['text' => '🔙 بازگشت به منو قبل', 'callback_data' => 'purchase_history']];
    $markup = ["inline_keyboard" => $keyboard];

if($message_id) {
        editMessage($chat_id, $message_id, $msg, json_encode($markup));
} else {
        sendMessage($chat_id, $msg, json_encode($markup));
}

}


function sendLogChannel($text)
{
    $logChannelId = settings('channel_reports_log');

if($logChannelId) {
        sendMessage($logChannelId, $text);
}

}

