import time
import re
import random
import jdatetime
import datetime as dt
import sqlite3
from datetime import datetime
from config import OWNER_ID

ENABLED_FLAG = 8

LOCK_COLUMNS = [
    'link', 'forward', 'edit', 'photo', 'video', 'file', 'zip', 'number',
    'music', 'voice', 'mention', 'repetition',
    'sticker', 'hashtag', 'code', 'swear', 'poll', 'story', 'location', 'live'
]

LOCK_NAMES_PERSIAN = [
    'لینک', 'فوروارد', 'ویرایش', 'عکس', 'فیلم', 'فایل', 'زیپ', 'عدد',
    'آهنگ', 'ویس', 'آیدی', 'کد هنگی',
    'استیکر', 'هشتگ', 'کد', 'فحاشی', 'نظرسنجی', 'استوری', 'لوکیشن', 'پخش زنده'
]


def set_lock_by_number(cursor, group_guid, lock_num, status):
    if 1 <= lock_num <= len(LOCK_COLUMNS):
        col = LOCK_COLUMNS[lock_num - 1]
        set_lock(cursor, group_guid, col, status)
        return True
    return False

def init_new_tables(cursor):
    cursor.execute("""CREATE TABLE IF NOT EXISTS user_stats (
        user_guid VARCHAR(64),
        group_guid VARCHAR(64),
        messages_count INT DEFAULT 0,
        today_messages INT DEFAULT 0,
        warnings INT DEFAULT 0,
        medals TEXT,
        level INT DEFAULT 0,
        join_date TEXT,
        last_date TEXT,
        asl TEXT,
        lagab TEXT,
        medal_score INT DEFAULT 0,
        PRIMARY KEY (user_guid, group_guid)
    )""")
    cursor.execute("""CREATE TABLE IF NOT EXISTS message_log (
        message_id VARCHAR(64),
        group_guid VARCHAR(64),
        received_at INT,
        PRIMARY KEY (message_id, group_guid)
    )""")
    cursor.execute("CREATE INDEX IF NOT EXISTS idx_msg_group ON message_log(group_guid)")
    cursor.execute("""CREATE TABLE IF NOT EXISTS mutes (
        user_guid VARCHAR(64),
        group_guid VARCHAR(64),
        until_time INT,
        PRIMARY KEY (user_guid, group_guid)
    )""")
    cursor.execute("""CREATE TABLE IF NOT EXISTS bans (
        user_guid VARCHAR(64),
        group_guid VARCHAR(64),
        banned_at INT,
        PRIMARY KEY (user_guid, group_guid)
    )""")
    cursor.execute("""CREATE TABLE IF NOT EXISTS locks (
        group_guid VARCHAR(64) PRIMARY KEY,
        link INT DEFAULT 0,
        forward INT DEFAULT 0,
        edit INT DEFAULT 0,
        photo INT DEFAULT 0,
        video INT DEFAULT 0,
        file INT DEFAULT 0,
        zip INT DEFAULT 0,
        number INT DEFAULT 0,
        music INT DEFAULT 0,
        voice INT DEFAULT 0,
        mention INT DEFAULT 0,
        repetition INT DEFAULT 0,
        sticker INT DEFAULT 0,
        hashtag INT DEFAULT 0,
        code INT DEFAULT 0,
        swear INT DEFAULT 0,
        poll INT DEFAULT 0,
        story INT DEFAULT 0,
        location INT DEFAULT 0,
        live INT DEFAULT 0
    )""")
    cursor.execute("""CREATE TABLE IF NOT EXISTS group_settings (
        group_guid VARCHAR(64) PRIMARY KEY,
        chatbot INT DEFAULT 0,
        auto_delete INT DEFAULT 0,
        auto_delete_time INT DEFAULT 0,
        default_warning_limit INT DEFAULT 3,
        default_mute_time INT DEFAULT 3600,
        group_status INT DEFAULT 1
    )""")
    cursor.execute("""CREATE TABLE IF NOT EXISTS chatbot (
        question VARCHAR(255) PRIMARY KEY,
        answer TEXT,
        group_guid VARCHAR(64)
    )""")
    cursor.execute("""CREATE TABLE IF NOT EXISTS bot_chats (
        chat_id VARCHAR(64) PRIMARY KEY,
        user_guid VARCHAR(64),
        user_name TEXT,
        start_date INT
    )""")
    cursor.execute("""CREATE TABLE IF NOT EXISTS medals (
        user_guid VARCHAR(64),
        group_guid VARCHAR(64),
        medal_type VARCHAR(50),
        awarded_at INT,
        PRIMARY KEY (user_guid, group_guid, medal_type)
    )""")
    cursor.execute("""CREATE TABLE IF NOT EXISTS allowed_groups (
        group_guid VARCHAR(64) PRIMARY KEY,
        added_by TEXT,
        added_at INT,
        expires_at INT
    )""")
    cursor.execute("""CREATE TABLE IF NOT EXISTS banner (
        id INT PRIMARY KEY CHECK (id = 1),
        source_chat_id TEXT,
        source_message_id TEXT,
        interval_hours INT,
        active INT DEFAULT 0
    )""")
    cursor.execute("""CREATE TABLE IF NOT EXISTS banner_exceptions (
        group_guid VARCHAR(64) PRIMARY KEY
    )""")
def add_allowed_group(cursor, group_guid, owner_guid, days):
    expires_at = int(time.time()) + (days * 86400)
    cursor.execute("REPLACE INTO allowed_groups (group_guid, added_by, added_at, expires_at) VALUES (%s, %s, %s, %s)",
                   (group_guid, owner_guid, int(time.time()), expires_at))
def is_subscription_mode(cursor):
    cursor.execute("SELECT value FROM bot_state WHERE `key`='bot_mode'")
    row = cursor.fetchone()
    return row and row[0] == "subscription"

def set_bot_mode(cursor, mode):
    cursor.execute("REPLACE INTO bot_state (`key`, value) VALUES (%s, %s)", ("bot_mode", mode))
    cursor.connection.commit()   

def set_banner(cursor, source_chat_id, source_message_id, interval_hours):
    cursor.execute("DELETE FROM banner")
    cursor.execute("INSERT INTO banner (id, source_chat_id, source_message_id, interval_hours, active) VALUES (1, %s, %s, %s, 1)",
                   (source_chat_id, source_message_id, interval_hours))

def get_banner(cursor):
    cursor.execute("SELECT source_chat_id, source_message_id, interval_hours, active FROM banner WHERE id=1")
    return cursor.fetchone()

def deactivate_banner(cursor):
    cursor.execute("UPDATE banner SET active=0 WHERE id=1")

def add_banner_exception(cursor, group_guid):
    cursor.execute("INSERT IGNORE INTO banner_exceptions (group_guid) VALUES (%s)", (group_guid,))

def remove_banner_exception(cursor, group_guid):
    cursor.execute("DELETE FROM banner_exceptions WHERE group_guid=%s", (group_guid,))


