import sqlite3


def create_tables():
    conn = sqlite3.connect('bot_klining.db')
    cursor = conn.cursor()

    cursor.execute('''
    CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY,
        telegram_id INTEGER UNIQUE,
        name TEXT,
        phone TEXT
    )
    ''')

    cursor.execute('''
    CREATE TABLE IF NOT EXISTS addresses (
        id INTEGER PRIMARY KEY,
        user_id INTEGER,
        address TEXT,
        FOREIGN KEY(user_id) REFERENCES users(id)
    )
    ''')

    cursor.execute('''
    CREATE TABLE IF NOT EXISTS orders (
        id INTEGER PRIMARY KEY,
        user_id INTEGER,
        address TEXT,
        cleaning_time TEXT,
        cleaning_type TEXT,
        payment_method TEXT,
        order_id TEXT UNIQUE,
        FOREIGN KEY(user_id) REFERENCES users(id)
    )
    ''')

    cursor.execute('''
    CREATE TABLE IF NOT EXISTS logs (
        id INTEGER PRIMARY KEY,
        user_id INTEGER,
        action TEXT,
        timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY(user_id) REFERENCES users(id)
    )
    ''')

    conn.commit()
    conn.close()

def add_user(telegram_id, name, phone):
    conn = sqlite3.connect('bot_klining.db')
    cursor = conn.cursor()
    cursor.execute('INSERT OR IGNORE INTO users (telegram_id, name, phone) VALUES (?, ?, ?)', (telegram_id, name, phone))
    conn.commit()
    conn.close()

def update_user_name(telegram_id, name):
    conn = sqlite3.connect('bot_klining.db')
    cursor = conn.cursor()
    cursor.execute('UPDATE users SET name = ? WHERE telegram_id = ?', (name, telegram_id))
    conn.commit()
    conn.close()

def update_user_phone(telegram_id, phone):
    conn = sqlite3.connect('bot_klining.db')
    cursor = conn.cursor()
    cursor.execute('UPDATE users SET phone = ? WHERE telegram_id = ?', (phone, telegram_id))
    conn.commit()
    conn.close()

def add_address(telegram_id, address):
    conn = sqlite3.connect('bot_klining.db')
    cursor = conn.cursor()
    cursor.execute('SELECT id FROM users WHERE telegram_id = ?', (telegram_id,))
    user_id = cursor.fetchone()[0]
    cursor.execute('INSERT INTO addresses (user_id, address) VALUES (?, ?)', (user_id, address))
    conn.commit()
    conn.close()

def delete_address(telegram_id, address):
    conn = sqlite3.connect('bot_klining.db')
    cursor = conn.cursor()
    cursor.execute('SELECT id FROM users WHERE telegram_id = ?', (telegram_id,))
    user_id = cursor.fetchone()[0]
    cursor.execute('DELETE FROM addresses WHERE user_id = ? AND address = ?', (user_id, address))
    conn.commit()
    conn.close()