import telebot
import random
import sqlite3
from datetime import datetime, timedelta

TOKEN = '8380503837:AAFQswMYOwoDyi_ktbYpauGQd8xHwBv4b7w'
bot = telebot.TeleBot(TOKEN)

SALES_CONTACTS = "@SL1XAL @vkanerhanov"

COUNTRY_PREFIXES = {
    'USA': '+1',
    'UK': '+44',
    'Russia': '+7',
    'Ukraine': '+380',
    'India': '+91',
    'Bangladesh': '+880',
    'Myanmar': '+95'
}

EXCLUSIVE_PRICES = {
    '+777': 'Цена по запросу',
    '+888': '150₽ (полный) / 200₽ (короткий)',
    '+999': '250₽ (полный) / 300₽ (короткий)',
    '+000': '500₽ (полный) / 600₽ (короткий)'
}

def get_db():
    return sqlite3.connect('/var/www/html/messenger/messenger.db')

def generate_code():
    return str(random.randint(100000, 999999))

def generate_regular_number(prefix):
    if prefix == '+7':
        return prefix + str(random.randint(9000000000, 9999999999))
    elif prefix == '+380':
        return prefix + str(random.randint(500000000, 999999999))
    elif prefix == '+1':
        return prefix + str(random.randint(2000000000, 9999999999))
    elif prefix == '+44':
        return prefix + str(random.randint(7000000000, 7999999999))
    elif prefix == '+91':
        return prefix + str(random.randint(6000000000, 9999999999))
    elif prefix == '+880':
        return prefix + str(random.randint(1000000000, 1999999999))
    elif prefix == '+95':
        return prefix + str(random.randint(100000000, 999999999))
    else:
        return prefix + str(random.randint(1000000000, 9999999999))

def generate_exclusive_number(prefix):
    if prefix in ['+888', '+999', '+000']:
        full = prefix + str(random.randint(10000000, 99999999))
        short = prefix + str(random.randint(1000, 9999))
        return random.choice([full, short])
    elif prefix == '+777':
        return prefix + str(random.randint(10000000, 99999999))
    return prefix + str(random.randint(10000000, 99999999))

@bot.message_handler(commands=['start'])
def start(message):
    markup = telebot.types.InlineKeyboardMarkup(row_width=2)
    markup.add(
        telebot.types.InlineKeyboardButton("Получить номер", callback_data="get_number"),
        telebot.types.InlineKeyboardButton("Прайс", callback_data="price"),
        telebot.types.InlineKeyboardButton("Поддержка", callback_data="support")
    )
    bot.send_message(
        message.chat.id,
        "SpicGram",
        reply_markup=markup
    )

@bot.callback_query_handler(func=lambda call: call.data == "get_number")
def get_number_callback(call):
    markup = telebot.types.InlineKeyboardMarkup(row_width=2)
    markup.add(
        telebot.types.InlineKeyboardButton("США +1", callback_data="country_USA"),
        telebot.types.InlineKeyboardButton("UK +44", callback_data="country_UK"),
        telebot.types.InlineKeyboardButton("Россия +7", callback_data="country_Russia"),
        telebot.types.InlineKeyboardButton("Украина +380", callback_data="country_Ukraine"),
        telebot.types.InlineKeyboardButton("Индия +91", callback_data="country_India"),
        telebot.types.InlineKeyboardButton("Бангладеш +880", callback_data="country_Bangladesh"),
        telebot.types.InlineKeyboardButton("Мьянма +95", callback_data="country_Myanmar")
    )
    markup.add(
        telebot.types.InlineKeyboardButton("+777", callback_data="exclusive_777"),
        telebot.types.InlineKeyboardButton("+888", callback_data="exclusive_888"),
        telebot.types.InlineKeyboardButton("+999", callback_data="exclusive_999"),
        telebot.types.InlineKeyboardButton("+000", callback_data="exclusive_000")
    )
    bot.edit_message_text(
        chat_id=call.message.chat.id,
        message_id=call.message.message_id,
        text="Выберите тип номера:",
        reply_markup=markup
    )

@bot.callback_query_handler(func=lambda call: call.data.startswith("country_"))
def country_callback(call):
    country = call.data.replace("country_", "")
    prefix = COUNTRY_PREFIXES.get(country, '+1')
    number = generate_regular_number(prefix)
    code = generate_code()
    expires = (datetime.now() + timedelta(minutes=5)).strftime('%Y-%m-%d %H:%M:%S')
    
    try:
        conn = get_db()
        c = conn.cursor()
        c.execute(
            "INSERT INTO verification_codes (phone, code, telegram_id, expires_at) VALUES (?, ?, ?, ?)",
            (number, code, call.message.chat.id, expires)
        )
        conn.commit()
        conn.close()
        
        bot.send_message(
            call.message.chat.id,
            f"Номер: {number}\nКод: {code}\n\nКод действителен 5 минут."
        )
    except Exception as e:
        bot.send_message(call.message.chat.id, "Ошибка. Попробуйте позже.")

@bot.callback_query_handler(func=lambda call: call.data.startswith("exclusive_"))
def exclusive_callback(call):
    prefix_map = {
        '777': '+777', '888': '+888', '999': '+999', '000': '+000'
    }
    prefix = prefix_map.get(call.data.replace("exclusive_", ""), '+888')
    number = generate_exclusive_number(prefix)
    code = generate_code()
    expires = (datetime.now() + timedelta(minutes=5)).strftime('%Y-%m-%d %H:%M:%S')
    
    try:
        conn = get_db()
        c = conn.cursor()
        c.execute(
            "INSERT INTO verification_codes (phone, code, telegram_id, expires_at) VALUES (?, ?, ?, ?)",
            (number, code, call.message.chat.id, expires)
        )
        conn.commit()
        conn.close()
        
        bot.send_message(
            call.message.chat.id,
            f"Номер: {number}\nКод: {code}\n\nЦена: {EXCLUSIVE_PRICES.get(prefix, '')}\nДля покупки: {SALES_CONTACTS}\n\nКод действителен 5 минут."
        )
    except Exception as e:
        bot.send_message(call.message.chat.id, "Ошибка. Попробуйте позже.")

@bot.callback_query_handler(func=lambda call: call.data == "price")
def price_callback(call):
    text = (
        "Прайс SpicGram\n\n"
        "Премиум подписка:\n"
        "1 месяц - 99₽\n"
        "3 месяца - 290₽\n"
        "6 месяцев - 580₽\n"
        "12 месяцев - 1,160₽\n"
        "2 года - 2,320₽\n\n"
        "Звезды:\n"
        "1 звезда - 0.4₽\n"
        "100 звезд - 40₽\n"
        "1000 звезд - 400₽\n\n"
        "Эксклюзивные номера:\n"
        "+888 (полный) - 150₽\n"
        "+888 (короткий) - 200₽\n"
        "+999 (полный) - 250₽\n"
        "+999 (короткий) - 300₽\n"
        "+000 (полный) - 500₽\n"
        "+000 (короткий) - 600₽\n\n"
        f"Контакты: {SALES_CONTACTS}"
    )
    bot.send_message(call.message.chat.id, text)

@bot.callback_query_handler(func=lambda call: call.data == "support")
def support_callback(call):
    bot.send_message(
        call.message.chat.id,
        f"Поддержка: @spicgram_support\nПокупка: {SALES_CONTACTS}\nКанал: @spicgram_news"
    )

if __name__ == '__main__':
    print("Бот запущен...")
    bot.infinity_polling()