def convert_to_font_styles(text):
    """
    تبدیل متن انگلیسی و اعداد به چند سبک فونت یونیکد.
    خروجی: لیستی از دیکشنری‌ها با کلیدهای 'style_name' و 'transformed_text'
    """
    persian_digits = '۰۱۲۳۴۵۶۷۸۹'
    arabic_digits = '٠١٢٣٤٥٦٧٨٩'
    english_digits = '0123456789'
    trans_table = str.maketrans(persian_digits + arabic_digits, english_digits + english_digits)
    text = text.translate(trans_table)

    lower_chars = 'abcdefghijklmnopqrstuvwxyz'
    upper_chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    digits = '0123456789'

    persian_chars = 'آ ا ب پ ت ث ج چ ح خ د ذ ر ز ژ س ش ص ض ط ظ ع غ ف ق ک گ ل م ن و ه ی'
    persian_list = list(persian_chars.replace(' ', ''))

    styles = {
        "🔤 معمولی": (lower_chars, upper_chars, digits),
        "𝐁𝐨𝐥𝐝": ('𝐚𝐛𝐜𝐝𝐞𝐟𝐠𝐡𝐢𝐣𝐤𝐥𝐦𝐧𝐨𝐩𝐪𝐫𝐬𝐭𝐮𝐯𝐰𝐱𝐲𝐳',
                  '𝐀𝐁𝐂𝐃𝐄𝐅𝐆𝐇𝐈𝐉𝐊𝐋𝐌𝐍𝐎𝐏𝐐𝐑𝐒𝐓𝐔𝐕𝐖𝐗𝐘𝐙',
                  '𝟎𝟏𝟐𝟑𝟒𝟓𝟔𝟕𝟖𝟗'),
        "𝐼𝑡𝑎𝑙𝑖𝑐": ('𝑎𝑏𝑐𝑑𝑒𝑓𝑔ℎ𝑖𝑗𝑘𝑙𝑚𝑛𝑜𝑝𝑞𝑟𝑠𝑡𝑢𝑣𝑤𝑥𝑦𝑧',
                    '𝐴𝐵𝐶𝐷𝐸𝐹𝐺𝐻𝐼𝐽𝐾𝐿𝑀𝑁𝑂𝑃𝑄𝑅𝑆𝑇𝑈𝑉𝑊𝑋𝑌𝑍',
                    '0123456789'),
        "𝑩𝒐𝒍𝒅 𝑰𝒕𝒂𝒍𝒊𝒄": ('𝒂𝒃𝒄𝒅𝒆𝒇𝒈𝒉𝒊𝒋𝒌𝒍𝒎𝒏𝒐𝒑𝒒𝒓𝒔𝒕𝒖𝒗𝒘𝒙𝒚𝒛',
                          '𝑨𝑩𝑪𝑫𝑬𝑭𝑮𝑯𝑰𝑱𝑲𝑳𝑴𝑵𝑶𝑷𝑸𝑹𝑺𝑻𝑼𝑽𝑾𝑿𝒀𝒁',
                          '𝟎𝟏𝟐𝟑𝟒𝟓𝟔𝟕𝟖𝟗'),
        "𝙼𝚘𝚗𝚘𝚜𝚙𝚊𝚌𝚎": ('𝚊𝚋𝚌𝚍𝚎𝚏𝚐𝚑𝚒𝚓𝚔𝚕𝚖𝚗𝚘𝚙𝚚𝚛𝚜𝚝𝚞𝚟𝚠𝚡𝚢𝚣',
                      '𝙰𝙱𝙲𝙳𝙴𝙵𝙶𝙷𝙸𝙹𝙺𝙻𝙼𝙽𝙾𝙿𝚀𝚁𝚂𝚃𝚄𝚅𝚆𝚇𝚈𝚉',
                      '𝟶𝟷𝟸𝟹𝟺𝟻𝟼𝟽𝟾𝟿'),
        "𝔻𝕠𝕦𝕓𝕝𝕖 𝕊𝕥𝕣𝕦𝕔𝕜": ('𝕒𝕓𝕔𝕕𝕖𝕗𝕘𝕙𝕚𝕛𝕜𝕝𝕞𝕟𝕠𝕡𝕢𝕣𝕤𝕥𝕦𝕧𝕨𝕩𝕪𝕫',
                        '𝔸𝔹ℂ𝔻𝔼𝔽𝔾ℍ𝕀𝕁𝕂𝕃𝕄ℕ𝕆ℙℚℝ𝕊𝕋𝕌𝕍𝕎𝕏𝕐ℤ',
                        '𝟘𝟙𝟚𝟛𝟜𝟝𝟞𝟟𝟠𝟡'),
        "𝒮𝒸𝓇𝒾𝓅𝓉": ('𝒶𝒷𝒸𝒹ℯ𝒻ℊ𝒽𝒾𝒿𝓀𝓁𝓂𝓃ℴ𝓅𝓆𝓇𝓈𝓉𝓊𝓋𝓌𝓍𝓎𝓏',
                   '𝒜ℬ𝒞𝒟ℰℱ𝒢ℋℐ𝒥𝒦ℒℳ𝒩𝒪𝒫𝒬ℛ𝒮𝒯𝒰𝒱𝒲𝒳𝒴𝒵',
                   '𝟢𝟣𝟤𝟥𝟦𝟧𝟨𝟩𝟪𝟫'),
        "𝖥𝗋𝖺𝗄𝗍𝗎𝗋": ('𝖆𝖇𝖈𝖉𝖊𝖋𝖌𝖍𝖎𝖏𝖐𝖑𝖒𝖓𝖔𝖕𝖖𝖗𝖘𝖙𝖚𝖛𝖜𝖝𝖞𝖟',
                    '𝕬𝕭𝕮𝕯𝕰𝕱𝕲𝕳𝕴𝕵𝕶𝕷𝕸𝕹𝕺𝕻𝕼𝕽𝕾𝕿𝖀𝖁𝖂𝖃𝖄𝖅',
                    '𝟎𝟏𝟐𝟑𝟒𝟓𝟔𝟕𝟖𝟗'),
        "𝕊𝖺𝗇𝗌 𝕊𝖾𝗋𝗂𝖿": ('𝖺𝖻𝖼𝖽𝖾𝖿𝗀𝗁𝗂𝗃𝗄𝗅𝗆𝗇𝗈𝗉𝗊𝗋𝗌𝗍𝗎𝗏𝗐𝗑𝗒𝗓',
                      '𝖠𝖡𝖢𝖣𝖤𝖥𝖦𝖧𝖨𝖩𝖪𝖫𝖬𝖭𝖮𝖯𝖰𝖱𝖲𝖳𝖴𝖵𝖶𝖷𝖸𝖹',
                      '𝟢𝟣𝟤𝟥𝟦𝟧𝟨𝟩𝟪𝟫'),
        "𝕊𝖺𝗇𝗌 𝕊𝖾𝗋𝗂𝖿 𝖡𝗈𝗅𝖽": ('𝖺𝖻𝖼𝖽𝖾𝖿𝗀𝗁𝗂𝗃𝗄𝗅𝗆𝗇𝗈𝗉𝗊𝗋𝗌𝗍𝗎𝗏𝗐𝗑𝗒𝗓',
                          '𝖠𝖡𝖢𝖣𝖤𝖥𝖦𝖧𝖨𝖩𝖪𝖫𝖬𝖭𝖮𝖯𝖰𝖱𝖲𝖳𝖴𝖵𝖶𝖷𝖸𝖹',
                          '𝟬𝟭𝟮𝟯𝟰𝟱𝟲𝟳𝟴𝟵'),
        "𝒮𝒶𝓃𝓈 𝒮𝑒𝓇𝒾𝒻 𝐼𝓉𝒶𝓁𝒾𝒸": ('𝒶𝒷𝒸𝒹ℯ𝒻ℊ𝒽𝒾𝒿𝓀𝓁𝓂𝓃ℴ𝓅𝓆𝓇𝓈𝓉𝓊𝓋𝓌𝓍𝓎𝓏',
                            '𝒜ℬ𝒞𝒟ℰℱ𝒢ℋℐ𝒥𝒦ℒℳ𝒩𝒪𝒫𝒬ℛ𝒮𝒯𝒰𝒱𝒲𝒳𝒴𝒵',
                            '𝟢𝟣𝟤𝟥𝟦𝟧𝟨𝟩𝟪𝟫'),
        "𝚄𝚗𝚍𝚎𝚛𝚕𝚒𝚗𝚎": ('a̲b̲c̲d̲e̲f̲g̲h̲i̲j̲k̲l̲m̲n̲o̲p̲q̲r̲s̲t̲u̲v̲w̲x̲y̲z̲',
                    'A̲B̲C̲D̲E̲F̲G̲H̲I̲J̲K̲L̲M̲N̲O̲P̲Q̲R̲S̲T̲U̲V̲W̲X̲Y̲Z̲',
                    '0̲1̲2̲3̲4̲5̲6̲7̲8̲9̲'),
        "̶S̶t̶r̶o̶k̶e̶": ('a̶b̶c̶d̶e̶f̶g̶h̶i̶j̶k̶l̶m̶n̶o̶p̶q̶r̶s̶t̶u̶v̶w̶x̶y̶z̶',
                    'A̶B̶C̶D̶E̶F̶G̶H̶I̶J̶K̶L̶M̶N̶O̶P̶Q̶R̶S̶T̶U̶V̶W̶X̶Y̶Z̶',
                    '0̶1̶2̶3̶4̶5̶6̶7̶8̶9̶'),
        "🅲🅸🆁🅲🅻🅴🅳": ('ⓐⓑⓒⓓⓔⓕⓖⓗⓘⓙⓚⓛⓜⓝⓞⓟⓠⓡⓢⓣⓤⓥⓦⓧⓨⓩ',
                  'ⒶⒷⒸⒹⒺⒻⒼⒽⒾⒿⓀⓁⓂⓃⓄⓅⓆⓇⓈⓉⓊⓋⓌⓍⓎⓏ',
                  '⓪①②③④⑤⑥⑦⑧⑨'),
        "🅟🅐🅡🅔🅝🅣🅗🅔🅢🅘🅢": ('🅐🅑🅒🅓🅔🅕🅖🅗🅘🅙🅚🅛🅜🅝🅞🅟🅠🅡🅢🅣🅤🅥🅦🅧🅨🅩',
                     '🄰🄱🄲🄳🄴🄵🄶🄷🄸🄹🄺🄻🄼🄽🄾🄿🅀🅁🅂🅃🅄🅅🅆🅇🅈🅉',
                     '0123456789'),
        "ℂ𝕚𝕣𝕔𝕝𝕖𝕕 𝕊𝕢𝕦𝕒𝕣𝕖": ('🅰🅱🅲🅳🅴🅵🅶🅷🅸🅹🅺🅻🅼🅽🅾🅿🆀🆁🆂🆃🆄🆅🆆🆇🆈🆉',
                         '🄰🄱🄲🄳🄴🄵🄶🄷🄸🄹🄺🄻🄼🄽🄾🄿🅀🅁🅂🅃🅄🅅🅆🅇🅈🅉',
                         '0123456789'),
        "𝕊𝕞𝕒𝕝𝕝 ℂ𝕒𝕡𝕤": ('ᵃᵇᶜᵈᵉᶠᵍʰⁱʲᵏˡᵐⁿᵒᵖᵟʳˢᵗᵘᵛʷˣʸᶻ',
                      'ᴬᴮᶜᴰᴱᶠᴳᴴᴵᴶᴷᴸᴹᴺᴼᴾᵠᴿˢᵀᵁⱽᵂˣʸᶻ',
                      '𝟢𝟣𝟤𝟥𝟦𝟧𝟨𝟩𝟪𝟫'),
    }

    result = []
    for style_name, (style_lower, style_upper, style_digits) in styles.items():
        transformed = []
        for ch in text:
            if 'a' <= ch <= 'z':
                idx = ord(ch) - ord('a')
                transformed.append(style_lower[idx])
            elif 'A' <= ch <= 'Z':
                idx = ord(ch) - ord('A')
                transformed.append(style_upper[idx])
            elif '0' <= ch <= '9':
                idx = ord(ch) - ord('0')
                transformed.append(style_digits[idx])
            elif ch in persian_list:
                transformed.append(ch)  # فارسی بدون تغییر
            else:
                transformed.append(ch)
        result.append({"style_name": style_name, "transformed_text": ''.join(transformed)})
    return result
    
