#Jason Wacker
#CIS261
#Employee Management System
#Phase 4

from datetime import datetime

#Employee Class
class Employee:
    def __init__(self, first_name, last_name, employee_id, hours, rate, record_date_str=None):
        self.first_name = first_name
        self.last_name = last_name
        self.employee_id = employee_id
        self.hours = hours
        self.rate = rate
        if record_date_str is None:
            self.record_date = datetime.now()
        else:
            self.record_date = datetime.strptime(record_date_str, "%Y-%m-%d")
        self.gross_pay = 0.0
        self.deductions = 0.0
        self.net_pay = 0.0
        self.calculate_gross_pay()
        self.calculate_deductions()
        self.calculate_net_pay()

    def calculate_gross_pay(self):
        if self.hours <= 40:
            self.gross_pay = self.hours * self.rate
        else:
            overtime_hours = self.hours - 40
            self.gross_pay = (40 * self.rate) + (overtime_hours * self.rate * 1.5)
    
    #25% total: Federal 15%, State 5%, Benefits 5%
    def calculate_deductions(self):
        self.deductions = self.gross_pay * 0.25

    def calculate_net_pay(self):
        self.net_pay = self.gross_pay - self.deductions

    def worked_overtime(self):
        return self.hours > 40
    
    def is_high_earner(self, minimum=1000):
        return self.gross_pay >= minimum

    def to_file_string(self):
        date_string = self.record_date.strftime("%Y-%m-%d")
        return (f"{self.first_name}|{self.last_name}|{self.employee_id}|{self.hours}|{self.rate}|{self.gross_pay}|{self.deductions}|{self.net_pay}|{date_string}")

    def __str__(self):
        return (f"Name:                                 {self.first_name} {self.last_name}\n"
                f"Employee ID:                          {self.employee_id}\n"
                f"Hours Worked:                         {self.hours:.2f}\n"
                f"Hourly Rate:                          ${self.rate:.2f}\n"
                f"Gross Pay:                            ${self.gross_pay:.2f}\n"
                f"Deductions:                           ${self.deductions:.2f}\n"
                f"Net Pay:                              ${self.net_pay:.2f}\n"
                f"Date:                                 {self.record_date.strftime('%Y-%m-%d')}")

#HRUser Class
class HRUser:
    def __init__(self, username, password, role, full_name):
        self.username = username
        self.password = password
        self.role = role
        self.full_name = full_name

#Part 1 Defining input functions and values
def get_employee_name():
    first_name = input("Enter employees first name (or ESC to quit): ")
    if first_name.upper() == "ESC":
        return "ESC", ""
    last_name = input("Enter employees last name: ")
    return first_name, last_name

def get_employee_id():
    employee_id = input("Enter employee ID: ")
    return employee_id

def get_hours_worked():
    hours = float(input("Enter hours worked: "))
    return hours

def get_hourly_rate():
    rate = float(input("Enter hourly rate: "))
    return rate

#Security Functions
def create_default_users():
    users = []
    users.append(HRUser("hrmanager", "hr2024", "HR Manager", "Admin User"))
    users.append(HRUser("hrstaff", "staff123", "HR Staff", "Staff User"))
    return users

def display_login_screen():
    print("\n" + "=" * 50)
    print("     Employee Management System - Login")
    print("=" * 50)

def authenticate_user(users, username, password):
    for user in users:
        if user.username == username and user.password == password:
            return user
    return None

def display_access_granted(username, role):
    print("\nAccess Granted.")
    print(f"Welcome, {username}! You are logged in as: {role}")
    if role == "HR Manager":
        print("Permissions: Process records, view reports, manage user accounts")
    else:
        print("Permissions: View reports only")
    
def display_access_denied():
    print("\nAccess denied. Invalid username or password.")
    print("The program will now exit.")

#User management functions
def add_new_user(users):
    print("\n--- Add New User ---")
    username = input("Enter new username: ")
    password = input("Enter new password: ")
    role = input("Enter role (HR Manager or HR Staff): ")
    while role != "HR Manager" and role != "HR Staff":
        print("Role must be exactly 'HR Manager' or 'HR Staff'.")
        role = input("Enter role (HR Manager or HR Staff):")
    full_name = input("Enter full name: ")
    new_user = HRUser(username, password, role, full_name)
    users.append(new_user)
    print(f"User '{username}' added with role {role}.")

def display_all_users(users):
    print("\n--- All Users ---")
    for number, user in enumerate(users, 1):
        print(f"{number}. Username: {user.username} | Role: {user.role} | Name: {user.full_name}")

def save_users_to_file(users, filename):
    try:
        with open(filename, 'w') as file:
            for user in users:
                file.write(f"{user.username}|{user.password}|{user.role}|{user.full_name}\n")
        print(f"{len(users)} user(s) saved to {filename}.")
    except Exception as error:
        print(f"Error saving users: {error}")

def load_users_from_file(filename):
    users = []
    try:
        with open(filename, 'r') as file:
            for line in file:
                line = line.strip()
                if line == "":
                    continue
                parts = line.split('|')
                users.append(HRUser(parts[0], parts[1], parts[2], parts[3]))
    except FileNotFoundError:
        print(f"No user file found ({filename}). Creating default users.")
        users = create_default_users()
    except Exception as error:
        print(f"Error loading users: {error}")
    return users

