import requests
import time
import random
import string
import os
import json
from datetime import datetime

BOT_TOKEN = "48864561:I0E7K2ArkDgRKqEYNdNoDqcVEu6UZ-i4Lu0"
ADMIN_ID = '57541026'
BOT_USERNAME = "cantebot"
BASE_URL = f"https://tapi.bale.ai/bot{BOT_TOKEN}"
DB_FILE = "bot_database.json"

def load_db():
    if os.path.exists(DB_FILE):
        with open(DB_FILE, 'r') as f:
            return json.load(f)
    return {"users": {}, "withdraw_requests": [], "withdraw_counter": 0, "settings": {"invite_text": "سلام دوست عزیز با لینک من عضو شو:\nLINK", "invite_photo": None, "withdraw_amount": 100000}}

db = load_db()
users_db = db.get("users", {})
withdraw_requests = db.get("withdraw_requests", [])
withdraw_counter = db.get("withdraw_counter", 0)
settings_db = db.get("settings", {"invite_text": "سلام دوست عزیز با لینک من عضو شو:\nLINK", "invite_photo": None, "withdraw_amount": 100000})
pending_inputs = {}

def save_db_data():
    db = {
        "users": users_db,
        "withdraw_requests": withdraw_requests,
        "withdraw_counter": withdraw_counter,
        "settings": settings_db
    }
    with open(DB_FILE, 'w') as f:
        json.dump(db, f, indent=4)

def send_message(chat_id, text, reply_markup=None, parse_mode="Markdown"):
    url = f"{BASE_URL}/sendMessage"
    data = {"chat_id": chat_id, "text": text, "parse_mode": parse_mode}
    if reply_markup:
        data["reply_markup"] = reply_markup
    try:
        response = requests.post(url, json=data)
        return response.json()
    except Exception as e:
        print(f"Error sending message: {e}")
        return None

def send_photo(chat_id, photo, caption=None, reply_markup=None):
    url = f"{BASE_URL}/sendPhoto"
    data = {"chat_id": chat_id}
    files = {"photo": photo}
    if caption:
        data["caption"] = caption
    if reply_markup:
        data["reply_markup"] = reply_markup
    try:
        requests.post(url, data=data, files=files)
    except Exception as e:
        print(f"Error sending photo: {e}")

def edit_message_text(chat_id, message_id, text, reply_markup=None, parse_mode="Markdown"):
    url = f"{BASE_URL}/editMessageText"
    data = {"chat_id": chat_id, "message_id": message_id, "text": text, "parse_mode": parse_mode}
    if reply_markup:
        data["reply_markup"] = reply_markup
    try:
        requests.post(url, json=data)
    except Exception as e:
        print(f"Error editing message: {e}")

def answer_callback_query(callback_query_id, text=None, show_alert=False):
    url = f"{BASE_URL}/answerCallbackQuery"
    data = {"callback_query_id": callback_query_id}
    if text:
        data["text"] = text
    if show_alert:
        data["show_alert"] = show_alert
    try:
        requests.post(url, json=data)
    except Exception as e:
        print(f"Error answering callback: {e}")

def get_main_keyboard():
    return {
        "keyboard": [
            [{"text": "دعوت از دوستان"}, {"text": "کیف پول"}],
            [{"text": "درخواست برداشت"}]
        ],
        "resize_keyboard": True
    }

def get_admin_keyboard():
    return {
        "keyboard": [
            [{"text": "تنظیم متن دعوت"}, {"text": "تنظیم عکس دعوت"}],
            [{"text": "تنظیم مبلغ برداشت"}, {"text": "لیست درخواست‌ها"}],
            [{"text": "بازگشت"}]
        ],
        "resize_keyboard": True
    }

def get_cancel_keyboard():
    return {
        "keyboard": [
            [{"text": "انصراف"}]
        ],
        "resize_keyboard": True
    }