def get_banner_exceptions_list(cursor):
    cursor.execute("SELECT group_guid FROM banner_exceptions")
    rows = cursor.fetchall()
    if not rows:
        return "📭 هیچ گروه استثنایی ثبت نشده است.", []
    text = "━━━━━━━━━━━━━━━━━━━━\n🚫 لیست گروه‌های استثنا (عدم دریافت بنر)\n━━━━━━━━━━━━━━━━━━━━\n"
    mono_parts = []
    for (guid,) in rows:
        group_name = guid
        result = _api_call("getChat", {"chat_id": guid})
        if result and result.get("status") == "OK":
            chat_data = result.get("data", {}).get("chat", {})
            group_name = chat_data.get("title") or guid
        text += f"👥 {group_name}\n{guid}\n━━━━━━━━━━━━━━━━━━━━\n"
        mono_parts.append({"text": guid})
    return text, mono_parts

def get_banner_exceptions(cursor):
    cursor.execute("SELECT group_guid FROM banner_exceptions")
    return [row[0] for row in cursor.fetchall()]
def delete_group_completely(cursor, group_guid):
    cursor.execute("DELETE FROM groups WHERE guid = %s", (group_guid,))
    cursor.execute("DELETE FROM allowed_groups WHERE group_guid = %s", (group_guid,))
    cursor.execute("DELETE FROM locks WHERE group_guid = %s", (group_guid,))
    cursor.execute("DELETE FROM group_settings WHERE group_guid = %s", (group_guid,))
    cursor.execute("DELETE FROM user_stats WHERE group_guid = %s", (group_guid,))
    cursor.execute("DELETE FROM message_log WHERE group_guid = %s", (group_guid,))
    cursor.execute("DELETE FROM mutes WHERE group_guid = %s", (group_guid,))
    cursor.execute("DELETE FROM bans WHERE group_guid = %s", (group_guid,))
    cursor.execute("DELETE FROM chatbot WHERE group_guid = %s", (group_guid,))

def remove_allowed_group(cursor, group_guid):
    cursor.execute("DELETE FROM allowed_groups WHERE group_guid=%s", (group_guid,))

def is_group_allowed(cursor, group_guid):
    cursor.execute("SELECT expires_at FROM allowed_groups WHERE group_guid=%s", (group_guid,))
    row = cursor.fetchone()
    if not row:
        return False
    expires_at = row[0]
    if expires_at < int(time.time()):
        cursor.execute("DELETE FROM allowed_groups WHERE group_guid=%s", (group_guid,))
        return False
    return True
    
def get_full_user_info_by_chat(chat_id):
    """دریافت نام کامل و یوزرنیم کاربر از طریق chat_id با متد getChat"""
    result = _api_call("getChat", {"chat_id": chat_id})
    if result and result.get("status") == "OK":
        data = result.get("data", {})
        chat = data.get("chat", {})
        first_name = chat.get("first_name", "")
        last_name = chat.get("last_name", "")
        username = chat.get("username", "")
        full_name = f"{first_name} {last_name}".strip()
        if not full_name:
            full_name = username or chat_id
        return full_name, username
    return chat_id, ""

