import streamlit as st
import pandas as pd
import qrcode
from io import BytesIO
import base64
import sqlite3
import bcrypt
import uuid

# Initialize session state
if 'logged_in' not in st.session_state:
    st.session_state.logged_in = False
    st.session_state.username = None
    st.session_state.is_admin = False

# Database setup
conn = sqlite3.connect('users.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS users
             (username TEXT PRIMARY KEY, password TEXT, is_admin INTEGER)''')
c.execute('''CREATE TABLE IF NOT EXISTS payments
             (id INTEGER PRIMARY KEY, username TEXT, amount REAL, timestamp DATETIME DEFAULT CURRENT_TIMESTAMP)''')
conn.commit()

# Helper functions
def hash_password(password):
    return bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode()

def check_password(password, hashed_password):
    return bcrypt.checkpw(password.encode(), hashed_password.encode())

def generate_qr_code(data):
    qr = qrcode.QRCode(version=1, box_size=10, border=5)
    qr.add_data(data)
    qr.make(fit=True)
    img = qr.make_image(fill_color="black", back_color="white")
    buffered = BytesIO()
    img.save(buffered, format="PNG")
    return base64.b64encode(buffered.getvalue()).decode()

# Admin functions
def register_user(username, password, is_admin=False):
    hashed_password = hash_password(password)
    c.execute("INSERT INTO users (username, password, is_admin) VALUES (?, ?, ?)",
              (username, hashed_password, int(is_admin)))
    conn.commit()

def get_payment_stats():
    df = pd.read_sql_query("SELECT * FROM payments", conn)
    return df

# User functions
def login(username, password):
    c.execute("SELECT password, is_admin FROM users WHERE username = ?", (username,))
    result = c.fetchone()
    if result and check_password(password, result[0]):
        st.session_state.logged_in = True
        st.session_state.username = username
        st.session_state.is_admin = bool(result[1])
        return True
    return False

def make_payment(username, amount):
    c.execute("INSERT INTO payments (username, amount) VALUES (?, ?)", (username, amount))
    conn.commit()

# Streamlit app
def main():
    st.title("Crypto Payment Admin Panel")

    if not st.session_state.logged_in:
        tab1, tab2 = st.tabs(["Login", "Register"])
        
        with tab1:
            st.subheader("Login")
            username = st.text_input("Username")
            password = st.text_input("Password", type="password")
            if st.button("Login"):
                if login(username, password):
                    st.success("Logged in successfully!")
                    st.experimental_rerun()
                else:
                    st.error("Invalid username or password")

        with tab2:
            if st.session_state.is_admin:
                st.subheader("Register New User")
                new_username = st.text_input("New Username")
                new_password = st.text_input("New Password", type="password")
                is_admin = st.checkbox("Is Admin")
                if st.button("Register"):
                    try:
                        register_user(new_username, new_password, is_admin)
                        st.success("User registered successfully!")
                    except sqlite3.IntegrityError:
                        st.error("Username already exists")
            else:
                st.warning("Only admins can register new users")

    else:
        st.sidebar.title(f"Welcome, {st.session_state.username}")
        st.sidebar.button("Logout", on_click=lambda: setattr(st.session_state, 'logged_in', False))

        if st.session_state.is_admin:
            st.subheader("Admin Dashboard")
            stats = get_payment_stats()
            st.dataframe(stats)
            
            st.subheader("Register New User")
            new_username = st.text_input("New Username")
            new_password = st.text_input("New Password", type="password")
            is_admin = st.checkbox("Is Admin")
            if st.button("Register"):
                try:
                    register_user(new_username, new_password, is_admin)
                    st.success("User registered successfully!")
                except sqlite3.IntegrityError:
                    st.error("Username already exists")
        else:
            st.subheader("User Dashboard")
            amount = st.number_input("Payment Amount", min_value=0.01, step=0.01)
            if st.button("Generate Payment QR"):
                payment_data = f"pay:{st.session_state.username}:{amount}"
                qr_code = generate_qr_code(payment_data)
                st.image(f"data:image/png;base64,{qr_code}", caption="Scan to pay")
                make_payment(st.session_state.username, amount)
                st.success("Payment recorded successfully!")

if __name__ == "__main__":
    main() ImportError: Unable to import required dependencies: numpy: Error importing numpy: you should not try to import numpy from its source directory; please exit the numpy source tree, and relaunch your python interpreter from there.
Traceback:

File "/home/m/adminka/venv/lib/python3.12/site-packages/streamlit/runtime/scriptrunner/exec_code.py", line 88, in exec_func_with_error_handling
    result = func()
             ^^^^^^
File "/home/m/adminka/venv/lib/python3.12/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 579, in code_to_exec
    exec(code, module.__dict__)
File "/home/m/adminka/st.py", line 2, in <module>
    import pandas as pd
File "/home/m/adminka/venv/lib/python3.12/site-packages/pandas/__init__.py", line 19, in <module>
    raise ImportError(