import sys, os, time, json, datetime, requests, pymysql, string, random
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

# ZORG: Ensure we can import from the local Binance directory
BINANCE_DIR = os.path.dirname(os.path.abspath(__file__))
if BINANCE_DIR not in sys.path: sys.path.insert(0, BINANCE_DIR)
PAYMENT_DIR = os.path.dirname(BINANCE_DIR)
BASE_DIR = os.path.dirname(PAYMENT_DIR)
if BASE_DIR not in sys.path: sys.path.insert(0, BASE_DIR)

from binance_imap import check_binance_email

BOT_TOKEN = "8690070480:AAHfl0bPp7XIEBXCxz07fIsHU3t0hCn29eY"
BINANCE_ID = "1221235491"
BINANCE_NICK = "Dear Nazari"
LOG_FILE = os.path.join(BASE_DIR, 'history.log')
DB_CFG = {'host': 'localhost', 'user': 'evisuyfj_GlobalDeviceCheckerBot', 'password': 'GlobalDeviceCheckerBot', 'database': 'evisuyfj_GlobalDeviceCheckerBot', 'cursorclass': pymysql.cursors.DictCursor, 'autocommit': True, 'charset': 'utf8mb4'}

def load_tz_config():
    offset_str = "+04:30"
    h, m = 4, 30
    dt_file = os.path.join(BASE_DIR, 'date-time.json')
    if os.path.exists(dt_file):
        try:
            with open(dt_file, 'r') as f:
                dt_cfg = json.load(f)
                offset_str = dt_cfg.get('db_offset', '+04:30')
                sign = -1 if offset_str.startswith('-') else 1
                parts = offset_str.replace('+', '').replace('-', '').split(':')
                h = sign * int(parts[0])
                m = sign * int(parts[1]) if len(parts) > 1 else 0
        except: pass
    return offset_str, datetime.timezone(datetime.timedelta(hours=h, minutes=m))

DB_TZ_OFFSET, LOCAL_TZ = load_tz_config()

def get_conn():
    try:
        conn = pymysql.connect(**DB_CFG)
        conn.cursor().execute(f"SET time_zone = '{DB_TZ_OFFSET}'")
        return conn
    except: return None

def edit_tg_message(chat_id, msg_id, text, kb=None):
    try:
        url = f"https://api.telegram.org/bot{BOT_TOKEN}/editMessageText"
        d = {'chat_id': chat_id, 'message_id': msg_id, 'text': text, 'parse_mode': 'HTML'}
        if kb: d['reply_markup'] = json.dumps(kb)
        requests.post(url, json=d, verify=False, timeout=5)
    except: pass

def gen_track_id(prefix):
    chars = string.ascii_lowercase + string.digits
    return f"{prefix}-" + ''.join(random.choices(chars, k=6))

def run():
    if len(sys.argv) < 6: return
    uid, cid, mid, inv_id = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]
    retry_count = int(sys.argv[5]) if len(sys.argv) > 5 else 0

    c = get_conn()
    if not c: return
    cur = c.cursor()
    cur.execute("SELECT amount, txid, created_at FROM invoices WHERE invoice_id=%s AND user_id=%s", (inv_id, uid))
    inv = cur.fetchone()
    c.close()

    if not inv: return
    amount, username = float(inv['amount']), inv['txid']
    target_date_str = inv['created_at'].strftime('%Y-%m-%d')
    found = False

    for attempt in range(1, 7):
        scan_txt = f"<b>⏳ Scanning Binance Network...</b>\nyour invoice id: <code>{inv_id}</code>\nChecking for your payment of <b>${amount:g}</b> from <b>{username}</b>.\n<blockquote> ├  To This Binance User\n │   ├ 🆔 <b>Binance ID:</b> <code>{BINANCE_ID}</code>\n │   └ 👤 <b>Nickname: {BINANCE_NICK}</b>\n └ I am waiting...</blockquote><i>Attempt {attempt}/6... Please wait up to 1 minute.</i>"
        edit_tg_message(cid, mid, scan_txt, {"inline_keyboard": [[{"text": "❌ Cancel payment", "callback_data": "cancel_draft"}]]})
        
        try: found = check_binance_email(amount, username, target_date_str)
        except: found = False
        
        if found:
            c = get_conn()
            if c:
                try:
                    c.begin()
                    c.cursor().execute("UPDATE invoices SET status = 'PAID' WHERE invoice_id = %s", (inv_id,))
                    c.cursor().execute("UPDATE users SET credit = credit + %s WHERE user_id = %s", (amount, uid))
                    trf_id = gen_track_id("TRF-AddPay")
                    c.cursor().execute("INSERT INTO transactions (user_id, amount, type, note, created_at, track_id) VALUES (%s, %s, 'CREDIT_ADD', %s, NOW(), %s)", (uid, amount, f"Binance Pay Auto (Sender: {username})", trf_id))
                    c.commit()
                    edit_tg_message(cid, mid, f"✅ <b>Payment Verified!</b>\n<blockquote>Your account has been credited with ${amount:g}.\nThank you for using our service.</blockquote>\n<b>Check your /Credit</b>")
                except: c.rollback()
                finally: c.close()
            return
            
        if attempt < 6: time.sleep(10)

    if not found:
        c = get_conn()
        if c:
            c.cursor().execute("UPDATE invoices SET status = 'FAILED' WHERE invoice_id = %s", (inv_id,))
            c.commit(); c.close()
        kb_list = []
        if retry_count < 3: kb_list.append([{"text": "🔄 Check Again", "callback_data": f"checkbinpay_{inv_id}||{retry_count+1}"}])
        kb_list.append([{"text": "📩 Report to Admin", "callback_data": f"reportbin_{inv_id}"}])
        kb_list.append([{"text": "❌ Cancel payment", "callback_data": "cancel_draft"}])
        txt = f"❌ <b>We could not verify your payment within 1 minute.</b>\n\n<b>📂 Payment Details:</b>\n ├ 👤 <b>Binance Username:</b> {username}\n ├ 💰 <b>Amount:</b> ${amount:g}\n └ 📅 <b>Date:</b> {target_date_str}\n\nPlease choose an option below:"
        edit_tg_message(cid, mid, txt, {"inline_keyboard": kb_list})

if __name__ == "__main__":
    run()