def get_chat_title(chat_guid):
    """دریافت عنوان گروه/کانال از API"""
    result = _api_call("getChat", {"chat_id": chat_guid})
    if result and result.get("status") == "OK":
        chat_data = result.get("data", {}).get("chat", {})
        return chat_data.get("title") or chat_guid
    return chat_guid

def get_welcome_text(cursor, chat_id, user_guid, OWNER_ID):
    full_name, username = get_full_user_info_by_chat(chat_id)
    guid = user_guid  
    
    # No need to fetch owned groups or check owner anymore
    return f"""━━━━━━━━━━━━━━━━━━
✨ به ربات خوش آمدید ✨
━━━━━━━━━━━━━━━━━━
👤 نام: {full_name}

🔹 شما مالک هیچ گروهی نیستید.

🤖 ربات مدیریت پیشرفته گروه

#گوید_کاربر_فعال_کننده :/>
{guid}

📌 از دکمه‌های پایین صفحه استفاده کنید.
📖 برای راهنمای کامل /help را بفرستید.
━━━━━━━━━━━━━━━━━━"""

def get_user_panel_text(cursor, chat_id, user_guid):
    full_name, username = get_full_user_info_by_chat(chat_id)
    guid = user_guid
    username_line = f"📛 یوزرنیم: @{username}" if username else ""
    return f"""━━━━━━━━━━━━━━━━━━━━
👤 پنل کاربری
━━━━━━━━━━━━━━━━━━━━
👤 نام: {full_name}
🆔 گوید: {guid}
{username_line}
━━━━━━━━━━━━━━━━━━━━
از دکمه‌های زیر استفاده کنید:"""
def get_helpp_text():
    return """━━━━━━━━━━━━━━━━━━━━
📖 راهنمای پنل
━━━━━━━━━━━━━━━━━━━━
♦1- پنل مدیریت

♦ لیست گروه‌ها: قابلیت مشاهده گروه‌ها گروه‌های فعال و غیر فعال

♦ آمار کلی: مشاهده کل گروه‌ها و گروه‌های فعال کاربرای فعال تعداد پیام کلی

♦ حذف گروه: این قابلیت برای غیر فعال کردن ربات در گروه‌ها است که با گوید گروه گوید گروه حذف می‌شود

♦ افزودن گروه: این قابلیت برای اضافه کردن گروه با گوید و تنظیم زمان فعال می‌شود

♦ پیام همگانی این قابلیت برای ارسال به کل پیوی های ربات است

♦ حالت ربات: برای اشتراکی کردن یا فعال سازی دائم ربات

♦2 پنل تبلیغات

♦ لیست استثنا:  قابلیت نمایش روه‌های که لینک تبلیغ رسال نمی‌شود

♦ ثبت بنر: روی دکمه ثبت بنر کلیک کنید و یک بنر فوروارد کنید 
تا بنر ثبت شود

♦ متوقف بنر: برای حذف کردن بنر

♦ مدیریت استثنا: این قابلیت برای اضافه کردن گروه و حذف کردن گروه
━━━━━━━━━━━━━━━━━━━━"""
def get_help_text():
    return """━━━━━━━━━━━━━━━━━━
💸 قیمت اشتراک 
━━━━━━━━━━━━━━━━━━
♦ خرید اشتراک ربات ماه ۱۵ هزار تومان می‌باشد
♦ مثل: که برای دو ماه ۳۰ هزار تومان می‌باشد
♦ برای خرید: کلیک کن👇
[ -𖣐->      @ReZa_TOK ] 
━━━━━━━━━━━━━━━━━━"""

def get_bot_stats(cursor):
    cursor.execute("SELECT COUNT(*) FROM groups WHERE guid LIKE 'g0%'")
    total_groups = cursor.fetchone()[0] or 0
    
    cursor.execute("SELECT COUNT(*) FROM groups WHERE guid LIKE 'g0%' AND active=1")
    active_groups = cursor.fetchone()[0] or 0
    
    cursor.execute("SELECT COUNT(DISTINCT user_guid) FROM user_stats")
    total_users = cursor.fetchone()[0] or 0
    
    cursor.execute("SELECT SUM(messages_count) FROM user_stats")
    total_messages = cursor.fetchone()[0] or 0
    
    return f"""━━━━━━━━━━━━━━━━━━━━
📊 آمار کلی ربات
━━━━━━━━━━━━━━━━━━━━
👥 کل گروه‌ها: {total_groups}
✅ گروه‌های فعال: {active_groups}
👤 کل کاربران: {total_users}
💬 کل پیام‌ها: {total_messages}
━━━━━━━━━━━━━━━━━━━━"""

def get_user_stats(cursor, user_guid, group_guid, user_name):
    cursor.execute("""
        SELECT COALESCE(messages_count, 0), COALESCE(today_messages, 0), 
            COALESCE(warnings, 0), COALESCE(level, 0)
        FROM user_stats WHERE user_guid=%s AND group_guid=%s
    """, (user_guid, group_guid))
    stats = cursor.fetchone()
    messages = stats[0] if stats else 0
    today = stats[1] if stats else 0
    warnings = stats[2] if stats else 0
    level = stats[3] if stats else 0

    text = f"""━━━━━━━━━━━━━━━━━━
وضعیت آمار و اشتراک
━━━━━━━━━━━━━━━━━━
👤 کاربر: {user_name}
#گوید_کاربر_فعال_کننده:/> 
{user_guid}

💰 وضعیت اشتراک: فعال
📅 انقضا: 1405/03/23 10:11
⏳ باقی‌مانده: 15 ساعت

⚡ سطح: {level}
⚠️ اخطار: {warnings}
💬 پیام امروز: {today}
💬 کل پیام‌ها: {messages}
━━━━━━━━━━━━━━━━━━"""
    mono_parts = [{"text": user_guid}]
    return text, mono_parts
    
def set_user_medal(cursor, user_guid, group_guid, score):
    cursor.execute("""
        INSERT INTO user_stats (user_guid, group_guid, medal_score)
        VALUES (%s, %s, %s)
        ON DUPLICATE KEY UPDATE medal_score = VALUES(medal_score)
    """, (user_guid, group_guid, score))

def set_user_asl(cursor, user_guid, group_guid, asl):
    cursor.execute("""
        INSERT INTO user_stats (user_guid, group_guid, asl)
        VALUES (%s, %s, %s)
        ON DUPLICATE KEY UPDATE asl = VALUES(asl)
    """, (user_guid, group_guid, asl))

def set_user_lagab(cursor, user_guid, group_guid, lagab):
    cursor.execute("""
        INSERT INTO user_stats (user_guid, group_guid, lagab)
        VALUES (%s, %s, %s)
        ON DUPLICATE KEY UPDATE lagab = VALUES(lagab)
    """, (user_guid, group_guid, lagab))

