
<?php
// ========================
// CONFIGURATION SECTION
// ========================
define('BOT_TOKEN', '8004112798:AAG7iPWxUqGW2EU-fPrD7p2Cx24x0KflwD0');
define('ADMIN_IDS', [111452882, 5045287497]);
define('API_URL', 'https://api.telegram.org/bot'.BOT_TOKEN.'/');
define('CHANNEL_ID', '@Airdrop_sah');
define('MAX_CAPTION_LENGTH', 2048);

// Database settings
define('DB_HOST', 'localhost:3306');
define('DB_USER', 'shirazw4_Airdrop_sah_bot'); 
define('DB_PASS', 'sB~xw(6%wJ5Wos,!');
define('DB_NAME', 'shirazw4_Airdrop_sah_bot');

// ========================
// FUNCTION DEFINITIONS
// ========================
function connectDB() {
    $db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    
    // بررسی خطاهای اتصال
    if ($db->connect_error) {
        error_log("Database connection failed: " . $db->connect_error);
        return false;
    }
    
    // بررسی اینکه اتصال واقعاً برقرار است
    if (!$db->ping()) {
        error_log("Database ping failed - connection is not active");
        $db->close();
        return false;
    }
    
    $db->set_charset("utf8mb4");
    return $db;
}

function isAdmin($user_id) {
    return in_array($user_id, ADMIN_IDS);
}

function sendMessage($chat_id, $text, $reply_to = null, $parse_mode = 'HTML') {
    $data = [
        'chat_id' => $chat_id,
        'text' => $text,
        'parse_mode' => $parse_mode,
        'reply_to_message_id' => $reply_to
    ];
    $url = API_URL . "sendMessage?" . http_build_query($data);
    return json_decode(file_get_contents($url), true);
}

function sendMessageWithKeyboard($chat_id, $text, $keyboard = null) {
    // اگر کیبورد null است، چیزی نفرست
    $reply_markup = $keyboard ? json_encode($keyboard) : '';

    $url = "https://api.telegram.org/bot" . BOT_TOKEN . "/sendMessage?"
         . http_build_query([
             'chat_id' => $chat_id,
             'text' => $text,
             'reply_markup' => $reply_markup,
             'parse_mode' => 'HTML'
         ]);

    file_get_contents($url);
}

// ---- منوی ادمین دو ردیفه ----
function getAdminKeyboard() {
    return [
        'keyboard' => [
            ['📋 نمایش هشتگ‌ها', 'ℹ️ راهنما'],
            ['🗑 حذف آخرین پست', '🗑 حذف پست با لینک یا شماره'],
        ],
        'resize_keyboard' => true
    ];
}

// حذف پست بر اساس message_id
function deleteChannelPost($message_id) {
    $data = [
        'chat_id' => CHANNEL_ID,
        'message_id' => $message_id
    ];
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, API_URL . "deleteMessage");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    
    $response = curl_exec($ch);
    curl_close($ch);
    
    return json_decode($response, true);
}
// گرفتن آخرین message_id پست کانال
function getLastChannelPostId() {
    $db = connectDB();
    if (!$db) return null;
    $res = $db->query("SELECT message_id FROM hashtag_posts2 ORDER BY id DESC LIMIT 1");
    $row = $res->fetch_assoc();
    $db->close();
    return $row['message_id'] ?? null;
}

function forwardMessageToChannels($original_message_id, $channels) {
    if (empty($channels)) return true;
    
    $channels = explode(',', $channels);
    $results = [];
    
    foreach ($channels as $channel) {
        $channel = trim($channel);
        if (empty($channel)) continue;
        
        $data = [
            'chat_id' => $channel,
            'from_chat_id' => CHANNEL_ID,
            'message_id' => $original_message_id
        ];
        
        $url = API_URL . "forwardMessage?" . http_build_query($data);
        $results[$channel] = json_decode(file_get_contents($url), true);
    }
    
    return $results;
}

