import tkinter as tk
from tkinter import ttk, messagebox
import sqlite3
from datetime import datetime
import re
from tkcalendar import DateEntry  # Pour les champs de date
import pandas as pd  # Pour l'export des données


class Database:
    def __init__(self):
        self.conn = sqlite3.connect('school.db')
        self.create_tables()

    def create_tables(self):
        c = self.conn.cursor()

        # Table Étudiants
        c.execute('''CREATE TABLE IF NOT EXISTS students (
            id INTEGER PRIMARY KEY,
            matricule TEXT UNIQUE,
            nom TEXT NOT NULL,
            prenom TEXT NOT NULL,
            date_naissance DATE,
            adresse TEXT,
            telephone TEXT,
            email TEXT,
            classe_id INTEGER,
            FOREIGN KEY (classe_id) REFERENCES classes (id))''')

        # Table Professeurs
        c.execute('''CREATE TABLE IF NOT EXISTS teachers (
            id INTEGER PRIMARY KEY,
            matricule TEXT UNIQUE,
            nom TEXT NOT NULL,
            prenom TEXT NOT NULL,
            telephone TEXT,
            email TEXT,
            specialite TEXT)''')

        # Table Classes
        c.execute('''CREATE TABLE IF NOT EXISTS classes (
            id INTEGER PRIMARY KEY,
            nom TEXT NOT NULL,
            niveau TEXT,
            annee_scolaire TEXT)''')

        # Table Matières
        c.execute('''CREATE TABLE IF NOT EXISTS matieres (
            id INTEGER PRIMARY KEY,
            nom TEXT NOT NULL,
            coefficient INTEGER)''')

        # Table Notes
        c.execute('''CREATE TABLE IF NOT EXISTS notes (
            id INTEGER PRIMARY KEY,
            student_id INTEGER,
            matiere_id INTEGER,
            note REAL,
            date_evaluation DATE,
            FOREIGN KEY (student_id) REFERENCES students (id),
            FOREIGN KEY (matiere_id) REFERENCES matieres (id))''')

        self.conn.commit()


class SchoolManagementSystem:
    def __init__(self, root):
        self.root = root
        self.root.title("Système de Gestion Scolaire")
        self.root.state('zoomed')  # Plein écran

        self.db = Database()
        self.setup_styles()
        self.create_main_interface()

    def setup_styles(self):
        # Configuration des styles
        style = ttk.Style()
        style.configure('Heading.TLabel', font=('Helvetica', 16, 'bold'))
        style.configure('Menu.TButton', padding=10, width=20)

    def create_main_interface(self):
        # Frame principal avec menu latéral
        self.main_frame = ttk.Frame(self.root)
        self.main_frame.pack(fill=tk.BOTH, expand=True)

        # Menu latéral
        self.sidebar = ttk.Frame(self.main_frame, relief='raised', padding="10")
        self.sidebar.pack(side=tk.LEFT, fill=tk.Y)

        # Zone de contenu
        self.content_frame = ttk.Frame(self.main_frame, padding="10")
        self.content_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)

        # Boutons du menu
        ttk.Button(self.sidebar, text="Tableau de bord",
                   style='Menu.TButton',
                   command=self.show_dashboard).pack(pady=5)
        ttk.Button(self.sidebar, text="Gestion des Étudiants",
                   style='Menu.TButton',
                   command=self.show_student_management).pack(pady=5)
        ttk.Button(self.sidebar, text="Gestion des Professeurs",
                   style='Menu.TButton',
                   command=self.show_teacher_management).pack(pady=5)
        ttk.Button(self.sidebar, text="Gestion des Classes",
                   style='Menu.TButton',
                   command=self.show_class_management).pack(pady=5)
        ttk.Button(self.sidebar, text="Gestion des Notes",
                   style='Menu.TButton',
                   command=self.show_grade_management).pack(pady=5)
        ttk.Button(self.sidebar, text="Rapports",
                   style='Menu.TButton',
                   command=self.show_reports).pack(pady=5)

        # Afficher le tableau de bord par défaut
        self.show_dashboard()

    def clear_content_frame(self):
        for widget in self.content_frame.winfo_children():
            widget.destroy()

    def show_dashboard(self):
        self.clear_content_frame()
        ttk.Label(self.content_frame, text="Tableau de Bord",
                  style='Heading.TLabel').pack(pady=20)

        # Statistiques
        stats_frame = ttk.Frame(self.content_frame)
        stats_frame.pack(fill=tk.X, pady=20)

        # Ajouter des widgets pour afficher les statistiques
        self.create_stat_widget(stats_frame, "Total Étudiants", self.get_total_students())
        self.create_stat_widget(stats_frame, "Total Professeurs", self.get_total_teachers())
        self.create_stat_widget(stats_frame, "Total Classes", self.get_total_classes())

    def create_stat_widget(self, parent, title, value):
        frame = ttk.Frame(parent)
        frame.pack(side=tk.LEFT, padx=20)
        ttk.Label(frame, text=title).pack()
        ttk.Label(frame, text=str(value), font=('Helvetica', 24)).pack()

    def get_total_students(self):
        c = self.db.conn.cursor()
        return c.execute("SELECT COUNT(*) FROM students").fetchone()[0]

    def get_total_teachers(self):
        c = self.db.conn.cursor()
        return c.execute("SELECT COUNT(*) FROM teachers").fetchone()[0]

    def get_total_classes(self):
        c = self.db.conn.cursor()
        return c.execute("SELECT COUNT(*) FROM classes").fetchone()[0]


class StudentManagement:
    def __init__(self, parent_frame, db):
        self.parent_frame = parent_frame
        self.db = db
        self.setup_student_interface()

    def setup_student_interface(self):
        # Frame pour la recherche
        search_frame = ttk.Frame(self.parent_frame)
        search_frame.pack(fill=tk.X, pady=10)

        ttk.Label(search_frame, text="Rechercher:").pack(side=tk.LEFT)
        self.search_entry = ttk.Entry(search_frame)
        self.search_entry.pack(side=tk.LEFT, padx=5)
        ttk.Button(search_frame, text="Rechercher",
                   command=self.search_students).pack(side=tk.LEFT)

        # Tableau des étudiants
        self.tree = ttk.Treeview(self.parent_frame, columns=(
            "matricule", "nom", "prenom", "classe", "telephone"
        ), show="headings")

        # Configuration des colonnes
        self.tree.heading("matricule", text="Matricule")
        self.tree.heading("nom", text="Nom")
        self.tree.heading("prenom", text="Prénom")
        self.tree.heading("classe", text="Classe")
        self.tree.heading("telephone", text="Téléphone")

        self.tree.pack(fill=tk.BOTH, expand=True)

        # Boutons d'action
        action_frame = ttk.Frame(self.parent_frame)
        action_frame.pack(fill=tk.X, pady=10)

        ttk.Button(action_frame, text="Ajouter",
                   command=self.add_student).pack(side=tk.LEFT, padx=5)
        ttk.Button(action_frame, text="Modifier",
                   command=self.edit_student).pack(side=tk.LEFT, padx=5)
        ttk.Button(action_frame, text="Supprimer",
                   command=self.delete_student).pack(side=tk.LEFT, padx=5)

quel est le probleme? l'app ne se lance pas, pase fenetre affichée