def update_user_message_count(cursor, user_guid, group_guid):
    today = datetime.now().strftime("%Y-%m-%d")
    cursor.execute("SELECT today_messages, last_date FROM user_stats WHERE user_guid=%s AND group_guid=%s", 
                   (user_guid, group_guid))
    row = cursor.fetchone()
    if row:
        last_date = row[1]
        if last_date is None or last_date != today:
            cursor.execute("""
                UPDATE user_stats SET messages_count = messages_count + 1,
                                      today_messages = 1,
                                      last_date = %s
                WHERE user_guid=%s AND group_guid=%s
            """, (today, user_guid, group_guid))
        else:
            cursor.execute("""
                UPDATE user_stats SET messages_count = messages_count + 1,
                                      today_messages = today_messages + 1
                WHERE user_guid=%s AND group_guid=%s
            """, (user_guid, group_guid))
    else:
        cursor.execute("""
            INSERT INTO user_stats (user_guid, group_guid, messages_count, today_messages, join_date, last_date)
            VALUES (%s, %s, 1, 1, %s, %s)
        """, (user_guid, group_guid, today, today))

def add_warning(cursor, user_guid, group_guid, warning_limit):
    cursor.execute("""
        INSERT INTO user_stats (user_guid, group_guid, warnings, messages_count, today_messages, join_date, last_date)
        VALUES (%s, %s, 1, 0, 0, %s, %s)
        ON DUPLICATE KEY UPDATE warnings = warnings + 1
    """, (user_guid, group_guid, datetime.now().strftime("%Y-%m-%d"), datetime.now().strftime("%Y-%m-%d")))
    
    cursor.execute("SELECT warnings FROM user_stats WHERE user_guid=%s AND group_guid=%s", (user_guid, group_guid))
    result = cursor.fetchone()
    return result and result[0] > warning_limit

def remove_warning(cursor, user_guid, group_guid):
    cursor.execute("""
        UPDATE user_stats SET warnings = warnings - 1 
        WHERE user_guid=%s AND group_guid=%s AND warnings > 0
    """, (user_guid, group_guid))

def add_mute(cursor, user_guid, group_guid, duration_seconds):
    until_time = int(time.time()) + duration_seconds
    cursor.execute("REPLACE INTO mutes (user_guid, group_guid, until_time) VALUES (%s, %s, %s)",
                   (user_guid, group_guid, until_time))

def remove_mute(cursor, user_guid, group_guid):
    cursor.execute("DELETE FROM mutes WHERE user_guid=%s AND group_guid=%s", (user_guid, group_guid))

def is_muted(cursor, user_guid, group_guid):
    cursor.execute("SELECT until_time FROM mutes WHERE user_guid=%s AND group_guid=%s", (user_guid, group_guid))
    result = cursor.fetchone()
    if result:
        if result[0] > int(time.time()):
            return True
        else:
            remove_mute(cursor, user_guid, group_guid)
    return False

def get_banned_users(cursor, group_guid):
    cursor.execute("SELECT user_guid, banned_at FROM bans WHERE group_guid=%s", (group_guid,))
    return cursor.fetchall()

def is_banned(cursor, user_guid, group_guid):
    cursor.execute("SELECT 1 FROM bans WHERE user_guid=%s AND group_guid=%s", (user_guid, group_guid))
    return cursor.fetchone() is not None

def get_lock_status(cursor, group_guid, lock_type):
    try:
        cursor.execute(f"SELECT {lock_type} FROM locks WHERE group_guid=%s", (group_guid,))
        result = cursor.fetchone()
        return result[0] if result else 0
    except Exception:
        return 0


    
def set_lock(cursor, group_guid, lock_type, value):
    cursor.execute(f"""
        INSERT INTO locks (group_guid, {lock_type})
        VALUES (%s, %s)
        ON DUPLICATE KEY UPDATE {lock_type} = VALUES({lock_type})
    """, (group_guid, value))

def add_medal(cursor, user_guid, group_guid, medal_type):
    cursor.execute("""
        REPLACE INTO medals (user_guid, group_guid, medal_type, awarded_at)
        VALUES (%s, %s, %s, %s)
    """, (user_guid, group_guid, medal_type, int(time.time())))

def remove_medal(cursor, user_guid, group_guid, medal_type):
    cursor.execute("DELETE FROM medals WHERE user_guid=%s AND group_guid=%s AND medal_type=%s", 
                   (user_guid, group_guid, medal_type))

def get_user_medals(cursor, user_guid, group_guid):
    cursor.execute("SELECT medal_type FROM medals WHERE user_guid=%s AND group_guid=%s", 
                   (user_guid, group_guid))
    return [row[0] for row in cursor.fetchall()]

def ban_chat_member(chat_id, user_id):
    payload = {"chat_id": chat_id, "user_id": user_id}
    return _api_call("banChatMember", payload)

def unban_chat_member(chat_id, user_id):
    payload = {"chat_id": chat_id, "user_id": user_id}
    return _api_call("unbanChatMember", payload)

def clear_user_data(c, user_guid, group_guid):
    try:
        c.execute("DELETE FROM mutes WHERE user_guid=%s AND group_guid=%s", (user_guid, group_guid))
        c.execute("DELETE FROM medals WHERE user_guid=%s AND group_guid=%s", (user_guid, group_guid))
        c.execute("UPDATE groups SET owner = NULL WHERE owner = %s AND guid = %s", (user_guid, group_guid))
        for admin_field in ['admin1', 'admin2', 'admin3']:
            c.execute(f"UPDATE groups SET {admin_field} = NULL WHERE {admin_field} = %s AND guid = %s", (user_guid, group_guid))
        c.execute("DELETE FROM user_stats WHERE user_guid=%s AND group_guid=%s", (user_guid, group_guid))
        c.execute("DELETE FROM bans WHERE user_guid=%s AND group_guid=%s", (user_guid, group_guid))
        print(f"✅ تمام اطلاعات کاربر {user_guid} در گروه {group_guid} پاک شد")
        return True
    except Exception as e:
        print(f"❌ خطا در پاک کردن اطلاعات کاربر: {e}")
        return False

def add_ban(c, user_guid, group_guid):
    try:
        result = ban_chat_member(group_guid, user_guid)
        if result and result.get("status") == "OK":
            print(f"✅ کاربر {user_guid} با موفقیت از گروه {group_guid} بن شد")
            clear_user_data(c, user_guid, group_guid)
            ban_time = int(time.time())
            c.execute("REPLACE INTO bans (user_guid, group_guid, banned_at) VALUES (%s, %s, %s)",
                     (user_guid, group_guid, ban_time))
            return True
        else:
            error_msg = result.get("data", {}).get("error", {}).get("message", "دسترسی کافی وجود ندارد") if result else "خطای نامشخص"
            print(f"❌ خطا در بن کردن کاربر: {error_msg}")
            return False
    except Exception as e:
        print(f"❌ خطا در add_ban: {e}")
        return False

def remove_ban(c, user_guid, group_guid):
    try:
        result = unban_chat_member(group_guid, user_guid)
        if result and result.get("status") == "OK":
            print(f"✅ بن کاربر {user_guid} در گروه {group_guid} رفع شد")
            c.execute("DELETE FROM bans WHERE user_guid=%s AND group_guid=%s", 
                     (user_guid, group_guid))
            return True
        else:
            error_msg = result.get("data", {}).get("error", {}).get("message", "دسترسی کافی وجود ندارد") if result else "خطای نامشخص"
            print(f"❌ خطا در رفع بن: {error_msg}")
            return False
    except Exception as e:
        print(f"❌ خطا در remove_ban: {e}")
        return False

