import sqlite3
import datetime
import pandas as pd

DB_FILE = "work_log.db"

def get_connection():
    conn = sqlite3.connect(DB_FILE)
    return conn

def init_db():
    conn = get_connection()
    c = conn.cursor()
    c.execute('''
        CREATE TABLE IF NOT EXISTS work_days (
            date TEXT PRIMARY KEY,
            hours REAL DEFAULT 8.0,
            note TEXT
        )
    ''')
    conn.commit()
    conn.close()

def toggle_day(date_str):
    """Toggles a work day: adds if not exists, removes if exists."""
    conn = get_connection()
    c = conn.cursor()
    
    # Check if exists
    c.execute("SELECT date FROM work_days WHERE date = ?", (date_str,))
    data = c.fetchone()
    
    if data:
        c.execute("DELETE FROM work_days WHERE date = ?", (date_str,))
    else:
        c.execute("INSERT INTO work_days (date, hours) VALUES (?, ?)", (date_str, 8.0))
        
    conn.commit()
    conn.close()

def get_all_days():
    """Returns a list of all work days."""
    conn = get_connection()
    df = pd.read_sql_query("SELECT * FROM work_days", conn)
    conn.close()
    return df
