import streamlit as st
import sqlite3
import datetime
# Connect to the database
conn = sqlite3.connect(r'C:\Users\neiro\Documents\+\GitHub\sgbd-usine\donnees\company.db')
cursor = conn.cursor()
# Set the title of the Streamlit app
st.title("Machine de Badgeage")
# Initialize session state for buttons
if 'badge_in_clicked' not in st.session_state:
    st.session_state.badge_in_clicked = False
if 'badge_out_clicked' not in st.session_state:
    st.session_state.badge_out_clicked = False

# Disable buttons if already clicked
badge_in_disabled = st.session_state.badge_in_clicked
badge_out_disabled = st.session_state.badge_out_clicked
# Display a welcome message
st.write("Passez une bonne journée!")
# Get the next NUM_LOG_JOUR_JOUR
cursor.execute("SELECT MAX(NUM_LOG_JOUR_JOUR) FROM LOG_JOURNEE_JOUR")
max_num_log_jour_jour = cursor.fetchone()[0]
NUM_LOG_JOUR_JOUR = max_num_log_jour_jour + 1 if max_num_log_jour_jour is not None else 1

# Get today's date
DATE = datetime.date.today().strftime('%Y-%m-%d')

# Employee number input²
NUMERO_EMPLOYE = st.number_input("Numéro Employé", min_value=1, step=1)

# Badge in button
if st.button("Badge In", disabled=badge_in_disabled, key="badge_in"):
    st.session_state.badge_in_clicked = True
    st.experimental_rerun()  # Force rerun to update button state
    HEURE_ARRIVEE = datetime.datetime.now().strftime('%H:%M:%S')
    cursor.execute('''
    INSERT INTO LOG_JOURNEE_JOUR (NUM_LOG_JOUR_JOUR, DATE, NUMERO_EMPLOYE, HEURE_ARRIVEE)
    VALUES (?, ?, ?, ?)
    ''', (NUM_LOG_JOUR_JOUR, DATE, NUMERO_EMPLOYE, HEURE_ARRIVEE))
    conn.commit()
    st.success(f"Arrivée enregistrée à {HEURE_ARRIVEE}")

# Badge out button
if st.button("Badge Out", disabled=badge_out_disabled, key="badge_out"):
    st.session_state.badge_out_clicked = True
    st.experimental_rerun()  # Force rerun to update button state
    HEURE_FIN = datetime.datetime.now().strftime('%H:%M:%S')
    cursor.execute('''
    UPDATE LOG_JOURNEE_JOUR
    SET HEURE_FIN = ?
    WHERE NUMERO_EMPLOYE = ? AND DATE = ?
    ''', (HEURE_FIN, NUMERO_EMPLOYE, DATE))
    conn.commit()
    st.success(f"Départ enregistré à {HEURE_FIN}")
    # Calculate working hours and update the database
    cursor.execute('''
    SELECT HEURE_ARRIVEE, HEURE_FIN FROM LOG_JOURNEE_JOUR
    WHERE NUMERO_EMPLOYE = ? AND DATE = ?
    ''', (NUMERO_EMPLOYE, DATE))
    result = cursor.fetchone()

    if result:
        HEURE_ARRIVEE, HEURE_FIN = result
        if HEURE_ARRIVEE and HEURE_FIN:
            # Calculate total hours worked
            heure_arrivee = datetime.datetime.strptime(HEURE_ARRIVEE, '%H:%M:%S')
            heure_fin = datetime.datetime.strptime(HEURE_FIN, '%H:%M:%S')
            nb_heures = (heure_fin - heure_arrivee).seconds / 3600.0
            
            # Calculate overtime hours
            nb_heures_sup = max(nb_heures - 9, 0)
            
            # Determine if there was a delay
            retard = heure_arrivee.time() > datetime.time(8, 0, 0)
            
            # Update the database with calculated values
            cursor.execute('''
            UPDATE LOG_JOURNEE_JOUR
            SET NB_HEURES = ?, NB_HEURES_SUP = ?, RETARD = ?
            WHERE NUMERO_EMPLOYE = ? AND DATE = ?
            ''', (nb_heures, nb_heures_sup, retard, NUMERO_EMPLOYE, DATE))
            conn.commit()

    # Display a summary of the day's work
    st.write("Récapitulatif de la journée:")
    st.write(f"Numéro Employé: {NUMERO_EMPLOYE}")
    # Fetch employee's name and surname
    cursor.execute('''
    SELECT NOM, PRENOM FROM EMPLOYE
    WHERE NUMERO_EMPLOYE = ?
    ''', (NUMERO_EMPLOYE,))
    employee = cursor.fetchone()
    if employee:
        NOM, PRENOM = employee
        st.write(f"Nom: {NOM}")
        st.write(f"Prénom: {PRENOM}")
    st.write(f"Nombre d'heures travaillées: {nb_heures:.2f}")
    st.write(f"Nombre d'heures supplémentaires: {nb_heures_sup:.2f}")
    st.write(f"Retard: {'Oui' if retard else 'Non'}")