def get_list_qofli(cursor, group_guid):
    cursor.execute("INSERT IGNORE INTO locks (group_guid) VALUES (%s)", (group_guid,))
    locks = [
        ('لینک          ', 'link'), ('فوروارد     ', 'forward'), ('ویرایش     ', 'edit'),
        ('عکس       ', 'photo'), ('فیلم         ', 'video'), ('فایل         ', 'file'),
        ('زیپ          ', 'zip'), ('عدد         ', 'number'), ('آهنگ        ', 'music'),
        ('ویس       ', 'voice'), ('آیدی        ', 'mention'), ('کد هنگی ', 'repetition'),
        ('استیکر     ', 'sticker'), ('هشتگ     ', 'hashtag'), ('کد           ', 'code'),
        ('فحاشی    ', 'swear'), ('نظرسنجی ', 'poll'), ('استوری    ', 'story'),
        ('لوکیشن    ', 'location'), ('پخش زنده', 'live')
    ]
    width = 1
    text = """━━━━━━━━━━━━━━━
(❌) -♡- >{ لیست قفلی } <¥> 
━━━━━━━━━━━━━━━"""
    for i, (name, col) in enumerate(locks, 1):
        status = get_lock_status(cursor, group_guid, col)
        is_locked = (status & ENABLED_FLAG) != 0
        lock_icon = "🔒" if is_locked else "🔓"
        if is_locked:
            ban_icon = "🚫" if (status & 1) else "➕"
            warn_icon = "⚠️" if (status & 2) else "➕"
            mute_icon = "🔇" if (status & 4) else "➕"
        else:
            ban_icon = warn_icon = mute_icon = "➕"
        text += f"\n❌>{i:1}>{name:<{width}}{lock_icon}>{warn_icon}>{ban_icon}>{mute_icon}"
    text += """
━━━━━━━━━━━━━━━
🔓 > 1 باز    🔒 > 1 قفل
🚫 > بن 1 فعال/غیرفعال 
⚠️ > اخطار 1 فعال/غیرفعال 
🔇 > سکوت 1 فعال/غیرفعال 
♦> همه باز / همه قفل
━━━━━━━━━━━━━━━"""
    cursor.execute("SELECT default_warning_limit, default_mute_time FROM group_settings WHERE group_guid=%s", (group_guid,))
    row = cursor.fetchone()
    if row:
        warning_limit = row[0] if row[0] is not None else 3
        mute_time = row[1] if row[1] is not None else 3600
        if mute_time >= 3600:
            mute_display = f"{mute_time // 3600} ساعت"
        elif mute_time >= 60:
            mute_display = f"{mute_time // 60} دقیقه"
        else:
            mute_display = f"{mute_time} ثانیه"
    else:
        warning_limit = 3
        mute_display = "1 ساعت"
    text += f"""
⚠️ > اخطار تنظیم شده: {warning_limit}
🔇 > سکوت تنظیم شده: {mute_display}
━━━━━━━━━━━━━━━"""
    return text

def get_user_amar(cursor, user_guid, group_guid, user_name, user_rank=0, is_self=True):
    try:
        rank_map = {0: "عادی", 1: "ادمین", 2: "مالک گروه", 3: "سازنده"}
        rank_text = rank_map.get(user_rank, "عادی")
        cursor.execute("SELECT default_warning_limit FROM group_settings WHERE group_guid=%s", (group_guid,))
        row_limit = cursor.fetchone()
        warning_limit = row_limit[0] if row_limit and row_limit[0] is not None else 3
        cursor.execute("""
            SELECT COALESCE(messages_count, 0),
                   COALESCE(today_messages, 0),
                   COALESCE(warnings, 0),
                   COALESCE(level, 0),
                   join_date,
                   asl,
                   lagab,
                   medal_score
            FROM user_stats WHERE user_guid=%s AND group_guid=%s
        """, (user_guid, group_guid))
        row = cursor.fetchone()
        if row:
            messages, today, warnings, level, join_date, asl, lagab, medal_score = row
        else:
            messages = today = warnings = level = 0
            join_date = asl = lagab = medal_score = None
        warning_display = f"{warnings}/{warning_limit}"
        medal_display = str(medal_score) if medal_score and medal_score > 0 else "ندارد"
        ZWSP = "\u200B"
        if not user_name or user_name == "مشاهده":
            user_name = "مشاهده" + (ZWSP * (user_rank + 1))
        if join_date:
            try:
                date_obj = datetime.strptime(join_date, "%Y-%m-%d")
                import jdatetime
                join_display = jdatetime.date.fromgregorian(date=date_obj).strftime("%Y/%m/%d")
            except:
                join_display = join_date
        else:
            join_display = "ندارد"
        asl_display = asl if asl else "تنظیم نشده"
        lagab_display = lagab if lagab else "تنظیم نشده"
        rlm = "\u200F"
        guid_line = f"{rlm}🆔:/--♡->{user_guid}"
        title = "آمار شما" if is_self else "آمار کاربر"
        return f"""━━━━━━━━━━━━━━━
(📊) -♡- >{{ {title} }} <¥>
━━━━━━━━━━━━━━━
👤 اکانت کاربر: {user_name}
⚡ سطح: {rank_text}
🌍 اصل: {asl_display}
🏷 لقب: {lagab_display}
⚠️ اخطار: {warning_display}
💬 پیام امروز: {today}
💬 کل پیام‌ها: {messages}
🏅 مدال: {medal_display}
📅 تاریخ عضویت: {join_display}
╮━━━━ گوید اکانت ━━━━╭ 
{guid_line}
━━━━━━━━━━━━━━━"""
    except Exception as e:
        print(f"Error in get_user_amar: {e}")
        rlm = "\u200F"
        guid_line = f"{rlm}-♡-> {user_guid}"
        title = "آمار شما" if is_self else "آمار کاربر"
        return f"""━━━━━━━━━━━━━━━
(📊) -♡- >{{ {title} }} <¥>
━━━━━━━━━━━━━━━
👤 اکانت کاربر: {user_name}
⚡ سطح: نامشخص
🌍 اصل: تنظیم نشده
🏷 لقب: تنظیم نشده
⚠️ اخطار: 0/%s
💬 پیام امروز: 0
💬 کل پیام‌ها: 0
🏅 مدال: ندارد
📅 تاریخ عضویت: نامشخص
╮━━━━ گوید اکانت ━━━━╭ 
{guid_line}
━━━━━━━━━━━━━━━"""

def get_start_keypad(user_guid):
    if user_guid == OWNER_ID:
        # همان منوی قبلی برای سازنده
        return {
            "rows": [
                {"buttons": [{"id": "start_panel", "type": "Simple", "button_text": "⚙️ پنل مدیریت"}]},
                {"buttons": [{"id": "tabl_pan", "type": "Simple", "button_text": "⚙️ پنل تبلیغات"}]},
                {"buttons": [{"id": "start_helpo", "type": "Simple", "button_text": "⚙️ راهنما"}]}
            ],
            "resize_keyboard": True,
            "one_time_keyboard": False
        }
    else:
        # دکمه‌های جدید برای کاربر عادی
        return {
            "rows": [
                {"buttons": [{"id": "user_stats", "type": "Simple", "button_text": "📊 آمار من"}]},
                {"buttons": [{"id": "user_subscription", "type": "Simple", "button_text": "📅 مدت اشتراک"}]},
                {"buttons": [{"id": "user_active_groups", "type": "Simple", "button_text": "📋 گروه‌های فعال"}]},
                {"buttons": [{"id": "user_price", "type": "Simple", "button_text": "💰 قیمت اشتراک"},
                 {"id": "user_contact", "type": "Simple", "button_text": "📞 پشتیبانی"}]},
            ],
            "resize_keyboard": True,
            "one_time_keyboard": False
        }