function sendPhotoToChannelSafeWithReply($photo, $caption, $hashtag, $enable_reply = null) {
    $db = connectDB();
    if (!$db) return ['ok' => false, 'error' => 'DB error'];

    // گرفتن جدیدترین پیام قبلی
    $stmt = $db->prepare("SELECT message_id FROM hashtag_posts2 WHERE hashtag = ? ORDER BY id DESC LIMIT 1");
    $stmt->bind_param("s", $hashtag);
    $stmt->execute();
    $stmt->bind_result($previous_msg_id);
    $stmt->fetch();
    $stmt->close();

    $data = [
        'chat_id' => CHANNEL_ID,
        'photo' => $photo,
        'caption' => $caption,
        'parse_mode' => 'HTML'
    ];

    // اگر enable_reply مشخص نشده، از مقدار پیش‌فرض دیتابیس استفاده می‌کنیم
    if ($enable_reply === null) {
        $enable_reply = getReplyStatus($hashtag);
    }

    // تنظیم ریپلای فقط اگر پیام قبلی وجود داشته باشد و ریپلای فعال باشد
    if ($previous_msg_id && $enable_reply) {
        $data['reply_to_message_id'] = $previous_msg_id;
    }

    $ch = curl_init(API_URL . "sendPhoto");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $res = curl_exec($ch);
    $curl_error = curl_error($ch);
    curl_close($ch);

    if ($curl_error) {
        return ['ok' => false, 'error' => "CURL Error: $curl_error"];
    }

    $result = json_decode($res, true);

    // اگر خطای reply_to_message_id اتفاق افتاد
    if (!$result['ok'] && isset($result['description']) && 
        strpos($result['description'], 'message to be replied not found') !== false) {
        // پیام قبلی را پاک کرده و دوباره بدون ریپلای ارسال می‌کنیم
        $stmt = $db->prepare("DELETE FROM hashtag_posts2 WHERE message_id = ?");
        $stmt->bind_param("i", $previous_msg_id);
        $stmt->execute();
        $stmt->close();

        unset($data['reply_to_message_id']);
        
        $ch = curl_init(API_URL . "sendPhoto");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $res = curl_exec($ch);
        $curl_error = curl_error($ch);
        curl_close($ch);

        if ($curl_error) {
            return ['ok' => false, 'error' => "CURL Error: $curl_error"];
        }
        $result = json_decode($res, true);
    }

    if (!($result['ok'] ?? false)) return $result;

    $msg_id = $result['result']['message_id'];
    $post_url = "https://t.me/" . substr(CHANNEL_ID, 1) . "/$msg_id";

    // ذخیره پیام جدید با وضعیت ریپلای
    $stmt = $db->prepare("
        INSERT INTO hashtag_posts2 (hashtag, message_id, post_url, enable_reply)
        VALUES (?, ?, ?, ?)
        ON DUPLICATE KEY UPDATE 
            message_id = VALUES(message_id), 
            post_url = VALUES(post_url),
            enable_reply = VALUES(enable_reply)
    ");
    $enable_reply_value = $enable_reply ? 1 : 0;
    $stmt->bind_param("sisi", $hashtag, $msg_id, $post_url, $enable_reply_value);
    $stmt->execute();
    $stmt->close();

    $hashtag_data = getHashtagData($hashtag);
    if (!empty($hashtag_data['forward_channels'])) {
        $forward_results = forwardMessageToChannels($msg_id, $hashtag_data['forward_channels']);
        $result['forward_results'] = $forward_results;
    }

    $db->close();

    return $result;
}
function getReplyStatus($hashtag) {
    $db = connectDB();
    if (!$db) return true; // حالت پیش‌فرض فعال
    
    $stmt = $db->prepare("SELECT enable_reply FROM hashtag_posts2 WHERE hashtag = ? ORDER BY id DESC LIMIT 1");
    $stmt->bind_param("s", $hashtag);
    $stmt->execute();
    $stmt->bind_result($enable_reply);
    $stmt->fetch();
    $stmt->close();
    $db->close();
    
    return $enable_reply ?? true; // اگر مقداری وجود نداشت، پیش‌فرض فعال است
}

function setReplyStatusForHashtag($hashtag, $status) {
    $db = connectDB();
    if (!$db) return false;
    
    $status = $status ? 1 : 0;
    $stmt = $db->prepare("UPDATE hashtag_posts2 SET enable_reply = ? WHERE hashtag = ?");
    $stmt->bind_param("is", $status, $hashtag);
    $result = $stmt->execute();
    $affected = $stmt->affected_rows;
    $stmt->close();
    $db->close();
    
    return $affected > 0;
}

function toggleReplyStatusForHashtag($hashtag) {
    $current_status = getReplyStatus($hashtag);
    $new_status = !$current_status;
    
    return setReplyStatusForHashtag($hashtag, $new_status);
}

function getHashtagData($hashtag) {
    $db = connectDB();
    if (!$db) return null;
    $stmt = $db->prepare("SELECT * FROM hashtag_links WHERE hashtag = ?");
    $stmt->bind_param("s", $hashtag);
    $stmt->execute();
    $result = $stmt->get_result();
    $data = $result->fetch_assoc();
    $stmt->close();
    $db->close();
    return $data;
}
function extractPositions($text) {
    // گرفتن حداقل 3 عدد، جداکننده فقط -, •, ., ,, :, ; یا فاصله (نه / )
    if (preg_match('/(?:^|\s)(\d+(?:\s*[\-\•\.,:;]\s*\d+){2,})(?=\s|$)/u', $text, $matches, PREG_OFFSET_CAPTURE)) {
        // اگر شبیه تاریخ YYYY-MM-DD یا DD-MM-YYYY بود، ردش کن
        if (preg_match('/\b\d{4}[\-]\d{1,2}[\-]\d{1,2}\b/', $matches[1][0]) ||
            preg_match('/\b\d{1,2}[\-]\d{1,2}[\-]\d{4}\b/', $matches[1][0])) {
            return false;
        }

        // جدا کردن همه اعداد
        preg_match_all('/\d+/', $matches[1][0], $nums);
        $numbers = $nums[0];

        if (count($numbers) >= 3) {
            return [
                'formatted' => "<blockquote>🎯 Position: " . implode(' - ', $numbers) . " 👈</blockquote>",
                'original'  => $matches[0][0],
                'offset'    => $matches[0][1],
                'length'    => mb_strlen($matches[0][0])
            ];
        }
    }
    return false;
}

function processDate($text) {
    $date_patterns = [
        '/\b\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}\b/',
        '/\b\d{1,2}[\/\-]\d{1,2}[\/\-]\d{4}\b/',
        '/⏰\s*\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}\b/',
        '/⏰\s*\d{1,2}[\/\-]\d{1,2}[\/\-]\d{4}\b/',
        '/\bT\s*=\s*\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}\b/i',
        '/\bT\s*=\s*\d{1,2}[\/\-]\d{1,2}[\/\-]\d{4}\b/i'
    ];
    
    foreach ($date_patterns as $pattern) {
        if (preg_match($pattern, $text, $matches)) {
            $date_str = trim(str_replace(['⏰', 'T='], '', $matches[0]));
            return [
                'date' => $date_str,
                'original' => $matches[0]
            ];
        }
    }
    return false;
}

function processCodes($text) {
    $codes = [];
    $removals = [];
    
    // حالت‌های خاص code
    if (preg_match('/\b(all-code|123-code|12-code|13-code|23-code|1-code|2-code|3-code)\b/i', $text, $m_mode, PREG_OFFSET_CAPTURE)) {
        $codes['mode'] = strtolower($m_mode[1][0]);
        $removals[] = ['pos' => $m_mode[0][1], 'len' => strlen($m_mode[0][0])];
    }
    
    // پیدا کردن codeها
    if (preg_match_all('/\b(code|code2|code3)\s*:\s*([^\s#]+)/i', $text, $m_all, PREG_SET_ORDER | PREG_OFFSET_CAPTURE)) {
        foreach ($m_all as $m) {
            $key = strtolower($m[1][0]);
            $val = $m[2][0];
            $codes[$key] = $val;
            $removals[] = ['pos' => $m[0][1], 'len' => strlen($m[0][0])];
        }
    }
    
    // حذف بخش‌های پیدا شده از متن اصلی
    usort($removals, function($a, $b) { return $b['pos'] - $a['pos']; });
    foreach ($removals as $r) {
        $text = substr_replace($text, '', $r['pos'], $r['len']);
    }
    
    return [
        'codes' => $codes,
        'text' => trim(preg_replace('/\s+/', ' ', $text))
    ];
}

function showAllHashtags($chat_id) {
    $db = connectDB();
    if (!$db) return false;
    
    $result = $db->query("SELECT DISTINCT hashtag FROM hashtag_links ORDER BY hashtag");
    $hashtags = [];
    while ($row = $result->fetch_assoc()) {
        $hashtags[] = $row['hashtag'];
    }
    $db->close();
    
    if (empty($hashtags)) {
        return sendMessageWithKeyboard($chat_id, "هیچ هشتگی در پایگاه داده وجود ندارد.");
    }
    
    $message = "📌 لیست هشتگ‌های موجود:\n\n";
    foreach ($hashtags as $hashtag) {
        $message .= "🔹 <code>" . htmlspecialchars($hashtag) . "</code>  ($hashtag) \n";
    }
    $message .= "\nمی‌توانید هر هشتگ را برای کپی کردن انتخاب کنید.";
    
    return sendMessageWithKeyboard($chat_id, $message);
}
function getTelegramPostTemplate($hashtag) {
    $db = connectDB();
    if (!$db) return null;
    
    $stmt = $db->prepare("SELECT template FROM telegram_post WHERE hashtag = ? LIMIT 1");
    $stmt->bind_param("s", $hashtag);
    $stmt->execute();
    $result = $stmt->get_result();
    $data = $result->fetch_assoc();
    $stmt->close();
    $db->close();
    
    return $data['template'] ?? null;
}
function processMorseCode($text) {
    // الگو برای تشخیص خطوط مورس (حروف + : اختیاری + نمادها)
    $pattern = '/([A-Z])\s*:?[\s　]*(?:[●⚫️•·\.]|[━—–\-])(?:[\s　]*(?:[●⚫️•·\.]|[━—–\-]))*/u';

    // پیدا کردن تمام خطوطی که شبیه کد مورس هستند
    if (preg_match_all($pattern, strtoupper($text), $matches)) {
        $lines = [];
        $letters = [];

        foreach ($matches[0] as $rawLine) {
            // تمیز کردن فاصله‌ها
            $cleanLine = trim($rawLine);
            // تبدیل کاراکترها به فرم استاندارد
            $cleanLine = str_replace(
                ['⚫️','•','·','.'], '●',
                str_replace(['━','—','–','-'], '━', $cleanLine)
            );
            // اطمینان از وجود فاصله بین علامت‌ها
            $cleanLine = preg_replace('/(●|━)(?=●|━)/u', '$1 ', $cleanLine);

            // گرفتن حرف (قبل از :)
            if (preg_match('/^([A-Z])/', $cleanLine, $m)) {
                $letters[] = $m[1];
            }

            // اگر بعد از حرف دو نقطه نیست، اضافه کن
            if (!preg_match('/^([A-Z]):/', $cleanLine)) {
                $cleanLine = preg_replace('/^([A-Z])\s*/', '$1: ', $cleanLine);
            }

            $lines[] = $cleanLine;
        }

        // ساخت عنوان USD یا مشابه
        $title = implode('', $letters);
        $final = "Daily Cipher Code: {$title}\n" . implode("\n", $lines);

        return "<blockquote>" . $final . "</blockquote>\n\n";
    }

    return ''; // اگر چیزی پیدا نشد
}
// ---- ذخیره وضعیت انتظار حذف در فایل JSON ----
function setPendingDelete($chat_id) {
    $file = __DIR__ . '/pending_delete.json';
    $data = file_exists($file) ? json_decode(file_get_contents($file), true) : [];
    $data[$chat_id] = true;
    file_put_contents($file, json_encode($data));
}

function isPendingDelete($chat_id) {
    $file = __DIR__ . '/pending_delete.json';
    if (!file_exists($file)) return false;
    $data = json_decode(file_get_contents($file), true);
    return !empty($data[$chat_id]);
}

function clearPendingDelete($chat_id) {
    $file = __DIR__ . '/pending_delete.json';
    if (!file_exists($file)) return;
    $data = json_decode(file_get_contents($file), true);
    unset($data[$chat_id]);
    file_put_contents($file, json_encode($data));
}
// === NEW: oktext line parser ===
function parseOkTextBlock($text, $force = false) {
    // اگر اجباری نیست و oktext در متن نیست، بی‌خیال
    if (!$force && !preg_match('/\boktext\b/i', $text)) {
        return ['found' => false];
    }

    // اگر اجباری نبود، بعد از اولین oktext رو بگیر
    if (!$force) {
        $parts = preg_split('/\boktext\b/i', $text, 2);
        $before = isset($parts[0]) ? rtrim($parts[0]) : '';
        $after  = isset($parts[1]) ? ltrim($parts[1])  : '';
    } else {
        // مود اجباری یعنی کل متن، بلوک oktext محسوب بشه
        $before = '';
        $after  = $text;
    }

    return [
        'found'     => true,
        'html'      => trim($after), // متن را بدون تغییر برمی‌گردانیم
        'remaining' => rtrim($before) // بقیهٔ متن برای پردازش‌های بعدی
    ];
}
function parseOkCodeBlock($text, $force = false, $db_data = null) {
    // ایموجی از db_data بگیر یا پیش‌فرض 📌
    $box_emoji = !empty($db_data['emoji']) ? trim($db_data['emoji']) : '📌';
    
    // تنظیمات استایل border
    $border_style = !empty($db_data['border_style']) ? $db_data['border_style'] : 'dash';
    
    // استایل‌های مختلف border
    $styles = [
        'dash' => [ // استایل با خط تیره (➖)
            'horizontal' => '➖',
            'vertical' => '',
            'top_left' => '╔',
            'top_right' => '╗',
            'bottom_left' => '╚',
            'bottom_right' => '╝',
            'name' => 'خط تیره'
        ],
        'line' => [ // استایل با خط معمولی (─)
            'horizontal' => '─',
            'vertical' => '│',
            'top_left' => '╭',
            'top_right' => '╮',
            'bottom_left' => '╰',
            'bottom_right' => '╯',
            'name' => 'خط ساده'
        ],
        'double' => [ // استایل دوبل
            'horizontal' => '═',
            'vertical' => '║',
            'top_left' => '╔',
            'top_right' => '╗',
            'bottom_left' => '╚',
            'bottom_right' => '╝',
            'name' => 'دوبل'
        ],
        'bold' => [ // استایل ضخیم
            'horizontal' => '━',
            'vertical' => '┃',
            'top_left' => '┏',
            'top_right' => '┓',
            'bottom_left' => '┗',
            'bottom_right' => '┛',
            'name' => 'ضخیم'
        ],
        'star' => [ // استایل ستاره‌ای
            'horizontal' => '✧',
            'vertical' => '│',
            'top_left' => '✦',
            'top_right' => '✦',
            'bottom_left' => '✦',
            'bottom_right' => '✦',
            'name' => 'ستاره‌ای'
        ],
        'dot' => [ // استایل نقطه‌ای
            'horizontal' => '•',
            'vertical' => '│',
            'top_left' => '‧',
            'top_right' => '‧',
            'bottom_left' => '‧',
            'bottom_right' => '‧',
            'name' => 'نقطه‌ای'
        ],
        'arrow' => [ // استایل پیکانی
            'horizontal' => '➖',
            'vertical' => '│',
            'top_left' => '↘',
            'top_right' => '↙',
            'bottom_left' => '↗',
            'bottom_right' => '↖',
            'name' => 'پیکانی'
        ]
    ];
    
    // انتخاب استایل یا پیش‌فرض
    $style = isset($styles[$border_style]) ? $styles[$border_style] : $styles['dash'];
    
    // تنظیمات ابعاد
    $min_width = !empty($db_data['min_width']) ? (int)$db_data['min_width'] : 5;
    $max_width = !empty($db_data['max_width']) ? (int)$db_data['max_width'] : 10;
    
    // اگر اجباری نیست و okcode در متن نیست، بی‌خیال
    if (!$force && !preg_match('/\bokcode\b/i', $text)) {
        return ['found' => false];
    }

    // جدا کردن متن
    if (!$force) {
        $parts = preg_split('/\bokcode\b/i', $text, 2);
        $before = isset($parts[0]) ? rtrim($parts[0]) : '';
        $after  = isset($parts[1]) ? ltrim($parts[1])  : '';
    } else {
        $before = '';
        $after  = $text;
    }

    // پردازش خطوط
    $lines = preg_split("/\r\n|\r|\n/", $after);
    $out = [];
    $all_lines_for_box = [];
    $code_parts = [];
    $text_parts = [];

    foreach ($lines as $ln) {
        if ($ln === '') { 
            $out[] = ''; 
            $all_lines_for_box[] = '';
            $code_parts[] = '';
            $text_parts[] = '';
            continue; 
        }

        $parts = explode('|', $ln, 2);

        // پاکسازی
        if (isset($parts[0])) {
            $parts[0] = preg_replace('/\x{00A0}|\x{2000}-\x{200B}|\x{202F}|\x{205F}|\x{3000}/u', ' ', $parts[0]);
        }
        if (isset($parts[1])) {
            $parts[1] = preg_replace('/\x{00A0}|\x{2000}-\x{200B}|\x{202F}|\x{205F}|\x{3000}/u', ' ', $parts[1]);
        }

        $code = isset($parts[0]) ? trim($parts[0]) : '';
        $codeEsc = htmlspecialchars($code, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
        $text = isset($parts[1]) ? trim($parts[1]) : '';
        $textEsc = htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');

        if ($text !== '') {
            $line_text = "<code>{$codeEsc}</code> | {$textEsc}";
            $clean_line = "{$code} | {$text}";
        } else {
            $line_text = "<code>{$codeEsc}</code>";
            $clean_line = $code;
        }
        
        $out[] = $line_text;
        $all_lines_for_box[] = $clean_line;
        $code_parts[] = $code;
        $text_parts[] = $text;
    }

    if (empty($all_lines_for_box)) {
        return ['found' => false];
    }
    
    // ========== محاسبه ابعاد ==========
    
    // طول بلندترین خط
    $max_length = 0;
    foreach ($all_lines_for_box as $line) {
        $line_length = mb_strlen($line, 'UTF-8');
        $max_length = max($max_length, $line_length);
    }
    
    $emoji_length = mb_strlen($box_emoji, 'UTF-8');
    $padding_after_emoji = 2;
    $side_padding = 2;
    
    $required_width = $emoji_length + $padding_after_emoji + $max_length + $side_padding;
    $box_width = max(min($required_width, $max_width), $min_width);
    
    // ساخت border
    $border = str_repeat($style['horizontal'], $box_width);
    
    // ========== ساخت خروجی HTML ==========
    $html_output = "";
    
    // هدر با ایموجی‌های تزئینی
    $decorative_emojis = !empty($db_data['header_emojis']) ? $db_data['header_emojis'] : '🌟💫';
    $html_output .= "{$decorative_emojis}{$style['top_left']}{$border}{$style['top_right']}\n";
    
    foreach ($code_parts as $index => $code) {
        $text = $text_parts[$index];
        $clean_line = $all_lines_for_box[$index];
        
        if ($code === '' && $text === '') {
            // خط خالی
            $html_output .= "{$style['vertical']}{$box_emoji}\n";
        } elseif ($text !== '') {
            // خط با کد و متن
            $current_length = mb_strlen($clean_line, 'UTF-8');
            $spaces_needed = max(0, $box_width - ($emoji_length + 2 + $current_length + 1));
            
            $html_output .= "{$style['vertical']}{$box_emoji}  <code>{$code}</code> | {$text}";
            if ($spaces_needed > 0) {
                $html_output .= str_repeat(' ', $spaces_needed);
            }
            $html_output .= "{$style['vertical']}\n";
        } else {
            // فقط کد
            $current_length = mb_strlen($clean_line, 'UTF-8');
            $spaces_needed = max(0, $box_width - ($emoji_length + 2 + $current_length + 1));
            
            $html_output .= "{$style['vertical']}{$box_emoji}  <code>{$code}</code>";
            if ($spaces_needed > 0) {
                $html_output .= str_repeat(' ', $spaces_needed);
            }
            $html_output .= "{$style['vertical']}\n";
        }
    }
    
    $html_output .= "{$style['bottom_left']}{$border}{$style['bottom_right']}";
    
    // ========== نسخه متنی ساده ==========
    $text_output = "";
    $text_output .= "{$decorative_emojis}{$style['top_left']}{$border}{$style['top_right']}\n";
    
    foreach ($all_lines_for_box as $clean_line) {
        if ($clean_line === '') {
            $text_output .= "{$style['vertical']}{$box_emoji}\n";
        } else {
            $current_length = mb_strlen($clean_line, 'UTF-8');
            $total_needed = $emoji_length + 2 + $current_length;
            $remaining_space = $box_width - $total_needed + 1;
            
            $text_output .= "{$style['vertical']}{$box_emoji}  {$clean_line}";
            if ($remaining_space > 0) {
                $text_output .= str_repeat(' ', $remaining_space);
            }
            $text_output .= "{$style['vertical']}\n";
        }
    }
    
    $text_output .= "{$style['bottom_left']}{$border}{$style['bottom_right']}";

    return [
        'found'     => true,
        'html'      => $html_output,
        'text'      => $text_output,
        'remaining' => rtrim($before),
        'style'     => $style['name'],
        'dimensions' => [
            'width' => $box_width,
            'lines' => count($all_lines_for_box)
        ]
    ];
}

// تابع کمکی برای دریافت لیست استایل‌های موجود
function getAvailableBorderStyles() {
    return [
        'dash'   => '┌➖➖➖┐ (خط تیره)',
        'line'   => '╭───╮ (خط ساده)',
        'double' => '╔═══╗ (دوبل)',
        'bold'   => '┏━━━┓ (ضخیم)',
        'star'   => '✦✧✧✧✦ (ستاره‌ای)',
        'dot'    => '‧•••‧ (نقطه‌ای)',
        'arrow'  => '↘➖➖↙ (پیکانی)'
    ];
}
function editLastChannelPost($hashtag, $new_caption, $new_photo = null, $enable_reply = null) {
    $db = connectDB();
    if (!$db) {
        error_log("Failed to connect to database in editLastChannelPost");
        return ['ok' => false, 'error' => 'Database connection failed'];
    }
    
    // پیدا کردن آخرین پست برای این هشتگ
    $query = "SELECT message_id, enable_reply FROM hashtag_posts2 WHERE hashtag = ? ORDER BY id DESC LIMIT 1";
    $stmt = $db->prepare($query);
    
    if (!$stmt) {
        error_log("Prepare failed for query: $query - Error: " . $db->error);
        $db->close();
        return ['ok' => false, 'error' => 'Prepare failed: ' . $db->error];
    }
    
    if (!$stmt->bind_param("s", $hashtag)) {
        error_log("Bind param failed for hashtag: $hashtag");
        $stmt->close();
        $db->close();
        return ['ok' => false, 'error' => 'Bind param failed'];
    }
    
    if (!$stmt->execute()) {
        error_log("Execute failed: " . $stmt->error);
        $stmt->close();
        $db->close();
        return ['ok' => false, 'error' => 'Execute failed: ' . $stmt->error];
    }
    
    // فقط 2 متغیر چون فقط 2 فیلد انتخاب کردیم
    $stmt->bind_result($message_id, $current_reply_status);
    $stmt->fetch();
    $stmt->close();
    
    if (!$message_id) {
        $db->close();
        error_log("No post found for hashtag: $hashtag");
        return ['ok' => false, 'error' => 'No post found for this hashtag'];
    }
    
    // اگر enable_reply مشخص نشده، از مقدار فعلی استفاده کن
    if ($enable_reply === null) {
        $enable_reply = $current_reply_status;
    }
    
    $result = [];
    
    // اگر عکس جدید ارائه شده، از editMessageMedia استفاده کن
    if ($new_photo) {
        $data = [
            'chat_id' => CHANNEL_ID,
            'message_id' => $message_id,
            'media' => json_encode([
                'type' => 'photo',
                'media' => $new_photo,
                'caption' => $new_caption,
                'parse_mode' => 'HTML'
            ])
        ];
        
        $ch = curl_init(API_URL . "editMessageMedia");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $res = curl_exec($ch);
        $curl_error = curl_error($ch);
        curl_close($ch);
        
        if ($curl_error) {
            $db->close();
            error_log("CURL Error in editMessageMedia: $curl_error");
            return ['ok' => false, 'error' => "CURL Error: $curl_error"];
        }
        
        $result = json_decode($res, true);
        
        // اگر ویرایش رسانه موفق بود، وضعیت reply را در دیتابیس ذخیره کن
        if ($result['ok']) {
            $update_stmt = $db->prepare("UPDATE hashtag_posts2 SET enable_reply = ? WHERE message_id = ?");
            if (!$update_stmt) {
                error_log("Prepare failed for UPDATE: " . $db->error);
                $db->close();
                return $result;
            }
            
            $update_stmt->bind_param("ii", $enable_reply, $message_id);
            $update_stmt->execute();
            $update_stmt->close();
        }
    } else {
        // فقط ویرایش کپشن
        $data = [
            'chat_id' => CHANNEL_ID,
            'message_id' => $message_id,
            'caption' => $new_caption,
            'parse_mode' => 'HTML'
        ];
        
        $ch = curl_init(API_URL . "editMessageCaption");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $res = curl_exec($ch);
        $curl_error = curl_error($ch);
        curl_close($ch);
        
        if ($curl_error) {
            $db->close();
            error_log("CURL Error in editMessageCaption: $curl_error");
            return ['ok' => false, 'error' => "CURL Error: $curl_error"];
        }
        
        $result = json_decode($res, true);
        
        // اگر ویرایش کپشن موفق بود، وضعیت reply را در دیتابیس ذخیره کن
        if ($result['ok']) {
            $update_stmt = $db->prepare("UPDATE hashtag_posts2 SET enable_reply = ? WHERE message_id = ?");
            if (!$update_stmt) {
                error_log("Prepare failed for UPDATE: " . $db->error);
                $db->close();
                return $result;
            }
            
            $update_stmt->bind_param("ii", $enable_reply, $message_id);
            $update_stmt->execute();
            $update_stmt->close();
        }
    }
    
    $db->close();
    return $result;
}
// ========================
// MAIN BOT LOGIC
// ========================
$content = file_get_contents("php://input");
$update = json_decode($content, true);

if ($update && isset($update['message'])) {
    $message = $update['message'];
    $user_id = $message['from']['id'];
    $chat_id = $message['chat']['id'];

    if (!isAdmin($user_id)) {
        sendMessage($chat_id, "⛔ You don't have permission to post.");
        exit;
    }

    if (isset($message['text']) && (
        $message['text'] === '/showhashtags' || 
        mb_strpos($message['text'], 'نمایش هشتگ‌ها') !== false
    )) {
        showAllHashtags($chat_id);
        exit;
    }

    if (isset($message['text']) && ($message['text'] === '/start' || strtolower($message['text']) === '/start')) {
        if (isAdmin($user_id)) {
            sendMessageWithKeyboard($chat_id, "📌 منوی ادمین به‌روزرسانی شد.", getAdminKeyboard());
        } else {
            sendMessage($chat_id, "👋 سلام! به ربات خوش آمدید.");
        }
        exit;
    }

    if (isset($message['text'])) {
        $cmd = trim($message['text']);
        
        // حذف آخرین پست
        if ($cmd === '🗑 حذف آخرین پست') {
            $last_id = getLastChannelPostId();
            if ($last_id) {
                $del = deleteChannelPost($last_id);
                if (!empty($del['ok'])) {
                    sendMessageWithKeyboard($chat_id, "✅ آخرین پست با موفقیت حذف شد.", getAdminKeyboard());
                } else {
                    sendMessageWithKeyboard($chat_id, "⚠️ حذف پست انجام نشد.", getAdminKeyboard());
                }
            } else {
                sendMessageWithKeyboard($chat_id, "⚠️ پستی برای حذف یافت نشد.", getAdminKeyboard());
            }
            exit;
        }

        // حذف پست با لینک یا شماره
        if ($cmd === '🗑 حذف پست با لینک یا شماره') {
            sendMessageWithKeyboard($chat_id, "🔹 لطفاً لینک کامل پست یا شماره پیام را ارسال کنید.", getAdminKeyboard());
            setPendingDelete($chat_id);
            exit;
        }

        // اگر منتظر شماره یا لینک پست هستیم
        if (isPendingDelete($chat_id)) {
            clearPendingDelete($chat_id);
            $input = trim($cmd);
            $post_id = null;

            if (is_numeric($input)) {
                $post_id = (int)$input;
            } elseif (preg_match('#/(\d+)$#', $input, $m)) {
                $post_id = (int)$m[1];
            }

            if ($post_id) {
                $del = deleteChannelPost($post_id);
                if (!empty($del['ok'])) {
                    sendMessageWithKeyboard($chat_id, "✅ پست شماره {$post_id} حذف شد.", getAdminKeyboard());
                } else {
                    sendMessageWithKeyboard($chat_id, "⚠️ حذف پست انجام نشد.", getAdminKeyboard());
                }
            } else {
                sendMessageWithKeyboard($chat_id, "⚠️ شماره پیام یا لینک معتبر نیست.", getAdminKeyboard());
            }
            exit;
        }

        // راهنما
        if ($cmd === 'ℹ️ راهنما') {
            $help_text = "<b>📌 راهنمای ربات ادمین(سرور 1):</b>\n\n";
            $help_text .= "• 📋 <b>نمایش هشتگ‌ها</b> — لیست هشتگ‌های ثبت‌شده در دیتابیس رو به شما نمایش می‌دهد.\n";
            $help_text .= "• 🗑 <b>حذف آخرین پست</b> — آخرین پost ارسال‌شده در کانال رو حذف می‌کنه.\n";
            $help_text .= "• 🗑 <b>حذف پست با لینک یا شماره</b> — با دادن لینک کامل پست یا شماره پیام، پست مورد نظر حذف می‌شود.\n";
            $help_text .= "• 📝 <b>ارسال دستی مطلب به کانال</b> — ارسال پست به کانال اصلی.\n";
            $help_text .= "• 📝 <b>ارسال دستی مطلب به کانال 2</b> — ارسال پست به کانال دوم.\n";
            $help_text .= "• ℹ️ <b>راهنما</b> — نمایش راهنمای ربات و دستوراتی که می‌توان به ربات ارسال کرد.\n\n";
            $help_text .= "<b>🔥 نحوه ارسال پست‌ها:</b>\n\n";
            $help_text .= "1. <b>ارسال هشتگ‌ها با کد okcode:</b>\n";
            $help_text .= "   وقتی می‌خواهید هشتگ‌ها همراه با کدهای خاص ارسال بشن، باید به این شکل پست ارسال کنید:\n";
            $help_text .= "<code>#MoneyBux okcode\nLtX3Ept26B | 10,000 Gold</code>\n\n";
            $help_text .= "2. <b>ارسال نقل قول و سوال روزانه:</b>\n";
            $help_text .= "   - <b>با کدگذاری:</b>\n";
            $help_text .= "<code>#MemHustle code: Gwei 1-code</code>\n";
            $help_text .= "   - <b>بدون کدگذاری:</b>\n";
            $help_text .= "<code>#MemHustle code: Gwei</code>\n";
            $help_text .= "<code>code2: Gwei</code>\n\n";
            $help_text .= "3. <b>ارسال موقعیت‌ها:</b>\n";
            $help_text .= "   موقعیت‌های عددی به چند شکل قابل ارسال هستند:\n";
            $help_text .= "<code>1-2-3-4</code>\n";
            $help_text .= "<code>1 - 2 - 3 - 4</code>\n";
            $help_text .= "<code>1,2,3,4</code>\n\n";
            $help_text .= "4. <b>سوالات روزانه و چندکلمه‌ای‌ها:</b>\n";
            $help_text .= "   اگر سوال روز یا هر عبارت دو یا چندکلمه‌ای باشد، باید بین هر کلمه از علامت <code>+</code> استفاده کنید:\n";
            $help_text .= "<code>#DailyQuestion code: Best+Investment</code>\n\n";
            $help_text .= "5. <b>ارسال عکس (در صورت عدم وجود عکس در دیتابیس):</b>\n";
            $help_text .= "   اگر دیتابیس شامل تصویر باشد، نیاز به ارسال عکس جداگانه نیست و ربات خودکار تصویر را ارسال خواهد کرد.\n";

            sendMessageWithKeyboard($chat_id, $help_text, getAdminKeyboard());
            exit;
        }
    }

    $text = isset($message['caption']) ? $message['caption'] : ($message['text'] ?? '');
    $hashtag = '';

    // بررسی وجود okedit در متن
    $okedit_mode = false;
    if (preg_match('/\bokedit\b/i', $text)) {
        $okedit_mode = true;
        // حذف okedit از متن
        $text = preg_replace('/\bokedit\b/i', '', $text);
        $text = trim($text);
    }

    if (preg_match('/#(\w+)/', $text, $matches)) {
        $hashtag = '#' . $matches[1];
        $text = str_replace($hashtag, '', $text);
        $text = trim($text);
    } elseif (preg_match('/\bdropee\b/i', $text)) {
        $hashtag = '#dropee';
    }

    // پردازش همزمان oktext و okcode
    $oktextBlock = parseOkTextBlock($text);
    $okcodeBlock = parseOkCodeBlock($text);

    $processed_caption = '';
    $remaining_text = $text;
    $codes = []; // مقدار پیش‌فرض

    // پردازش همزمان هر دو بلوک اگر وجود دارند
    if ($oktextBlock['found']) {
        $processed_caption .= $oktextBlock['html'] . "\n\n";
        $remaining_text = $oktextBlock['remaining'];
    }

    if ($okcodeBlock['found']) {
        $processed_caption .= $okcodeBlock['html'] . "\n\n";
        $remaining_text = $okcodeBlock['remaining'];
    }

    // اگر هیچکدام پیدا نشدند، پردازش عادی انجام شود
    if (!$oktextBlock['found'] && !$okcodeBlock['found']) {
        // 1. پردازش موقعیت‌های عددی (قبل از پردازش تاریخ)
        $position_data = extractPositions($remaining_text);
        if ($position_data) {
            $processed_caption .= $position_data['formatted'] . "\n";
            $remaining_text = str_replace($position_data['original'], '', $remaining_text);
            $remaining_text = preg_replace('/^\s*-\s*\d+\s*$/m', '', $remaining_text);
            $remaining_text = trim($remaining_text);
        }

        // 2. پردازش تاریخ
        $date_data = processDate($remaining_text);
        $display_date = $date_data ? $date_data['date'] : date('Y/m/d');
        if ($date_data) {
            $remaining_text = str_replace($date_data['original'], '', $remaining_text);
            $remaining_text = trim($remaining_text);
        }

        // 3. پردازش کدها
        $code_result = processCodes($remaining_text);
        $remaining_text = $code_result['text'];
        $codes = $code_result['codes'];

        // 3.1 پردازش کد مورس
        $morse_block = processMorseCode($remaining_text); 
        if (!empty($morse_block)) {
            $processed_caption .= $morse_block;
            $remaining_text = preg_replace('/([A-Z])\s*:?[\s　]*(?:[●⚫️•·\.]|[━—–\-])(?:[\s　]*(?:[●⚫️•·\.]|[━—–\-]))*/u', '', $remaining_text);
            $remaining_text = trim($remaining_text);
        }

        // 4. پردازش لیست‌های عددی
        if (preg_match_all('/\d{1,2}[).]\s?.+?(?=\n|$)/', $remaining_text, $matches)) {
            $list_lines = array_map(function($item) {
                return preg_replace('/(\d{1,2})[.)]/', '$1)', $item);
            }, $matches[0]);
            
            $processed_caption .= implode("\n", $list_lines) . "\n\n";
            $remaining_text = str_replace($matches[0], '', $remaining_text);
            $remaining_text = trim($remaining_text);
        }

        // 5. پردازش متن باقیمانده
        $remaining_text = trim(preg_replace('/\s+/', ' ', $remaining_text));
        if (!empty($remaining_text)) {
            $processed_caption .= $remaining_text . "\n\n";
        }
    } else {
        // اگر oktext یا okcode وجود داشت، تاریخ را جداگانه پردازش کن
        $date_data = processDate($remaining_text);
        $display_date = $date_data ? $date_data['date'] : date('Y/m/d');
        if ($date_data) {
            $remaining_text = str_replace($date_data['original'], '', $remaining_text);
            $remaining_text = trim($remaining_text);
        }
    }

    // 6. پردازش هشتگ و داده‌های دیتابیس
    $remaining_text = preg_replace('/#\w+/', '', $remaining_text);
    $remaining_text = trim($remaining_text);

    // گرفتن داده از جدول hashtag_links
    $db_data = !empty($hashtag) ? getHashtagData($hashtag) : [];
    $combo_text = !empty($db_data['combo']) ? $db_data['combo'] : 'Daily Combo';

    // اضافه کردن متن پیش‌فرض از فیلد telegram_post همین جدول
    if (!empty($db_data['telegram_post'])) {
        if (!empty($processed_caption)) {
            $processed_caption .= "\n" . $db_data['telegram_post'];
        } else {
            $processed_caption = $db_data['telegram_post'];
        }
    }

    // بررسی وجود عکس در پیام یا دیتابیس
    $photo = isset($message['photo']) ? end($message['photo'])['file_id'] : ($db_data['image_url'] ?? null);

    // 7. ساخت کپشن نهایی
    $final_caption = "✨ $hashtag $combo_text ⏰ " . $display_date . " ✨\n\n";
    $final_caption .= trim($processed_caption);
// اضافه کردن کدها
// اضافه کردن کدها
function wrap_text($text, $length = 20) {
    return trim(chunk_split($text, $length, "\n"));
}

// تنظیم اندازه کادر بر اساس طول متن (بدون فضا)
function get_box_size($text, $small_limit = 10, $large_limit = 20) {
    // حذف فاصله‌ها از متن و سپس محاسبه طول واقعی
    $text = str_replace(' ', '', $text);  // حذف فاصله‌ها
    $text_length = strlen($text);  // محاسبه طول متن بدون فضا

    if ($text_length > $large_limit) {
        return "large";  // اگر طول متن بیشتر از 20 کاراکتر باشد
    } elseif ($text_length <= $small_limit) {
        return "small";  // اگر طول متن کمتر از 10 کاراکتر باشد
    }
    return "medium";  // بین این دو مقدار
}

$order = ['code','code2','code3'];
$codes_texts = [];

foreach ($order as $k) {
    if (!empty($codes[$k])) {
        $label = !empty($db_data[$k]) ? $db_data[$k] : ucfirst($k);
        
        // پیش‌فرض مقدار بدون <code>
        $value = $codes[$k];
        // جایگزینی + با فاصله
        $value = str_replace('+', ' ', $value);
        // بررسی mode برای <code>
        $need_code_tag = false;
        if (!empty($codes['mode'])) {
            $mode = $codes['mode'];
            $need_code_tag =
                ($mode === 'all-code') ||
                ($mode === '1-code'   && $k === 'code') ||
                ($mode === '2-code'   && $k === 'code2') ||
                ($mode === '3-code'   && $k === 'code3') ||
                ($mode === '12-code'  && in_array($k, ['code','code2'])) ||
                ($mode === '13-code'  && in_array($k, ['code','code3'])) ||
                ($mode === '23-code'  && in_array($k, ['code2','code3'])) ||
                ($mode === '123-code' && in_array($k, ['code','code2','code3']));
            
            if ($need_code_tag) {
                $value = "<code>{$value}</code>";
            }
        }

        // فقط اگر <code> نیست، متن طولانی رو wrap کن
        if (!$need_code_tag) {
            $value = wrap_text($value, 20);
        }

        $emoji = !empty($db_data['emoji']) ? trim($db_data['emoji']) : '📌';
        $codes_texts[] = "<b>{$emoji} {$label}:</b> {$value}";    
    }
}
// ========================
// تنظیمات کادر کدها (همه تغییرات اینجا)
// ========================
$box_config = [
    // استایل گوشه‌ها و خطوط:
    // 'rounded' = ╭ ╮ ╰ ╯ با خط ─
    // 'sharp'   = ┌ ┐ └ ┘ با خط ─
    // 'double'  = ╔ ╗ ╚ ╝ با خط ═
    // 'bold'    = ┏ ┓ ┗ ┛ با خط ━
    // 'dot'     = ┌ ┐ └ ┘ با خط •
    'style' => 'rounded',  // 👈 استایل رو اینجا عوض کن

    'emoji_header' => '🌟💫',   // ایموجی بالای کادر
    'emoji_line'   => '💎',     // ایموجی ابتدای هر خط
    'padding'      => 2,        // فاصله اضافی سمت راست
    'min_width'    => 13,       // حداقل عرض کادر
    'max_width'    => 15,       // حداکثر عرض کادر (0 = نامحدود)
    'separator'    => true,     // جداکننده بین کادرها (true/false)
];

// تعریف استایل‌ها
$box_styles = [
    'rounded' => ['tl' => '╭', 'tr' => '╮', 'bl' => '╰', 'br' => '╯', 'h' => '─'],
    'sharp'   => ['tl' => '┌', 'tr' => '┐', 'bl' => '└', 'br' => '┘', 'h' => '─'],
    'double'  => ['tl' => '╔', 'tr' => '╗', 'bl' => '╚', 'br' => '╝', 'h' => '═'],
    'bold'    => ['tl' => '┏', 'tr' => '┓', 'bl' => '┗', 'br' => '┛', 'h' => '━'],
    'dot'     => ['tl' => '┌', 'tr' => '┐', 'bl' => '└', 'br' => '┘', 'h' => '•'],
];

// انتخاب استایل
$s = $box_styles[$box_config['style']] ?? $box_styles['dot'];

// ========================
// ساخت کادر
// ========================
if (!empty($codes_texts)) {
    $count = count($codes_texts);
    
    // محاسبه طول خطوط
    $max_length = $box_config['min_width'];
    foreach ($codes_texts as $txt) {
        $clean_txt = strip_tags($txt);
        $max_length = max($max_length, strlen($clean_txt));
    }
    
    // اعمال حداکثر عرض
    if ($box_config['max_width'] > 0) {
        $max_length = min($max_length, $box_config['max_width']);
    }
    
    // محاسبه عرض نهایی
    $box_width = $max_length + $box_config['padding'];
    $horizontal = str_repeat($s['h'], $box_width);
    
    // ایموجی‌ها
    $eh = $box_config['emoji_header'];
    $el = $box_config['emoji_line'];
    
    // ساخت کادر
    $box = "{$eh}{$s['tl']}{$horizontal}{$s['tr']}\n";
    
    foreach ($codes_texts as $i => $txt) {
        $lines = explode("\n", $txt);
        foreach ($lines as $line) {
            $clean_line = strip_tags($line);
            $space_count = $box_width - strlen($clean_line);
            $box .= "{$el}  {$line}" . str_repeat(' ', max(0, $space_count)) . "\n";
        }
        
        // جداکننده بین کادرها
        if ($box_config['separator'] && $i < $count - 1) {
            $box .= "{$s['bl']}{$horizontal}{$s['br']}\n";
            $box .= "{$eh}{$s['tl']}{$horizontal}{$s['tr']}\n";
        }
    }
    
    $box .= "{$s['bl']}{$horizontal}{$s['br']}";
    $final_caption .= "\n" . $box;
}


    
    // اضافه کردن لینک‌های سفارشی
    if (!empty($db_data['additional_links'])) {
        $links = explode('|', $db_data['additional_links']);
        $custom_links = '';
        foreach ($links as $link) {
            $link = trim($link);
            if (preg_match('/^(.+?)\s*\((https?:\/\/[^)]+)\)/', $link, $matches)) {
                $title = trim($matches[1]);
                $url = trim($matches[2]);
                $custom_links .= "<a href=\"$url\">$title</a> | ";
            }
        }
        $custom_links = rtrim($custom_links, '| ');
        $final_caption .= "\n\n<blockquote>" . $custom_links."</blockquote>";
    }
    
    // اضافه کردن لینک اصلی
    if (!empty($db_data['link'])) {
        $button_text = str_replace('#', '', $hashtag);
        $final_caption .= "\n\n" . $db_data['link'];
        $final_caption .= "\n<blockquote expandable>🚀 Launch 👉 <a href=\"{$db_data['link']}\">$button_text</a>";
        
        if (!empty($db_data['general_hashtags'])) {
            $final_caption .= "\n\n\n\n\n\n\n\n\n\n\n\n" . $db_data['general_hashtags'];
        }
        
        $final_caption .= "</blockquote>";
    }
    
    // اضافه کردن متن سفارشی
    if (!empty($db_data['additional_text'])) {
        $final_caption .= "\n\n" . $db_data['additional_text'];
    }
/*    
// اضافه کردن بخش MetaMask به صورت زیبا
if (strpos($final_caption, '@MetaMask Season 1 Rewards') === false) {
    $metamask_section = "\n🦊 <b>MetaMask Season 1 Rewards</b> ★ <code>$30,000,000</code>
├─ 🔗 <a href=\"https://link.metamask.io/rewards?referral=26FECP\">Claim Rewards</a>
└─ 📚 <a href=\"https://t.me/Airdrop_sah/31742\">Full Guide</a>";
    
    $final_caption .= $metamask_section;
}
        $final_caption .= "</blockquote>";
*/
/* 
 $final_caption .= "\n<blockquote expandable>";
  
// اضافه کردن بخش MetaMask به صورت زیبا
if (strpos($final_caption, '@MetaMask Season 1 Rewards') === false) {
    $metamask_section = "\n🦊 <b>MetaMask S1 Rewards</b>|<a href=\"https://link.metamask.io/rewards?referral=26FECP\">Claim Rewards</a>|📚 <a href=\"https://t.me/Airdrop_sah/31742\">Full Guide</a>";
    
    $final_caption .= $metamask_section;
}
        $final_caption .= "</blockquote>";
*/
// اضافه کردن Daily Combo
// Adding 3 formatted links
$final_caption .= "\n" .
    "<a href='https://t.me/+6gS598R7J00zZjE0'>📬 Daily Combo</a> • " .
    "<a href='https://t.me/fomo_fighters_bot/game?startapp=ref111452882'>⚔️ FomoFighters ⚔️</a> • " .
    "<a href='https://t.me/DailyComboWorld'>💬 Chat</a>";    // حذف هشتگ‌های تکراری از کل کپشن (به جز خط اول)
    $lines = explode("\n", $final_caption);
    if (count($lines) > 1) {
        $first_line = array_shift($lines);
        $rest_content = implode("\n", $lines);
        $rest_content = str_replace($hashtag, '', $rest_content);
        $final_caption = $first_line . "\n" . $rest_content;
    }

    // بررسی طول کپشن
    if (strlen($final_caption) > MAX_CAPTION_LENGTH) {
        $final_caption = substr($final_caption, 0, MAX_CAPTION_LENGTH);
        $notification = "⚠️ Caption was trimmed.";
    }

    // جایگزینی + با فاصله در تمام blockquote ها
    $final_caption = preg_replace_callback('/(<blockquote>.*?<\/blockquote>)/s', function($matches) {
        $block = $matches[1];
        $block = str_replace('+', ' ', $block);
        return $block;
    }, $final_caption);

    // اگر در حالت ویرایش هستیم
    if ($okedit_mode) {
        // گرفتن وضعیت reply از دیتابیس
        $current_reply_status = getReplyStatus($hashtag);
        
        $result = editLastChannelPost($hashtag, $final_caption, $photo, $current_reply_status);
        
        if (!($result['ok'] ?? false)) {
            $error_msg = "⚠️ ویرایش پست انجام نشد.\n";
            $error_msg .= "خطا: " . ($result['description'] ?? 'Unknown error');
            sendMessage($chat_id, $error_msg);
        } else {
            $response = "✅ پست آخر برای هشتگ $hashtag با موفقیت ویرایش شد!";
            if (!empty($notification)) {
                $response .= "\n" . $notification;
            }
            sendMessageWithKeyboard($chat_id, $response, getAdminKeyboard());
        }
        exit;
    }

    // اگر عکس وجود ندارد، پیام هشدار بده و متوقف کن
    if (!$photo) {
        sendMessageWithKeyboard($chat_id, "⚠️ No photo provided and no default image in database.", getAdminKeyboard());
        exit;
    }

    // ارسال نهایی
    try {
        $result = sendPhotoToChannelSafeWithReply($photo, $final_caption, $hashtag);
        
        if (!($result['ok'] ?? false)) {
            error_log("API Error: " . print_r($result, true));
            throw new Exception("API request failed. Response: " . json_encode($result));
        }
        
        // اگر pending delete فعال است، آن را غیرفعال کنید
        if (isPendingDelete($chat_id)) {
            clearPendingDelete($chat_id);
        }
        
        $response = "✅ Post published successfully!\n";
        $response .= "🔗 Link: https://t.me/" . substr(CHANNEL_ID, 1) . "/" . $result['result']['message_id'];
        
        if (!empty($notification)) {
            $response .= "\n" . $notification;
        }
        
        sendMessageWithKeyboard($chat_id, $response, getAdminKeyboard());
    } catch (Exception $e) {
        // ثبت خطا در error_log
        error_log("Posting Failed: " . $e->getMessage());
        
        // ساخت پیام خطای دقیق برای ارسال به ادمین
        $error_message = "⚠️ ارسال پست با خطا مواجه شد:\n\n";
        $error_message .= "▫️ <b>Error:</b> " . htmlspecialchars($e->getMessage()) . "\n";
        
        // اگر خطای API تلگرام وجود دارد
        if (isset($result['description'])) {
            $error_message .= "▫️ <b>Telegram API Error:</b> " . htmlspecialchars($result['description']) . "\n";
        }
        
        // اگر اطلاعات بیشتری از پاسخ API موجود است
        if (isset($result)) {
            $error_message .= "▫️ <b>API Response:</b> <pre>" . htmlspecialchars(json_encode($result, JSON_PRETTY_PRINT)) . "</pre>\n";
        }
        
        // ارسال پیام خطا به ادمین با تمام جزئیات
        sendMessageWithKeyboard($chat_id, $error_message);
        
        // همچنین می‌توانید خطا را به سایر ادمین‌ها هم ارسال کنید
        foreach (ADMIN_IDS as $admin_id) {
            if ($admin_id != $chat_id) {
                sendMessage($admin_id, $error_message);
            }
        }
    }
}