import tkinter as tk
from tkinter import ttk, messagebox
import sqlite3
from datetime import datetime
from openpyxl import Workbook

class AdvancedHRMS:
    def __init__(self, root):
        self.root = root
        self.root.title("نظام إدارة الموارد البشرية المتقدم")
        self.root.geometry("1400x900")

        self.create_database()
        self.create_widgets()
        self.load_initial_data()

        self.current_emp_id = None

    def create_database(self):
        self.conn = sqlite3.connect('advanced_hrms.db')
        self.cursor = self.conn.cursor()

        tables = [
            '''CREATE TABLE IF NOT EXISTS employees (
                id TEXT PRIMARY KEY,
                name TEXT,
                dob TEXT,
                nationality TEXT,
                hire_date TEXT,
                department TEXT,
                salary REAL)''',

            '''CREATE TABLE IF NOT EXISTS attendance (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                emp_id TEXT,
                date TEXT,
                check_in TEXT,
                check_out TEXT)''',

            '''CREATE TABLE IF NOT EXISTS salaries (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                emp_id TEXT,
                month TEXT,
                basic REAL,
                deductions REAL,
                allowances REAL,
                net REAL)''',

            '''CREATE TABLE IF NOT EXISTS leaves (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                emp_id TEXT,
                start_date TEXT,
                end_date TEXT,
                type TEXT,
                status TEXT DEFAULT 'معلق')''',

            '''CREATE TABLE IF NOT EXISTS performance (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                emp_id TEXT,
                date TEXT,
                productivity REAL,
                teamwork REAL,
                comments TEXT)'''
        ]

        for table in tables:
            self.cursor.execute(table)
        self.conn.commit()

    def create_widgets(self):
        toolbar = ttk.Frame(self.root)
        toolbar.pack(side='top', fill='x')

        self.emp_selector = ttk.Combobox(toolbar, postcommand=self.update_emp_list)
        self.emp_selector.pack(side='left', padx=5, pady=5)
        self.emp_selector.bind('<<ComboboxSelected>>', self.select_employee)

        ttk.Button(toolbar, text="تصدير Excel", command=self.export_to_excel).pack(side='right', padx=5)

        self.tab_control = ttk.Notebook(self.root)

        self.tab_employees = self.create_employee_tab()
        self.tab_control.add(self.tab_employees, text='الموظفين')

        self.tab_attendance = self.create_attendance_tab()
        self.tab_control.add(self.tab_attendance, text='الحضور')

        self.tab_salaries = self.create_salary_tab()
        self.tab_control.add(self.tab_salaries, text='الرواتب')

        self.tab_leaves = self.create_leave_tab()
        self.tab_control.add(self.tab_leaves, text='الإجازات')

        self.tab_performance = self.create_performance_tab()
        self.tab_control.add(self.tab_performance, text='التقييم')

        self.tab_control.pack(expand=1, fill='both')

    def create_employee_tab(self):
        tab = ttk.Frame(self.tab_control)

        # ... (Rest of the employee tab code - same as before)

        return tab

    def create_attendance_tab(self):
        tab = ttk.Frame(self.tab_control)

        # ... (Rest of the attendance tab code - same as before)

        return tab

    def create_salary_tab(self):
        tab = ttk.Frame(self.tab_control)

        # ... (Rest of the salary tab code - same as before)

        return tab

    def create_leave_tab(self):
        tab = ttk.Frame(self.tab_control)

        # ... (Rest of the leave tab code - same as before)

        return tab

    def create_performance_tab(self):
        tab = ttk.Frame(self.tab_control)

        # ... (Rest of the performance tab code - same as before)

        return tab


    def export_to_excel(self):
        try:
            wb = Workbook()

            # تصدير الموظفين
            ws_emp = wb.active
            ws_emp.title = "الموظفين"
            ws_emp.append(['الرقم الوظيفي', 'الاسم', 'تاريخ الميلاد', 'الجنسية', 'تاريخ التعيين', 'القسم', 'الراتب'])  # Include all columns
            employees = self.cursor.execute("SELECT id, name, dob, nationality, hire_date, department, salary FROM employees").fetchall() # Select all columns
            for emp in employees:
                ws_emp.append(emp)

            # تصدير الرواتب
            ws_sal = wb.create_sheet("الرواتب")
            ws_sal.append(['الشهر', 'الأساسي', 'الخصومات', 'المكافآت', 'الصافي'])
            salaries = self.cursor.execute("SELECT month, basic, deductions, allowances, net FROM salaries").fetchall()
            for sal in salaries:
                ws_sal.append(sal)

            # ... (Export other tables - attendance, leaves, performance)

            wb.save("hr_export.xlsx")
            messagebox.showinfo("نجاح", "تم التصدير إلى hr_export.xlsx")
        except Exception as e:
            messagebox.showerror("خطأ", f"خطأ في التصدير: {str(e)}")

    def update_emp_list(self):
        try:
            self.emp_selector['values'] = [row[0] for row in self.cursor.execute("SELECT id FROM employees").fetchall()]
        except Exception as e:
            messagebox.showerror("خطأ", str(e))

    def select_employee(self, event):
        self.current_emp_id = self.emp_selector.get()
        # ... (Load and display details for the selected employee in the appropriate tabs) ...

    def load_initial_data(self):
        self.update_emp_list()  # Load employee list at start
        self.refresh_employee_table() # Refresh the employee table

    def refresh_employee_table(self):
        try:
            self.employee_tree.delete(*self.employee_tree.get_children())  # Clear existing data
            employees = self.cursor.execute("SELECT id, name, dob, nationality, hire_date, department, salary FROM employees").fetchall()
            for employee in employees:
                self.employee_tree.insert("", tk.END, values=employee)
        except Exception as e:
            messagebox.showerror("Error", str(e))

    # ... (Add other data loading/refresh functions for attendance, salaries, etc.)

    def add_employee(self):
        try:
            data = [self.entries[label].get() for label in ['الرقم الوظيفي', 'الاسم', 'تاريخ الميلاد', 'الجنسية', 'تاريخ التعيين', 'القسم', 'الراتب']]
            self.cursor.execute("INSERT INTO employees VALUES (?, ?, ?, ?, ?, ?, ?)", data)
            self.conn.commit()
            self.refresh_employee_table()  # Refresh the table after adding
            messagebox.showinfo("نجاح", "تمت إضافة الموظف.")
            # Clear the entry fields after adding (optional)
            for entry in self.entries.values():
                entry.delete(0, tk.END)
        except Exception as e:
            self.conn.rollback()
            messagebox.showerror("خطأ", str(e))

    # ... (Implement update_employee, delete_employee, check_in, check_out, calculate_salary, submit_leave, save_performance)

if __name__ == "__main__":
    root = tk.Tk()
    app = AdvancedHRMS(root)
    root.mainloop()

