# -*- coding: utf-8 -*-
import sqlite3
import jdatetime
from config import DB_NAME, INITIAL_SUPER_ADMIN

def init_db():
    conn = sqlite3.connect(DB_NAME)
    c = conn.cursor()
    c.execute("""
        CREATE TABLE IF NOT EXISTS users (
            user_id INTEGER PRIMARY KEY,
            has_favorites INTEGER DEFAULT 0,
            joined_date TEXT
        )
    """)
    try:
        c.execute("ALTER TABLE users ADD COLUMN joined_date TEXT")
    except sqlite3.OperationalError:
        pass

    c.execute("""
        CREATE TABLE IF NOT EXISTS admins (
            user_id INTEGER PRIMARY KEY
        )
    """)
    c.execute("""
        CREATE TABLE IF NOT EXISTS settings (
            key TEXT PRIMARY KEY,
            value TEXT
        )
    """)
    c.execute("""
        CREATE TABLE IF NOT EXISTS auto_channels (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            channel_id TEXT UNIQUE,
            times TEXT,
            status TEXT DEFAULT 'on'
        )
    """)
    conn.commit()

    default_settings = {
        "sleep_mode": "off",
        "forced_channel": "",
        "ad_text": "🌐 زرین قسط : zaringhest.com\n\nآدرس:\nمشهد، امامت ۷-۹، پاساژ عمارت، طبقه ۲+\nتلفن : 05136015020",
        "channel_ad_btn_status": "off",
        "channel_ad_btn_name": "📢 کانال اسپانسر",
        "channel_ad_btn_link": "https://t.me/zaringhest"
    }
    for k, v in default_settings.items():
        c.execute("INSERT OR IGNORE INTO settings (key, value) VALUES (?, ?)", (k, v))
    
    c.execute("INSERT OR IGNORE INTO admins (user_id) VALUES (?)", (INITIAL_SUPER_ADMIN,))
    conn.commit()
    conn.close()

def get_setting(key: str) -> str:
    conn = sqlite3.connect(DB_NAME)
    c = conn.cursor()
    c.execute("SELECT value FROM settings WHERE key = ?", (key,))
    row = c.fetchone()
    conn.close()
    return row[0] if row else ""

def set_setting(key: str, value: str):
    conn = sqlite3.connect(DB_NAME)
    c = conn.cursor()
    c.execute("INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)", (key, value))
    conn.commit()
    conn.close()

def is_admin(user_id: int) -> bool:
    if user_id == INITIAL_SUPER_ADMIN:
        return True
    conn = sqlite3.connect(DB_NAME)
    c = conn.cursor()
    c.execute("SELECT 1 FROM admins WHERE user_id = ?", (user_id,))
    res = c.fetchone()
    conn.close()
    return bool(res)

def add_admin(user_id: int):
    conn = sqlite3.connect(DB_NAME)
    c = conn.cursor()
    c.execute("INSERT OR IGNORE INTO admins (user_id) VALUES (?)", (user_id,))
    conn.commit()
    conn.close()

def remove_admin(user_id: int):
    if user_id == INITIAL_SUPER_ADMIN:
        return
    conn = sqlite3.connect(DB_NAME)
    c = conn.cursor()
    c.execute("DELETE FROM admins WHERE user_id = ?", (user_id,))
    conn.commit()
    conn.close()

def get_all_admins():
    conn = sqlite3.connect(DB_NAME)
    c = conn.cursor()
    c.execute("SELECT user_id FROM admins")
    rows = c.fetchall()
    conn.close()
    return [r[0] for r in rows]

def register_user(user_id: int):
    conn = sqlite3.connect(DB_NAME)
    c = conn.cursor()
    now_str = jdatetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S")
    c.execute("INSERT OR IGNORE INTO users (user_id, joined_date) VALUES (?, ?)", (user_id, now_str))
    conn.commit()
    conn.close()

def set_user_favorite(user_id: int, status: int):
    conn = sqlite3.connect(DB_NAME)
    c = conn.cursor()
    c.execute("UPDATE users SET has_favorites = ? WHERE user_id = ?", (status, user_id))
    conn.commit()
    conn.close()

def get_user_favorite_status(user_id: int) -> bool:
    conn = sqlite3.connect(DB_NAME)
    c = conn.cursor()
    c.execute("SELECT has_favorites FROM users WHERE user_id = ?", (user_id,))
    row = c.fetchone()
    conn.close()
    return bool(row[0]) if row else False

def get_total_users_count() -> int:
    conn = sqlite3.connect(DB_NAME)
    c = conn.cursor()
    c.execute("SELECT COUNT(*) FROM users")
    count = c.fetchone()[0]
    conn.close()
    return count

def get_all_user_ids() -> list:
    conn = sqlite3.connect(DB_NAME)
    c = conn.cursor()
    c.execute("SELECT user_id FROM users")
    rows = c.fetchall()
    conn.close()
    return [r[0] for r in rows]

def add_auto_channel(channel_id: str, times: str):
    conn = sqlite3.connect(DB_NAME)
    c = conn.cursor()
    c.execute("INSERT OR REPLACE INTO auto_channels (channel_id, times, status) VALUES (?, ?, 'on')", (channel_id, times))
    conn.commit()
    conn.close()

def remove_auto_channel(channel_db_id: int):
    conn = sqlite3.connect(DB_NAME)
    c = conn.cursor()
    c.execute("DELETE FROM auto_channels WHERE id = ?", (channel_db_id,))
    conn.commit()
    conn.close()

def update_channel_times(channel_db_id: int, times: str):
    conn = sqlite3.connect(DB_NAME)
    c = conn.cursor()
    c.execute("UPDATE auto_channels SET times = ? WHERE id = ?", (times, channel_db_id))
    conn.commit()
    conn.close()

def toggle_channel_status(channel_db_id: int):
    conn = sqlite3.connect(DB_NAME)
    c = conn.cursor()
    c.execute("SELECT status FROM auto_channels WHERE id = ?", (channel_db_id,))
    row = c.fetchone()
    if row:
        new_status = 'off' if row[0] == 'on' else 'on'
        c.execute("UPDATE auto_channels SET status = ? WHERE id = ?", (new_status, channel_db_id))
        conn.commit()
    conn.close()

def get_all_auto_channels():
    conn = sqlite3.connect(DB_NAME)
    c = conn.cursor()
    c.execute("SELECT id, channel_id, times, status FROM auto_channels")
    rows = c.fetchall()
    conn.close()
    return rows

def get_auto_channel_by_id(channel_db_id: int):
    conn = sqlite3.connect(DB_NAME)
    c = conn.cursor()
    c.execute("SELECT id, channel_id, times, status FROM auto_channels WHERE id = ?", (channel_db_id,))
    row = c.fetchone()
    conn.close()
    return row