def handle_start(user_id, chat_id, message_id=None, args=None):
    if str(user_id) not in users_db:
        users_db[str(user_id)] = {"invited_by": None, "invite_count": 0, "balance": 0}
        save_db_data()
    
    if args:
        referrer_id = args
        if str(referrer_id) != str(user_id) and str(referrer_id) in users_db:
            users_db[str(user_id)]["invited_by"] = referrer_id
            users_db[str(referrer_id)]["invite_count"] += 1
            users_db[str(referrer_id)]["balance"] += 1000
            save_db_data()
            try:
                send_message(int(referrer_id), f"یک کاربر با لینک شما به بات پیوست.\nموجودی شما: {users_db[str(referrer_id)]['balance']} تومان")
            except:
                pass
    
    text = "به ربات خوش آمدید!"
    keyboard = get_main_keyboard()
    if message_id:
        edit_message_text(chat_id, message_id, text, reply_markup=keyboard)
    else:
        send_message(chat_id, text, reply_markup=keyboard)

def process_update(update):
    if "message" in update:
        message = update["message"]
        chat_id = message["chat"]["id"]
        user_id = message["from"]["id"]
        text = message.get("text")
        msg_id = message.get("message_id")
        photo = message.get("photo")
        
        if text:
            if text == "/start" or text.startswith("/start "):
                parts = text.split(" ")
                args = parts[1] if len(parts) > 1 else None
                handle_start(user_id, chat_id, args=args)
                return
            
            elif text == "/panel":
                if user_id == ADMIN_ID:
                    send_message(chat_id, "پنل مدیریت:", reply_markup=get_admin_keyboard())
                return
            
            elif text == "بازگشت":
                send_message(chat_id, "منوی اصلی:", reply_markup=get_main_keyboard())
                if user_id in pending_inputs:
                    del pending_inputs[user_id]
                return
            
            elif text == "انصراف":
                if user_id in pending_inputs:
                    del pending_inputs[user_id]
                send_message(chat_id, "عملیات لغو شد.", reply_markup=get_main_keyboard())
                return
            
            elif text == "دعوت از دوستان":
                link = f"https://ble.ir/{BOT_USERNAME}?start={user_id}"
                invite_text_template = settings_db.get("invite_text", "LINK")
                final_text = invite_text_template.replace("LINK", link)
                
                if settings_db.get("invite_photo"):
                    send_photo(chat_id, settings_db["invite_photo"], caption=final_text)
                else:
                    send_message(chat_id, final_text)
                return
            
            elif text == "کیف پول":
                user_data = users_db.get(str(user_id), {"balance": 0, "invite_count": 0})
                balance = user_data.get("balance", 0)
                invite_count = user_data.get("invite_count", 0)
                msg = f"💰 موجودی شما: {balance} تومان\n👥 تعداد دعوت‌ها: {invite_count}"
                send_message(chat_id, msg)
                return
            
            elif text == "درخواست برداشت":
                user_data = users_db.get(str(user_id), {"balance": 0})
                balance = user_data.get("balance", 0)
                withdraw_amount = settings_db.get("withdraw_amount", 100000)
                
                if balance < withdraw_amount:
                    send_message(chat_id, f"موجودی شما کافی نیست.\nحداقل موجودی برای برداشت: {withdraw_amount} تومان")
                    return
                
                pending_inputs[user_id] = {"step": "withdraw_card"}
                send_message(chat_id, "لطفا شماره کارت ۱۶ رقمی خود را وارد کنید:", reply_markup=get_cancel_keyboard())
                return
            
            elif text == "تنظیم متن دعوت" and user_id == ADMIN_ID:
                pending_inputs[user_id] = {"step": "waiting_text"}
                send_message(chat_id, "لطفا متن جدید را ارسال کنید (کلمه LINK در متن لینک کاربر خواهد بود):", reply_markup=get_cancel_keyboard())
                return
            
            elif text == "تنظیم عکس دعوت" and user_id == ADMIN_ID:
                pending_inputs[user_id] = {"step": "waiting_photo"}
                send_message(chat_id, "لطفا عکس جدید را ارسال کنید:", reply_markup=get_cancel_keyboard())
                return
            
            elif text == "تنظیم مبلغ برداشت" and user_id == ADMIN_ID:
                pending_inputs[user_id] = {"step": "waiting_withdraw_amount"}
                send_message(chat_id, f"مبلغ فعلی برداشت: {settings_db['withdraw_amount']} تومان\nلطفا مبلغ جدید را به تومان وارد کنید:", reply_markup=get_cancel_keyboard())
                return
            
            elif text == "لیست درخواست‌ها" and user_id == ADMIN_ID:
                pending_requests = [r for r in withdraw_requests if r["status"] == "pending"]
                if not pending_requests:
                    send_message(chat_id, "درخواست در انتظاری وجود ندارد.")
                    return
                
                for req in pending_requests:
                    user_info = users_db.get(str(req["user_id"]), {})
                    user_name = user_info.get("name", "نامشخص")
                    msg = f"درخواست #{req['id']}\n"
                    msg += f"کاربر: {user_name} (ID: {req['user_id']})\n"
                    msg += f"مبلغ: {req['amount']} تومان\n"
                    msg += f"شماره کارت: {req['card_number']}\n"
                    msg += f"صاحب کارت: {req['card_holder']}\n"
                    msg += f"تاریخ: {req['date']}"
                    
                    keyboard = {
                        "inline_keyboard": [
                            [
                                {"text": "✅ پرداخت شد", "callback_data": f"withdraw_confirm_{req['id']}"},
                                {"text": "❌ رد", "callback_data": f"withdraw_reject_{req['id']}"}
                            ]
                        ]
                    }
                    send_message(chat_id, msg, reply_markup=keyboard)
                return
            
            if user_id in pending_inputs:
                step = pending_inputs[user_id].get("step")
                
                if step == "waiting_text":
                    settings_db["invite_text"] = text
                    save_db_data()
                    send_message(chat_id, "متن دعوت با موفقیت تغییر کرد.", reply_markup=get_main_keyboard())
                    del pending_inputs[user_id]
                    return
                
                elif step == "waiting_withdraw_amount":
                    try:
                        amount = int(text)
                        if amount <= 0:
                            send_message(chat_id, "مبلغ باید بزرگتر از صفر باشد.")
                            return
                        settings_db["withdraw_amount"] = amount
                        save_db_data()
                        send_message(chat_id, f"مبلغ برداشت به {amount} تومان تغییر کرد.", reply_markup=get_main_keyboard())
                        del pending_inputs[user_id]
                    except ValueError:
                        send_message(chat_id, "لطفا یک عدد معتبر وارد کنید.")
                    return
                
                elif step == "withdraw_card":
                    if len(text) != 16 or not text.isdigit():
                        send_message(chat_id, "شماره کارت باید ۱۶ رقم و فقط شامل اعداد باشد.")
                        return
                    
                    pending_inputs[user_id]["card"] = text
                    pending_inputs[user_id]["step"] = "withdraw_name"
                    send_message(chat_id, "لطفا نام صاحب کارت را وارد کنید:", reply_markup=get_cancel_keyboard())
                    return
                
                elif step == "withdraw_name":
                    card = pending_inputs[user_id].get("card")
                    amount = settings_db.get("withdraw_amount", 100000)
                    now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                    
                    global withdraw_counter
                    withdraw_counter += 1
                    request_id = withdraw_counter
                    
                    user_info = users_db.get(str(user_id), {})
                    try:
                        user_name = f"@{message['from'].get('username', '')}" if message['from'].get('username') else f"{message['from'].get('first_name', '')} {message['from'].get('last_name', '')}".strip()
                    except:
                        user_name = "نامشخص"
                    
                    request = {
                        "id": request_id,
                        "user_id": user_id,
                        "user_name": user_name,
                        "amount": amount,
                        "card_number": card,
                        "card_holder": text,
                        "date": now,
                        "status": "pending"
                    }
                    
                    withdraw_requests.append(request)
                    users_db[str(user_id)]["balance"] -= amount
                    save_db_data()
                    
                    msg = f"✅ درخواست برداشت شما ثبت شد.\n"
                    msg += f"مبلغ: {amount} تومان\n"
                    msg += f"شماره کارت: {card}\n"
                    msg += f"صاحب کارت: {text}\n"
                    msg += f"تاریخ: {now}\n"
                    msg += f"شناسه درخواست: {request_id}\n"
                    msg += "درخواست شما در انتظار تایید ادمین است."
                    
                    send_message(chat_id, msg, reply_markup=get_main_keyboard())
                    
                    admin_msg = f"📋 درخواست برداشت جدید #{request_id}\n"
                    admin_msg += f"کاربر: {user_name} (ID: {user_id})\n"
                    admin_msg += f"مبلغ: {amount} تومان\n"
                    admin_msg += f"شماره کارت: {card}\n"
                    admin_msg += f"صاحب کارت: {text}\n"
                    admin_msg += f"تاریخ: {now}"
                    
                    admin_keyboard = {
                        "inline_keyboard": [
                            [
                                {"text": "✅ پرداخت شد", "callback_data": f"withdraw_confirm_{request_id}"},
                                {"text": "❌ رد", "callback_data": f"withdraw_reject_{request_id}"}
                            ]
                        ]
                    }
                    send_message(ADMIN_ID, admin_msg, reply_markup=admin_keyboard)
                    
                    del pending_inputs[user_id]
                    return
        
        if photo and user_id in pending_inputs:
            step = pending_inputs[user_id].get("step")
            if step == "waiting_photo":
                file_id = photo[-1]["file_id"]
                settings_db["invite_photo"] = file_id
                save_db_data()
                send_message(chat_id, "عکس دعوت با موفقیت تغییر کرد.", reply_markup=get_main_keyboard())
                del pending_inputs[user_id]
                return

    elif "callback_query" in update:
        call = update["callback_query"]
        call_id = call["id"]
        data = call["data"]
        chat_id = call["message"]["chat"]["id"]
        message_id = call["message"]["message_id"]
        user_id = call["from"]["id"]
        
        if data.startswith("withdraw_confirm_"):
            if user_id != ADMIN_ID:
                answer_callback_query(call_id, "شما دسترسی ندارید", True)
                return
            
            request_id = int(data.replace("withdraw_confirm_", ""))
            for req in withdraw_requests:
                if req["id"] == request_id and req["status"] == "pending":
                    req["status"] = "confirmed"
                    save_db_data()
                    
                    user_msg = f"✅ درخواست برداشت #{request_id} تایید شد.\n"
                    user_msg += "تسویه حساب با موفقیت انجام شد."
                    send_message(req["user_id"], user_msg)
                    
                    edit_message_text(chat_id, message_id, f"✅ درخواست #{request_id} تایید شد\n" + call["message"]["text"])
                    answer_callback_query(call_id, "تایید شد")
                    break
            return
        
        elif data.startswith("withdraw_reject_"):
            if user_id != ADMIN_ID:
                answer_callback_query(call_id, "شما دسترسی ندارید", True)
                return
            
            request_id = int(data.replace("withdraw_reject_", ""))
            for req in withdraw_requests:
                if req["id"] == request_id and req["status"] == "pending":
                    req["status"] = "rejected"
                    users_db[str(req["user_id"])]["balance"] += req["amount"]
                    save_db_data()
                    
                    user_msg = f"❌ درخواست برداشت #{request_id} رد شد.\n"
                    user_msg += f"مبلغ {req['amount']} تومان به کیف پول شما بازگردانده شد."
                    send_message(req["user_id"], user_msg)
                    
                    edit_message_text(chat_id, message_id, f"❌ درخواست #{request_id} رد شد\n" + call["message"]["text"])
                    answer_callback_query(call_id, "رد شد")
                    break
            return

def main():
    last_update_id = 0
    print("Bot started...")
    while True:
        try:
            url = f"{BASE_URL}/getUpdates?offset={last_update_id + 1}"
            response = requests.get(url)
            data = response.json()
            if data["ok"]:
                for result in data["result"]:
                    last_update_id = result["update_id"]
                    process_update(result)
            time.sleep(1)
        except Exception as e:
            print(f"Error: {e}")
            time.sleep(5)

if __name__ == "__main__":
    main()