def get_owner_panel_keypad():
    return {
        "rows": [
            {"buttons": [{"id": "owner_stats", "type": "Simple", "button_text": "📊 آمار کلی"}, {"id": "owner_groups", "type": "Simple", "button_text": "📋 لیست گروه‌ها"}]},
            {"buttons": [{"id": "owner_add_group", "type": "Simple", "button_text": "➕ افزودن گروه"}, {"id": "owner_remove_group", "type": "Simple", "button_text": "➖ حذف گروه"}]},
            {"buttons": [{"id": "owner_toggle_mode", "type": "Simple", "button_text": "🔄 حالت ربات"}, {"id": "owner_broadcast", "type": "Simple", "button_text": "📢 ارسال همگانی"}]},
            {"buttons": [{"id": "owner_back", "type": "Simple", "button_text": "🔙 بازگشت"}]}
        ],
        "resize_keyboard": True,
        "one_time_keyboard": False
    }
def get_owner_panelt_keypad():
    return {
        "rows": [
            {"buttons": [{"id": "owner_banner", "type": "Simple", "button_text": "📣 ثبت بنر"}, {"id": "owner_exception_list", "type": "Simple", "button_text": "📋 لیست استثنا"}]},
            {"buttons": [{"id": "owner_exception", "type": "Simple", "button_text": "🚫 مدیریت استثنا"}, {"id": "owner_stop_banner", "type": "Simple", "button_text": "⏹ توقف بنر"}]},
            {"buttons": [{"id": "owner_back", "type": "Simple", "button_text": "🔙 بازگشت"}]}
        ],
        "resize_keyboard": True,
        "one_time_keyboard": False
    }


_api_call_func = None


def set_api_call_func(func):
    global _api_call_func
    _api_call_func = func

def _api_call(method, data=None):
    if _api_call_func is None:
        raise Exception("api_call function not set! Call set_api_call_func first")
    return _api_call_func(method, data)

def get_user_subscription_info(cursor, user_guid):
    """
    نمایش اشتراک کاربر در گروه‌هایی که نقش مالک یا ادمین دارد.
    """
    cursor.execute("""
        SELECT groups.guid, allowed_groups.expires_at 
        FROM allowed_groups 
        JOIN groups ON groups.guid = allowed_groups.group_guid
        WHERE (groups.owner = %s OR groups.admin1 = %s OR groups.admin2 = %s OR groups.admin3 = %s)
    """, (user_guid, user_guid, user_guid, user_guid))
    rows = cursor.fetchall()
    if not rows:
        return "📭 شما در هیچ گروهی مالک یا ادمین نیستید."
    text = "━━━━━━━━━━━━━━━━━━━━\n📅 وضعیت اشتراک شما در گروه‌ها:\n━━━━━━━━━━━━━━━━━━━━\n"
    for guid, expires_at in rows:
        group_name = get_chat_title(guid)
        if expires_at and expires_at > int(time.time()):
            remaining = expires_at - int(time.time())
            days = remaining // 86400
            hours = (remaining % 86400) // 3600
            expiry_str = f"{days} روز و {hours} ساعت" if days > 0 else f"{hours} ساعت"
            status = "✅ فعال"
        else:
            expiry_str = "منقضی شده"
            status = "❌ غیرفعال"
        text += f"👥 {group_name}\n🆔 {guid}\n{status} - {expiry_str}\n━━━━━━━━━━━━━━━━━━━━\n"
    return text
    
def get_user_managed_groups(cursor, user_guid):
    cursor.execute("""
        SELECT guid, active, owner FROM groups 
        WHERE (owner = %s OR admin1 = %s OR admin2 = %s OR admin3 = %s)
    """, (user_guid, user_guid, user_guid, user_guid))
    rows = cursor.fetchall()
    if not rows:
        return "📭 شما در هیچ گروهی مدیریت ندارید."
    text = "━━━━━━━━━━━━━━━━━━━━\n📋 گروه‌هایی که مدیریت می‌کنید:\n━━━━━━━━━━━━━━━━━━━━\n"
    for guid, active, owner in rows:
        group_name = get_chat_title(guid)
        status = "✅ فعال" if active else "❌ غیرفعال"
        role = "مالک" if owner == user_guid else "ادمین"
        text += f"👥 {group_name}\n🆔 {guid}\n🔰 {role} - {status}\n━━━━━━━━━━━━━━━━━━━━\n"
    return text
def set_chat_keypad(chat_id, keypad):
    payload = {"chat_id": chat_id, "chat_keypad_type": "New", "chat_keypad": keypad}
    return _api_call("editChatKeypad", payload)

def remove_chat_keypad(chat_id):
    payload = {"chat_id": chat_id, "chat_keypad_type": "Remove"}
    return _api_call("editChatKeypad", payload)