def display_user_management_menu():
    print("\n--- User Management ---")
    print("1. Add New User")
    print("2. View All Users")
    print("3. Return to Main Menu")

def manage_user_accounts(users, users_filename):
    while True:
        display_user_management_menu()
        choice = input("Enter your choice: ")
        if choice == "1":
            add_new_user(users)
            save_users_to_file(users, users_filename)
        elif choice == "2":
            display_all_users(users)
        elif choice == "3":
            break
        else:
            print("Invalid choice. Please try again.")

#Menu functions
def display_menu(role):
    print("\n" + "=" *50)
    print("MAIN MENU")
    if role == "HR Manager":
        print("1. Process Employee Records")
        print("2. View Reports")
        print("3. Manage User Accounts")
        print("4. Exit")
    else:
        print("1. View Reports")
        print("2. Exit")

def get_menu_choice():
    choice = input("Enter your choice: ")
    return choice

#Save Function
def save_records_to_file(employee_records, filename):
    try:
        with open(filename, 'w') as file:
            for employee in employee_records:
                file.write(employee.to_file_string() + "\n")
        print(f"\n{len(employee_records)} record(s) saved to {filename}.")
    except Exception as error:
        print(f"Error saving records: {error}")

#Load Function
def load_records_from_file(filename):
    employee_records = []
    try:
        with open(filename, 'r') as file:
            for line in file:
                line = line.strip()
                if line == "":
                    continue
                parts = line.split('|')
                employee = Employee(parts[0], parts[1], parts[2], float(parts[3]), float(parts[4]), parts[8])
                employee_records.append(employee)
    except FileNotFoundError:
        print(f"No saved file found ({filename}). Starting with no records.")
    except Exception as error:
        print(f"Error loading records: {error}")
    return employee_records

#Menu handler functions
def process_employee_records(filename):
    employee_records = load_records_from_file(filename)
    print(f"Loaded {len(employee_records)} existing employee record(s).")
    print("Hours over 40 are paid at 1.5x. Deductions are 25% of gross pay.")
    print("Type ESC for the first name when you are done.")

    while True:
        first_name, last_name = get_employee_name()
        if first_name.upper() == "ESC":
            break
        employee_id = get_employee_id()
        hours = get_hours_worked()
        rate = get_hourly_rate()

        employee = Employee(first_name, last_name, employee_id, hours, rate)
        print("\n" + "-" * 50)
        print(employee)
        print("-" * 50)
        employee_records.append(employee)

    save_records_to_file(employee_records, filename)

def view_reports(filename):
    employee_records = load_records_from_file(filename)
    generate_report(employee_records)

def generate_report(employee_records):
    if len(employee_records) == 0:
        print("\nNo employee records to report.")
        return
    
    print("\n" + "=" *50)
    print("              Employee Report")
    print("=" * 50)
    for number, employee in enumerate(employee_records, 1):
        print(f"\nEmployee Record #{number}")
        print(employee)

    gross_pays = [employee.gross_pay for employee in employee_records]
    total_gross = sum(gross_pays)
    average_gross = sum(gross_pays) / len(gross_pays)
    highest_gross = max(gross_pays)
    lowest_gross = min(gross_pays)
    total_deductions = sum([employee.deductions for employee in employee_records])
    total_net = sum([employee.net_pay for employee in employee_records])

    overtime_count = 0
    high_earner_count = 0
    for employee in employee_records:
        if employee.worked_overtime():
            overtime_count = overtime_count + 1
        if employee.is_high_earner():
            high_earner_count = high_earner_count + 1
    
    print("\n" + "=" *50)
    print("================ Payroll Summary ================")
    print(f"Total Employees:                {len(employee_records)}")
    print(f"Total Gross Pay:                ${total_gross:.2f}")
    print(f"Total Deductions:               ${total_deductions:.2f}")
    print(f"Total Net Pay:                  ${total_net:.2f}")
    print(f"Average Gross Pay:              ${average_gross:.2f}")
    print(f"Highest Gross Pay:              ${highest_gross:.2f}")
    print(f"Lowest Gross Pay:               ${lowest_gross:.2f}")
    print(f"Overtime Employees:             {overtime_count}")
    print(f"High Earners (>= $1000):        {high_earner_count}")
    print("=" * 50)

#Main Function
def main():
    employees_filename = "employee_records.txt"
    users_filename = "hr_users.txt"
    
    users = load_users_from_file(users_filename)
    
    display_login_screen()
    username = input("Username: ")
    password = input("Password: ")
    
    current_user = authenticate_user(users, username, password)
    if current_user is None:
        display_access_denied()
        return
    
    display_access_granted(current_user.username, current_user.role)
    
    while True:
        display_menu(current_user.role)
        choice = get_menu_choice()
        
        if current_user.role == "HR Manager":
            if choice == "1":
                process_employee_records(employees_filename)
            elif choice == "2":
                view_reports(employees_filename)
            elif choice == "3":
                manage_user_accounts(users, users_filename)
            elif choice == "4":
                break
            else:
                print("Invalid choice. Please try again.")
        else:
            if choice == "1":
                view_reports(employees_filename)
            elif choice == "2":
                break
            else:
                print("Invalid choice. Please try again.")
    
    save_users_to_file(users, users_filename)
    print("Goodbye!")
    
main()