def get_group_amar(cursor, group_guid, group_name, member_count=None):
    try:
        cursor.execute("SELECT COUNT(DISTINCT user_guid) FROM user_stats WHERE group_guid=%s", (group_guid,))
        total_members = cursor.fetchone()[0] or 0
        if member_count is not None:
            total_members = member_count
        
        cursor.execute("SELECT SUM(messages_count) FROM user_stats WHERE group_guid=%s", (group_guid,))
        total_messages = cursor.fetchone()[0] or 0
        
        today = datetime.now().strftime("%Y-%m-%d")
        cursor.execute("SELECT SUM(today_messages) FROM user_stats WHERE group_guid=%s AND last_date=%s", 
                       (group_guid, today))
        today_messages = cursor.fetchone()[0] or 0
        
        current_time = int(time.time())
        cursor.execute("SELECT COUNT(*) FROM mutes WHERE group_guid=%s AND until_time > %s", (group_guid, current_time))
        muted_count = cursor.fetchone()[0] or 0
        
        cursor.execute("SELECT COUNT(*) FROM bans WHERE group_guid=%s", (group_guid,))
        banned_count = cursor.fetchone()[0] or 0
        
        cursor.execute("SELECT SUM(warnings) FROM user_stats WHERE group_guid=%s", (group_guid,))
        total_warnings = cursor.fetchone()[0] or 0
        
        cursor.execute("SELECT owner, admin1, admin2, admin3 FROM groups WHERE guid=%s", (group_guid,))
        row = cursor.fetchone()
        admin_count = 0
        if row:
            if row[0]: admin_count += 1 
            if row[1]: admin_count += 1   
            if row[2]: admin_count += 1   
            if row[3]: admin_count += 1   
        
        cursor.execute("SELECT group_status FROM group_settings WHERE group_guid=%s", (group_guid,))
        group_status_row = cursor.fetchone()
        group_status = "باز" if (group_status_row and group_status_row[0] == 1) else "بسته"
        
        cursor.execute("SELECT chatbot FROM group_settings WHERE group_guid=%s", (group_guid,))
        chatbot_row = cursor.fetchone()
        chatbot_status = "روشن" if (chatbot_row and chatbot_row[0] == 1) else "خاموش"
        ai_status = chatbot_status
        
        cursor.execute("SELECT value FROM bot_state WHERE `key`='bot_mode'")
        mode_row = cursor.fetchone()
        subscription_mode = (mode_row and mode_row[0] == "subscription")
        subscription_status = "فعال" if subscription_mode else "غیرفعال"
        expires_at = None
        cursor.execute("SELECT expires_at FROM allowed_groups WHERE group_guid=%s", (group_guid,))
        exp_row = cursor.fetchone()
        if exp_row:
            expires_at = exp_row[0]

        if expires_at and expires_at > int(time.time()):
            remaining_seconds = expires_at - int(time.time())
            days = remaining_seconds // 86400
            hours = (remaining_seconds % 86400) // 3600
            if days > 0:
                remaining_str = f"{days} روز و {hours} ساعت"
            else:
                remaining_str = f"{hours} ساعت"
            expiry_datetime = datetime.fromtimestamp(expires_at)
            expiry_shamsi = jdatetime.date.fromgregorian(date=expiry_datetime).strftime("%Y/%m/%d")
            expiry_time = expiry_datetime.strftime(" %H:%M")
            expiry_date_str = f"{expiry_shamsi}{expiry_time}"
        else:
            expiry_date_str = "نامشخص"
            remaining_str = "نامشخص"
        
        return f"""━━━━━━━━━━━━━━━
(📊) -♡- >{{ آمار گروه }} <¥> 
━━━━━━━━━━━━━━━
🔱اسم گروه: {group_name}
🔱عضوهای فعال: {total_members}
💬 پیام‌ها: {total_messages}
💬 پیام‌های امروز: {today_messages}
⚠️ تعداد اخطار : {total_warnings}
🔇 سکوت ها: {muted_count}
🚫 بن شده: {banned_count}
⚖ تعداد مالک ادمین: {admin_count}
💰 وضعیت اشتراک: {subscription_status}
📅 انقضا: {expiry_date_str}
⏳ باقی‌مانده: {remaining_str}
━━━━━━━━━━━━━━━
♦ حذف پیام ها
♦ حذف پیام (عدد) 
♦ حذف (ریبلای) 
━━━━━━━━━━━━━━━
🎤 سخنگو: {chatbot_status}
🤖 هوش مصنوعی: {ai_status}
━━━━━━━━━━━━━━━
🔺گروه: {group_status}
━━━━━━━━━━━━━━━"""
    except Exception as e:
        print(f"Error in get_group_amar: {e}")
        return f"""━━━━━━━━━━━━━━━
(📊) -♡- >{{ آمار گروه }} <¥> 
━━━━━━━━━━━━━━━
🔱اسم گروه: {group_name}
🔱عضوهای فعال: 0
💬 پیام‌ها: 0
💬 پیام‌های امروز: 0
🚩 پیام حذف شده: 0
⚠️ تعداد اخطار : 0
🔇 سکوت ها: 0
🚫 بن شده: 0
⚖ تعداد مالک ادمین: 0
💰 وضعیت اشتراک: نامشخص
📅 انقضا: نامشخص
⏳ باقی‌مانده: نامشخص
━━━━━━━━━━━━━━━
♦ حذف پیام ها
♦ حذف پیام (عدد) 
♦ حذف (ریبلای) 
━━━━━━━━━━━━━━━
🎤 سخنگو: خاموش
🤖 هوش مصنوعی: خاموش
━━━━━━━━━━━━━━━
🔺گروه: باز
━━━━━━━━━━━━━━━"""

def get_sereshgari_list():
    return """━━━━━━━━━━━━━━━
(📋) -♡- >{ لیست سرگرمی } <¥> 
━━━━━━━━━━━━━━━
1.  فال - فال عمومی
2. جوک - یه جوک بامزه
3. داستان - داستان کوتاه
4. چیستان - چیستان ببینید
5. جراعت - یک کاری
6. حقیقت - یک سوال 
━━━━━━━━━━━━━━━
🎲 بازی و شانس
تاس - انداختن تاس
سکه - سکه بینداز
━━━━━━━━━━━━━━━
🏅بازی برای گرفتن مدال
━━━━━━━━━━━━━━━
✂️ سنگ کاغذ قیچی
سنگ - بازی با ربات
کاغذ - بازی با ربات
قیچی - بازی با ربات
برای هر برنده شدن یک مدال 🏅دریافت می کنید
━━━━━━━━━━━━━━━
چالش -  یک سوال پورسیده میشود
به شکل نظرسنجی با جواب صحیح 
 یک مدال 🏅 دریافت می کنید
━━━━━━━━━━━━━━━
برای تماشی مدال🏅  آمارم
━━━━━━━━━━━━━━━"""



def get_date_time():
    now_gregorian = dt.datetime.now()
    now_jalali = jdatetime.datetime.now()
    
    persian_months = ['فروردین', 'اردیبهشت', 'خرداد', 'تیر', 'مرداد', 'شهریور', 'مهر', 'آبان', 'آذر', 'دی', 'بهمن', 'اسفند']
    persian_weekdays = {
        0: "شنبه",
        1: "یک‌شنبه",
        2: "دوشنبه",
        3: "سه‌شنبه",
        4: "چهارشنبه",
        5: "پنج‌شنبه",
        6: "جمعه"
    }
    
    weekday_name = persian_weekdays[now_jalali.weekday()]
    shamsi_date = f"{weekday_name} {now_jalali.day} {persian_months[now_jalali.month-1]} {now_jalali.year}"
    gregorian_date = now_gregorian.strftime("%A %d %B %Y")
    
    time_24 = now_jalali.strftime("%H:%M:%S")
    time_12 = now_gregorian.strftime("%I:%M:%S %p")
    time_12_fa = time_12.replace("AM", "قبل از ظهر").replace("PM", "بعد از ظهر")
    
    return {
        'shamsi': shamsi_date,
        'gregorian': gregorian_date,
        'time_24': time_24,
        'time_12': time_12_fa
    }

def learn_question(cursor, group_guid, question, answer):
    cursor.execute("REPLACE INTO chatbot (question, answer, group_guid) VALUES (%s, %s, %s)",
                   (question.lower().strip(), answer, group_guid))

def get_answer(cursor, group_guid, question):
    cursor.execute("SELECT answer FROM chatbot WHERE group_guid=%s AND question=%s", 
                   (group_guid, question.lower().strip()))
    result = cursor.fetchone()
    return result[0] if result else None

def play_game(game_name, user_guid):
    games = {'تاس': random.randint(1, 6), 'دارت': random.randint(1, 20), 'فوتبال دستی': random.choice(['پیروزی', 'باخت', 'مساوی']), 'ماشین قمار': random.randint(0, 100), 'پیش‌بینی': random.choice(['بله', 'خیر', 'شاید', 'نامشخص'])}
    if game_name in games:
        return f"🎲 نتیجه: {games[game_name]}"
    riddles = {'چیست که هرچه بیشتر از آن برداری، بزرگتر میشود؟': 'گودال', 'آن چیست که بدون زبان حرف میزند؟': 'ایمیل', 'کدام کلید باز نمی‌شود؟': 'کلید برنامه نویسی'}
    if 'معما' in game_name:
        riddle = random.choice(list(riddles.keys()))
        return f"🎭 معمای جدید:\n{riddle}\n\nپاسخ خود را بفرستید..."
    return None

def parse_time_to_seconds(time_str):
    time_str = time_str.strip()
    if time_str.isdigit():
        return int(time_str) * 60
    match = re.match(r'(\d+)\s*(ساعت|دقیقه|ثانیه)', time_str)
    if match:
        value = int(match.group(1))
        unit = match.group(2)
        if unit == 'ساعت':
            return value * 3600
        elif unit == 'دقیقه':
            return value * 60
        elif unit == 'ثانیه':
            return value
    return None