<?php
/**
To automatically use the server's default timezone:
*/
 //date_default_timezone_set(date_default_timezone_get());//
 date_default_timezone_set('Asia/Karachi');
 
require_once 'session_config_emp.php';

// Database connection
include_once 'connect.php';

// Email configuration for official domain
$email_from = 'noreply@dsisajk.net';
$email_from_name = 'AJ&K Education Department District Kotli- DSIS System';

// Handle redirect from successful submission - IMPORTANT: This should be at the TOP
if (isset($_GET['new_emp']) && isset($_GET['cnic'])) {
    $new_emp_id = (int)$_GET['new_emp'];
    $new_cnic = $_GET['cnic'];
    
    // First, check if employee exists in employees table (newly created profile)
    $verify_stmt = $conn->prepare("SELECT * FROM employees WHERE employee_id = ? AND cnic = ?");
    $verify_stmt->bind_param("is", $new_emp_id, $new_cnic);
    $verify_stmt->execute();
    $verify_result = $verify_stmt->get_result();
    
    if ($verify_result->num_rows > 0) {
        $new_employee = $verify_result->fetch_assoc();
        
        // Store in session
        $_SESSION['employee_id'] = $new_employee['employee_id'];
        $_SESSION['cnic'] = $new_employee['cnic'];
        $_SESSION['full_name'] = $new_employee['full_name'];
        
        // Also check if they exist in registrations_emp table
        $reg_stmt = $conn->prepare("SELECT * FROM registrations_emp WHERE cnic = ?");
        $reg_stmt->bind_param("s", $new_employee['cnic']);
        $reg_stmt->execute();
        $reg_result = $reg_stmt->get_result();
        
        if ($reg_result->num_rows > 0) {
            // User exists in both tables - normal login
            $reg_data = $reg_result->fetch_assoc();
            $_SESSION['reg_emp_id'] = $reg_data['id']; // Store registration ID
            $_SESSION['employee_data'] = [
                'full_name' => $reg_data['full_name'],
                'emp_numb' => $reg_data['emp_numb'],
                'cnic' => $reg_data['cnic'],
                'dob' => $reg_data['dob'],
                'photo_path' => $new_employee['photo_path'] ?? null // Add photo_path from employees table
            ];
        } else {
            // User only exists in employees table (newly created profile)
            // Create minimal session data from employees table
            $_SESSION['employee_data'] = [
                'full_name' => $new_employee['full_name'],
                'emp_numb' => $new_employee['personal_no'], // Use personal_no as emp_numb
                'cnic' => $new_employee['cnic'],
                'dob' => $new_employee['date_of_birth'],
                'photo_path' => $new_employee['photo_path'] ?? null // Add photo_path
            ];
        }
        $reg_stmt->close();
        
        // Mark profile as complete
        $_SESSION['profile_incomplete'] = false;
        $_SESSION['profile_created'] = true; // Add this flag
        
        // Redirect to clean URL
        header("Location: employee_dashboard.php");
        exit();
    }
    $verify_stmt->close();
}

// Check if we have employee data in session from new profile creation
if (isset($_SESSION['cnic']) && isset($_SESSION['full_name'])) {
    // Use session data to get employee details
    $employee_exists = true;
    $employee = [
        'full_name' => $_SESSION['full_name'],
        'cnic' => $_SESSION['cnic'],
        'role_id' => $_SESSION['employee_data']['role_id'] ?? 6, // Default to teacher role
        'role_name' => $_SESSION['employee_data']['role_name'] ?? 'Employee',
        'photo_path' => $_SESSION['employee_data']['photo_path'] ?? null // Add photo_path
    ];
    
    // Check if profile exists in employees table
    $profile_check_stmt = $conn->prepare("SELECT * FROM employees WHERE cnic = ?");
    $profile_check_stmt->bind_param("s", $_SESSION['cnic']);
    $profile_check_stmt->execute();
    $profile_result = $profile_check_stmt->get_result();
    $profile_exists = $profile_result->num_rows > 0;
    
    if ($profile_exists) {
        $profile_data = $profile_result->fetch_assoc();
        // Update session with employee_id from employees table
        $_SESSION['employee_id'] = $profile_data['employee_id'];
        // Update photo_path in employee array
        $employee['photo_path'] = $profile_data['photo_path'] ?? $employee['photo_path'];
    }
    $profile_check_stmt->close();
    
} else {
    // Original logic for existing registrations
    if (isset($_SESSION['employee_id']) && isset($_SESSION['cnic'])) {
        // First check if employee_roles table exists and has data
        $check_tables = $conn->query("SHOW TABLES LIKE 'employee_roles'");
        if ($check_tables->num_rows === 0) {
            $stmt = $conn->prepare("SELECT re.*, e.photo_path FROM registrations_emp re 
                                   LEFT JOIN employees e ON re.cnic = e.cnic 
                                   WHERE re.id = ? AND re.cnic = ?");
            if (!$stmt) {
                die("Error preparing query: " . $conn->error);
            }
            $stmt->bind_param("is", $_SESSION['employee_id'], $_SESSION['cnic']);
            $stmt->execute();
            $result = $stmt->get_result();
            
            if ($result->num_rows === 0) {
                session_destroy();
                header("Location: login_emp.php?error=invalid_session");
                exit();
            }
            
            $employee = $result->fetch_assoc();
            $stmt->close();
            
            // Set a default role name
            $employee['role_name'] = 'Employee';
            $employee['role_id'] = 6; // Default to teacher role
        } else {
            $stmt = $conn->prepare("SELECT re.*, er.role_name, er.role_id, e.photo_path 
                                   FROM registrations_emp re
                                   LEFT JOIN employee_roles er ON re.role_id = er.role_id
                                   LEFT JOIN employees e ON re.cnic = e.cnic
                                   WHERE re.id = ? AND re.cnic = ?");
            if (!$stmt) {
                die("Error preparing query: " . $conn->error);
            }
            $stmt->bind_param("is", $_SESSION['employee_id'], $_SESSION['cnic']);
            $stmt->execute();
            $result = $stmt->get_result();

            if ($result->num_rows === 0) {
                session_destroy();
                header("Location: login_emp.php?error=invalid_session");
                exit();
            }

            $employee = $result->fetch_assoc();
            $stmt->close();
            
            if (empty($employee['role_name'])) {
                $employee['role_name'] = 'Employee';
            }
            if (empty($employee['role_id'])) {
                $employee['role_id'] = 6;
            }
        }
        
        $employee_exists = true;

        $_SESSION['employee_data'] = [
            'full_name' => $employee['full_name'],
            'emp_numb' => $employee['emp_numb'],
            'cnic' => $employee['cnic'],
            'dob' => $employee['dob'],
            'role_id' => $employee['role_id'],
            'role_name' => $employee['role_name'],
            'photo_path' => $employee['photo_path'] ?? null
        ];

        // Check if profile exists in employees table
        $profile_check_stmt = $conn->prepare("SELECT * FROM employees WHERE cnic = ?");
        $profile_check_stmt->bind_param("s", $_SESSION['cnic']);
        $profile_check_stmt->execute();
        $profile_result = $profile_check_stmt->get_result();
        $profile_exists = $profile_result->num_rows > 0;
        $profile_check_stmt->close();
    } else {
        $employee_exists = false;
        $profile_exists = false;
    }
}

// If profile doesn't exist, set session flag
if (!$profile_exists) {
    $_SESSION['profile_incomplete'] = true;
} else {
    $_SESSION['profile_incomplete'] = false;
}

// Fetch statistics for quick stats (ONLY for DEO and MIS/Administrator)
$stats = [];
$show_quick_stats = false;

// Define access levels based on role_id from employee_roles table
$is_secretary = (isset($employee['role_id']) && $employee['role_id'] == 1);
$is_deo = (isset($employee['role_id']) && $employee['role_id'] == 2);
$is_ddeo = (isset($employee['role_id']) && $employee['role_id'] == 3);
$is_aeo = (isset($employee['role_id']) && $employee['role_id'] == 4);
$is_principal = (isset($employee['role_id']) && ($employee['role_id'] == 5 || $employee['role_id'] == 10 || $employee['role_id'] == 11));
$is_teacher = (isset($employee['role_id']) && $employee['role_id'] == 6);
$is_mis_admin = (isset($employee['role_id']) && $employee['role_id'] == 7);
$is_clerk = (isset($employee['role_id']) && $employee['role_id'] == 8);
$is_staff = (isset($employee['role_id']) && $employee['role_id'] == 9);

// NEW: DEO now has approval access (along with MIS Admin)
$has_approval_access = ($is_deo || $is_mis_admin);

// Quick Stats only for DEO and MIS/Administrator
if ($is_deo || $is_mis_admin) {
    $show_quick_stats = true;
    
    // Total registered employees (from registrations_emp table)
    $stats_query = $conn->query("SELECT COUNT(*) as total_registered FROM registrations_emp WHERE status = 1");
    if ($stats_query) {
        $stats['total_registered'] = $stats_query->fetch_assoc()['total_registered'] ?? 0;
        $stats_query->close();
    }

    // Total profiles completed (from employees table)
    $stats_query = $conn->query("SELECT COUNT(*) as profiles_completed FROM employees");
    if ($stats_query) {
        $stats['profiles_completed'] = $stats_query->fetch_assoc()['profiles_completed'] ?? 0;
        $stats_query->close();
    }

    // Calculate pending profiles
    $stats['pending_profiles'] = max(0, $stats['total_registered'] - $stats['profiles_completed']);

    // Calculate completion percentage
    if ($stats['total_registered'] > 0) {
        $stats['completion_percentage'] = round(($stats['profiles_completed'] / $stats['total_registered']) * 100, 1);
    } else {
        $stats['completion_percentage'] = 0;
    }

    // Get all registered employees for the stats modal
    $all_employees = [];
    $all_pending_profiles = [];
    $all_completed_profiles = [];

    // Registered employees (all approved registrations)
    $employees_query = $conn->query("SELECT re.id, re.full_name, re.emp_numb, re.cnic, re.employee_email, re.created_at, er.role_name, 
                                    (SELECT COUNT(*) FROM employees e WHERE e.cnic = re.cnic) as profile_completed
                                     FROM registrations_emp re 
                                     LEFT JOIN employee_roles er ON re.role_id = er.role_id 
                                     WHERE re.status = 1 
                                     ORDER BY re.created_at DESC");
    if ($employees_query) {
        while ($row = $employees_query->fetch_assoc()) {
            $row['profile_completed'] = $row['profile_completed'] > 0;
            $all_employees[] = $row;
            
            // Separate into pending and completed profiles
            if ($row['profile_completed']) {
                $all_completed_profiles[] = $row;
            } else {
                $all_pending_profiles[] = $row;
            }
        }
        $employees_query->close();
    }
}

// Access control
$has_hr_access = ($is_secretary || $is_deo || $is_mis_admin);
$has_finance_access = ($is_secretary || $is_deo || $is_mis_admin);
$has_school_access = ($is_secretary || $is_deo || $is_mis_admin || $is_aeo || $is_principal);
$has_student_access = ($is_secretary || $is_deo || $is_mis_admin || $is_aeo || $is_teacher);
$has_reports_access = ($is_secretary || $is_deo || $is_mis_admin || $is_aeo);
$has_announcements_access = ($is_secretary || $is_deo || $is_principal || $is_mis_admin);
$has_teacher_portal_access = $is_teacher;

// New access levels for added cards
$has_teacher_results_access = ($is_teacher || $is_principal || $is_aeo || $is_ddeo || $is_deo || $is_mis_admin);
$has_smc_access = ($is_principal || $is_aeo || $is_ddeo || $is_deo || $is_mis_admin);
$has_games_access = true; // Everyone can access games
$has_books_access = true; // Everyone can access books
$has_softwares_access = ($is_mis_admin || $is_deo || $is_teacher); // MIS, DEO, Teachers
$has_office_management_access = ($is_clerk || $is_staff || $is_mis_admin || $is_deo);
$has_documents_access = true; // Everyone can access documents
$has_applications_access = true; // Everyone can submit/view applications

// Function to generate initials from name
function getInitials($name) {
    $words = explode(' ', trim($name));
    $initials = '';
    foreach ($words as $word) {
        if (!empty($word)) {
            $initials .= strtoupper($word[0]);
        }
    }
    return substr($initials, 0, 2);
}

// Generate initials for fallback
$initials = getInitials($employee['full_name']);

// Check if default profile image exists, if not create one
$default_image_path = 'images/default_profile.png';
if (!file_exists($default_image_path)) {
    if (!file_exists('images')) {
        mkdir('images', 0755, true);
    }
    
    if (function_exists('imagecreatetruecolor')) {
        $img = imagecreatetruecolor(100, 100);
        $bg_color = imagecolorallocate($img, 26, 62, 114);
        $text_color = imagecolorallocate($img, 255, 255, 255);
        
        imagefilledrectangle($img, 0, 0, 100, 100, $bg_color);
        imagestring($img, 5, 35, 40, "ED", $text_color);
        imagepng($img, $default_image_path);
        imagedestroy($img);
    }
}

// Determine profile picture path
$profile_pic = 'images/default_profile.png';
if (!empty($employee['photo_path'])) {
    if (file_exists($employee['photo_path'])) {
        $profile_pic = $employee['photo_path'];
    } elseif (file_exists('uploads/' . $employee['photo_path'])) {
        $profile_pic = 'uploads/' . $employee['photo_path'];
    } elseif (file_exists('../uploads/' . $employee['photo_path'])) {
        $profile_pic = '../uploads/' . $employee['photo_path'];
    }
}

// Check for pending registration approvals - NOW FOR BOTH DEO AND MIS ADMIN
$pending_count = 0;
$pending_registrations = [];
if ($has_approval_access) { // Both DEO and MIS Admin
    $check_roles_table = $conn->query("SHOW TABLES LIKE 'employee_roles'");
    if ($check_roles_table->num_rows > 0) {
        $check_pending = $conn->prepare("SELECT re.id, re.full_name, re.emp_numb, re.cnic, re.dob, re.employee_email, er.role_name, re.created_at 
                                        FROM registrations_emp re 
                                        LEFT JOIN employee_roles er ON re.role_id = er.role_id 
                                        WHERE re.status = 0 
                                        AND re.forgot_password_request = 0
                                        ORDER BY re.created_at DESC");
    } else {
        $check_pending = $conn->prepare("SELECT re.id, re.full_name, re.emp_numb, re.cnic, re.dob, re.employee_email, re.created_at 
                                        FROM registrations_emp re 
                                        WHERE re.status = 0 
                                        AND re.forgot_password_request = 0
                                        ORDER BY re.created_at DESC");
    }
    
    if ($check_pending) {
        if ($check_pending->execute()) {
            $pending_result = $check_pending->get_result();
            $pending_count = $pending_result->num_rows;
            
            while ($row = $pending_result->fetch_assoc()) {
                if (!isset($row['role_name'])) {
                    $row['role_name'] = 'Employee';
                }
                $pending_registrations[] = $row;
            }
            $check_pending->close();
        }
    }
}

// Password reset requests - NOW FOR BOTH DEO AND MIS ADMIN
$password_reset_count = 0;
$password_reset_requests = [];

if ($has_approval_access) { // Both DEO and MIS Admin
    if (!$conn) die("No DB connection");
    
    try {
        $check_columns = $conn->query("SHOW COLUMNS FROM registrations_emp");
        $columns = [];
        while ($col = $check_columns->fetch_assoc()) {
            $columns[$col['Field']] = true;
        }
        
        $sql_fields = "re.id, re.full_name, re.emp_numb, re.cnic, re.employee_email, re.forgot_password_new, re.created_at";
        if (isset($columns['last_password_change'])) {
            $sql_fields .= ", re.last_password_change";
        }
        
        $check_roles = $conn->query("SHOW TABLES LIKE 'employee_roles'");
        if ($check_roles->num_rows > 0) {
            $sql_fields .= ", er.role_name";
        }
        
        $sql = "SELECT $sql_fields
                FROM registrations_emp re";
        
        if ($check_roles->num_rows > 0) {
            $sql .= " LEFT JOIN employee_roles er ON re.role_id = er.role_id";
        }
        
        $sql .= " WHERE re.forgot_password_request = 1 
                AND re.status = 0
                ORDER BY re.created_at DESC";
        
        $result = $conn->query($sql);
        if ($result) {
            $password_reset_count = $result->num_rows;
            while ($row = $result->fetch_assoc()) {
                if (!isset($row['role_name'])) {
                    $row['role_name'] = 'Employee';
                }
                $password_reset_requests[] = $row;
            }
        } else {
            error_log("Password reset query error: " . $conn->error);
        }
        
    } catch (Exception $e) {
        error_log("Error in password reset processing: " . $e->getMessage());
    }
}

// Function to send registration approval email
function sendRegistrationApprovalEmail($to_email, $full_name, $emp_numb, $cnic, $admin_name) {
    global $email_from;
    
    if (empty($to_email) || !filter_var($to_email, FILTER_VALIDATE_EMAIL)) {
        error_log("Invalid email address for registration approval: " . $to_email);
        return false;
    }
    
    $subject = 'Registration Approved – AJ&K Education Department District Kotli';
    
    $email_body = "
Dear $full_name,

We are pleased to inform you that your registration with AJ&K Education Department District Kotli has been approved.

Employee Details:
------------------
Full Name       : $full_name
Employee Number : $emp_numb
CNIC            : $cnic
Approved By     : $admin_name
Approval Date   : " . date('F j, Y') . "

Your account is now active and you can access the Employee Management System using your registered credentials.

Login URL: http://" . $_SERVER['HTTP_HOST'] . "/login_emp.php

Important Notes:
1. Keep your login credentials confidential
2. Complete your employee profile after first login
3. Contact system administrator if you face any issues

This is an automated message from the AJ&K Education Department District Kotli DSIS System.
";

    $headers = [];
    $headers[] = "From: AJ&K Education Department District Kotli <$email_from>";
    $headers[] = "Reply-To: $email_from";
    $headers[] = "Return-Path: $email_from";
    $headers[] = "MIME-Version: 1.0";
    $headers[] = "Content-Type: text/plain; charset=UTF-8";
    $headers[] = "X-Mailer: PHP/" . phpversion();

    if (!mail($to_email, $subject, $email_body, implode("\r\n", $headers))) {
        error_log('Registration approval email failed to send to ' . $to_email);
        return false;
    }
    
    return true;
}

// Function to send password reset approval email
function sendPasswordResetApprovalEmail($to_email, $full_name, $emp_numb, $cnic, $admin_name, $new_password) {
    global $email_from;
    
    if (empty($to_email) || !filter_var($to_email, FILTER_VALIDATE_EMAIL)) {
        error_log("Invalid email address for password reset: " . $to_email);
        return false;
    }
    
    $subject = 'Password Reset Approved – AJ&K Education Department District Kotli';
    
    $email_body = "
Dear $full_name,

Your password reset request has been approved by the system administrator.

IMPORTANT SECURITY NOTICE:
Your new login password is: $new_password
Please change this password immediately after login for security reasons.

Account Details:
------------------
Employee Name   : $full_name
Employee Number : $emp_numb
CNIC            : $cnic
Approved By     : $admin_name
Approval Date   : " . date('F j, Y') . "

You can now login to the Employee Management System using your new password.

Login URL: http://" . $_SERVER['HTTP_HOST'] . "/login_emp.php

Security Recommendations:
1. Change your password immediately after first login
2. Use a strong password with letters, numbers, and special characters
3. Never share your password with anyone
4. Log out after each session

This is an automated message from the AJ&K Education Department District Kotli DSIS System.
";

    $headers = [];
    $headers[] = "From: AJ&K Education Department District Kotli <$email_from>";
    $headers[] = "Reply-To: $email_from";
    $headers[] = "Return-Path: $email_from";
    $headers[] = "MIME-Version: 1.0";
    $headers[] = "Content-Type: text/plain; charset=UTF-8";
    $headers[] = "X-Mailer: PHP/" . phpversion();

    if (!mail($to_email, $subject, $email_body, implode("\r\n", $headers))) {
        error_log('Password reset approval email failed to send to ' . $to_email);
        return false;
    }
    
    return true;
}

// Handle approval/reject actions via AJAX - NOW FOR BOTH DEO AND MIS ADMIN
if (isset($_POST['action']) && $has_approval_access) {
    $response = ['success' => false, 'message' => '', 'email_sent' => false];
    
    if (isset($_POST['registration_id']) && isset($_POST['action_type'])) {
        $registration_id = intval($_POST['registration_id']);
        $action_type = $_POST['action_type'];
        
        if ($action_type === 'approve') {
            // Get admin's name from session
            $admin_name = 'System Administrator';
            
            if (!empty($_SESSION['full_name'])) {
                $admin_name = $_SESSION['full_name'];
            } elseif (!empty($_SESSION['employee_data']['full_name'])) {
                $admin_name = $_SESSION['employee_data']['full_name'];
            } elseif (!empty($employee['full_name'])) {
                $admin_name = $employee['full_name'];
            }
            
            $current_time = date('Y-m-d H:i:s');
            
            // First get employee details including email
            $get_emp_stmt = $conn->prepare("SELECT full_name, emp_numb, cnic, employee_email FROM registrations_emp WHERE id = ?");
            if ($get_emp_stmt) {
                $get_emp_stmt->bind_param("i", $registration_id);
                $get_emp_stmt->execute();
                $emp_result = $get_emp_stmt->get_result();
                $emp_data = $emp_result->fetch_assoc();
                $get_emp_stmt->close();
                
                $employee_name = $emp_data['full_name'] ?? '';
                $employee_number = $emp_data['emp_numb'] ?? '';
                $employee_cnic = $emp_data['cnic'] ?? '';
                $employee_email = $emp_data['employee_email'] ?? '';
                
                // Update status to 1 (approved) and reset forgot_password_request to 0
                $update_stmt = $conn->prepare("UPDATE registrations_emp SET status = 1, forgot_password_request = 0, reg_approved_by = ?, reg_approved_time = ? WHERE id = ?");
                if ($update_stmt) {
                    $update_stmt->bind_param("ssi", $admin_name, $current_time, $registration_id);
                    if ($update_stmt->execute()) {
                        // Send email notification if email exists
                        if (!empty($employee_email) && filter_var($employee_email, FILTER_VALIDATE_EMAIL)) {
                            $email_sent = sendRegistrationApprovalEmail($employee_email, $employee_name, $employee_number, $employee_cnic, $admin_name);
                            if ($email_sent) {
                                $response['email_sent'] = true;
                                $response['message'] = 'Registration approved successfully and email sent to ' . $employee_email;
                            } else {
                                $response['message'] = 'Registration approved but email notification failed to send';
                            }
                        } else {
                            $response['message'] = 'Registration approved successfully (No email sent - invalid or missing email address)';
                        }
                        $response['success'] = true;
                    } else {
                        $response['message'] = 'Error approving registration: ' . $update_stmt->error;
                    }
                    $update_stmt->close();
                } else {
                    $response['message'] = 'Error preparing update statement: ' . $conn->error;
                }
            } else {
                $response['message'] = 'Error fetching employee details: ' . $conn->error;
            }
            
        } elseif ($action_type === 'reject') {
            // Get employee email before deletion for notification
            $get_emp_stmt = $conn->prepare("SELECT full_name, employee_email FROM registrations_emp WHERE id = ?");
            $employee_name = '';
            $employee_email = '';
            if ($get_emp_stmt) {
                $get_emp_stmt->bind_param("i", $registration_id);
                $get_emp_stmt->execute();
                $emp_result = $get_emp_stmt->get_result();
                if ($emp_result->num_rows > 0) {
                    $emp_data = $emp_result->fetch_assoc();
                    $employee_name = $emp_data['full_name'] ?? '';
                    $employee_email = $emp_data['employee_email'] ?? '';
                }
                $get_emp_stmt->close();
            }
            
            // Delete the record
            $delete_stmt = $conn->prepare("DELETE FROM registrations_emp WHERE id = ?");
            if ($delete_stmt) {
                $delete_stmt->bind_param("i", $registration_id);
                if ($delete_stmt->execute()) {
                    $response['success'] = true;
                    $response['message'] = 'Registration rejected and deleted';
                } else {
                    $response['message'] = 'Error rejecting registration: ' . $delete_stmt->error;
                }
                $delete_stmt->close();
            } else {
                $response['message'] = 'Error preparing delete statement: ' . $conn->error;
            }
        }
    }
    
    // Return JSON response
    header('Content-Type: application/json');
    echo json_encode($response);
    exit();
}

// Handle password reset approval/reject actions via AJAX - NOW FOR BOTH DEO AND MIS ADMIN
if (isset($_POST['password_action']) && $has_approval_access) {
    $response = ['success' => false, 'message' => '', 'email_sent' => false];
    
    if (isset($_POST['request_id']) && isset($_POST['action_type'])) {
        $request_id = intval($_POST['request_id']);
        $action_type = $_POST['action_type'];
        
        if ($action_type === 'approve_reset') {
            // Get the new password and employee details from the request
            $get_password_stmt = $conn->prepare("SELECT forgot_password_new, full_name, emp_numb, cnic, employee_email FROM registrations_emp WHERE id = ? AND forgot_password_request = 1 AND status = 0");
            if ($get_password_stmt) {
                $get_password_stmt->bind_param("i", $request_id);
                if ($get_password_stmt->execute()) {
                    $password_result = $get_password_stmt->get_result();
                    if ($password_result->num_rows > 0) {
                        $password_data = $password_result->fetch_assoc();
                        $new_password = $password_data['forgot_password_new'];
                        $employee_name = $password_data['full_name'] ?? '';
                        $employee_number = $password_data['emp_numb'] ?? '';
                        $employee_cnic = $password_data['cnic'] ?? '';
                        $employee_email = $password_data['employee_email'] ?? '';
                        
                        // Check if new_password is not null or empty
                        if (!empty($new_password)) {
                            // Hash the new password
                            $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
                            
                            // Get admin's name
                            $admin_name = 'System Administrator';
                            if (!empty($_SESSION['full_name'])) {
                                $admin_name = $_SESSION['full_name'];
                            } elseif (!empty($_SESSION['employee_data']['full_name'])) {
                                $admin_name = $_SESSION['employee_data']['full_name'];
                            } elseif (!empty($employee['full_name'])) {
                                $admin_name = $employee['full_name'];
                            }
                            
                            $current_time = date('Y-m-d H:i:s');
                            
                            // Check what columns exist
                            $check_columns = $conn->query("SHOW COLUMNS FROM registrations_emp");
                            $columns = [];
                            while ($col = $check_columns->fetch_assoc()) {
                                $columns[$col['Field']] = true;
                            }
                            
                            // Build query with password reset approval fields
                            $sql = "UPDATE registrations_emp SET 
                                    password = ?, 
                                    status = 1,
                                    forgot_password_request = 0,
                                    forgot_password_new = NULL,
                                    reset_approved_by = ?,
                                    reset_approved_time = ?";
                            
                            // Add last_password_change if column exists
                            if (isset($columns['last_password_change'])) {
                                $sql .= ", last_password_change = NOW()";
                            }
                            
                            $sql .= " WHERE id = ?";
                            
                            $update_stmt = $conn->prepare($sql);
                            
                            if ($update_stmt) {
                                $update_stmt->bind_param("sssi", $hashed_password, $admin_name, $current_time, $request_id);
                                
                                if ($update_stmt->execute()) {
                                    // Send email notification if email exists
                                    if (!empty($employee_email) && filter_var($employee_email, FILTER_VALIDATE_EMAIL)) {
                                        $email_sent = sendPasswordResetApprovalEmail($employee_email, $employee_name, $employee_number, $employee_cnic, $admin_name, $new_password);
                                        if ($email_sent) {
                                            $response['email_sent'] = true;
                                            $response['message'] = 'Password updated successfully, user approved and email sent to ' . $employee_email;
                                        } else {
                                            $response['message'] = 'Password updated and user approved but email notification failed to send';
                                        }
                                    } else {
                                        $response['message'] = 'Password updated successfully and user approved (No email sent - invalid or missing email address)';
                                    }
                                    $response['success'] = true;
                                } else {
                                    error_log("Password reset update error: " . $update_stmt->error);
                                    $response['message'] = 'Error updating password: ' . $update_stmt->error;
                                }
                                $update_stmt->close();
                            } else {
                                error_log("Failed to prepare update statement: " . $conn->error);
                                $response['message'] = 'Error preparing update statement: ' . $conn->error;
                            }
                        } else {
                            $response['message'] = 'No new password found in the request';
                        }
                    } else {
                        $response['message'] = 'Password reset request not found or already processed';
                    }
                } else {
                    error_log("Error executing password fetch query: " . $get_password_stmt->error);
                    $response['message'] = 'Error fetching password data: ' . $get_password_stmt->error;
                }
                $get_password_stmt->close();
            } else {
                error_log("Failed to prepare password fetch statement: " . $conn->error);
                $response['message'] = 'Error preparing password fetch statement: ' . $conn->error;
            }
            
        } elseif ($action_type === 'reject_reset') {
            // Get employee email before deletion for notification
            $get_emp_stmt = $conn->prepare("SELECT full_name, employee_email FROM registrations_emp WHERE id = ?");
            $employee_name = '';
            $employee_email = '';
            if ($get_emp_stmt) {
                $get_emp_stmt->bind_param("i", $request_id);
                $get_emp_stmt->execute();
                $emp_result = $get_emp_stmt->get_result();
                if ($emp_result->num_rows > 0) {
                    $emp_data = $emp_result->fetch_assoc();
                    $employee_name = $emp_data['full_name'] ?? '';
                    $employee_email = $emp_data['employee_email'] ?? '';
                }
                $get_emp_stmt->close();
            }
            
            // DELETE the entire record from registrations_emp table
            $delete_stmt = $conn->prepare("DELETE FROM registrations_emp WHERE id = ?");
            if ($delete_stmt) {
                $delete_stmt->bind_param("i", $request_id);
                if ($delete_stmt->execute()) {
                    $response['success'] = true;
                    $response['message'] = 'Record deleted successfully!';
                } else {
                    $response['message'] = 'Error deleting record: ' . $delete_stmt->error;
                }
                $delete_stmt->close();
            } else {
                $response['message'] = 'Error preparing delete statement: ' . $conn->error;
            }
        }
    }
    
    header('Content-Type: application/json');
    echo json_encode($response);
    exit();
}

// Check if this is an AJAX request for modal content - NOW FOR BOTH DEO AND MIS ADMIN
if (isset($_GET['get_pending']) && $_GET['get_pending'] == 'true') {
    if ($has_approval_access) { // Both DEO and MIS Admin
        // Refresh data for accurate count
        $check_roles_table = $conn->query("SHOW TABLES LIKE 'employee_roles'");
        if ($check_roles_table->num_rows > 0) {
            $check_pending = $conn->prepare("SELECT re.id, re.full_name, re.emp_numb, re.cnic, re.dob, re.employee_email, er.role_name, re.created_at, re.reg_approved_by, re.reg_approved_time FROM registrations_emp re LEFT JOIN employee_roles er ON re.role_id = er.role_id WHERE re.status = 0 AND re.forgot_password_request = 0 ORDER BY re.created_at DESC");
        } else {
            $check_pending = $conn->prepare("SELECT re.id, re.full_name, re.emp_numb, re.cnic, re.dob, re.employee_email, re.created_at, re.reg_approved_by, re.reg_approved_time FROM registrations_emp re WHERE re.status = 0 AND re.forgot_password_request = 0 ORDER BY re.created_at DESC");
        }
        
        $pending_registrations_refresh = [];
        if ($check_pending) {
            if ($check_pending->execute()) {
                $pending_result = $check_pending->get_result();
                while ($row = $pending_result->fetch_assoc()) {
                    if (!isset($row['role_name'])) {
                        $row['role_name'] = 'Employee';
                    }
                    $pending_registrations_refresh[] = $row;
                }
                $check_pending->close();
            }
        }
        ?>
        <?php if (empty($pending_registrations_refresh)): ?>
            <div class="emp-dashboard-no-pending">
                <i class="fas fa-check-circle"></i>
                <h5>No Pending Requests</h5>
                <p>There are no registration requests pending approval at this time.</p>
            </div>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table table-hover emp-dashboard-table approval-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Full Name</th>
                            <th>Employee No</th>
                            <th>CNIC</th>
                            <th>Email</th>
                            <th>Date of Birth</th>
                            <th>Role</th>
                            <th>Registration Date</th>
                            <th>Approved By</th>
                            <th>Approval Time</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($pending_registrations_refresh as $registration): ?>
                        <tr id="registration-row-<?php echo $registration['id']; ?>">
                            <td><?php echo $registration['id']; ?></td>
                            <td><strong><?php echo htmlspecialchars($registration['full_name']); ?></strong></td>
                            <td><?php echo htmlspecialchars($registration['emp_numb'] ?? 'N/A'); ?></td>
                            <td class="emp-dashboard-cnic-display"><?php echo htmlspecialchars($registration['cnic']); ?></td>
                            <td><?php echo htmlspecialchars($registration['employee_email'] ?? 'N/A'); ?></td>
                            <td><?php echo htmlspecialchars($registration['dob']); ?></td>
                            <td>
                                <span class="badge bg-info emp-dashboard-role-badge">
                                    <?php echo htmlspecialchars($registration['role_name']); ?>
                                </span>
                            </td>
                            <td><?php echo date('Y-m-d H:i', strtotime($registration['created_at'])); ?></td>
                            <td>
                                <?php if (!empty($registration['reg_approved_by'])): ?>
                                    <span class="text-success"><?php echo htmlspecialchars($registration['reg_approved_by']); ?></span>
                                <?php else: ?>
                                    <span class="text-muted">Pending</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if (!empty($registration['reg_approved_time'])): ?>
                                    <?php echo date('Y-m-d H:i', strtotime($registration['reg_approved_time'])); ?>
                                <?php else: ?>
                                    <span class="text-muted">-</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <div class="emp-dashboard-action-buttons">
                                    <?php if (empty($registration['reg_approved_by'])): ?>
                                        <button class="btn btn-success emp-dashboard-btn-action" onclick="empDashboardApproveRegistration(<?php echo $registration['id']; ?>)">
                                            <i class="fas fa-check"></i> Approve
                                        </button>
                                    <?php endif; ?>
                                    <button class="btn btn-danger emp-dashboard-btn-action" onclick="empDashboardRejectRegistration(<?php echo $registration['id']; ?>)">
                                            <i class="fas fa-times"></i> Reject
                                    </button>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
        <?php
        exit();
    }
}

// Check if this is an AJAX request for password reset modal content - NOW FOR BOTH DEO AND MIS ADMIN
if (isset($_GET['get_password_reset']) && $_GET['get_password_reset'] == 'true') {
    if ($has_approval_access) { // Both DEO and MIS Admin
        // Check what columns exist
        $check_columns = $conn->query("SHOW COLUMNS FROM registrations_emp");
        $columns = [];
        while ($col = $check_columns->fetch_assoc()) {
            $columns[$col['Field']] = true;
        }
        
        // Build SQL query based on available columns
        $sql_fields = "re.id, re.full_name, re.emp_numb, re.cnic, re.employee_email, re.forgot_password_new, re.created_at";
        if (isset($columns['last_password_change'])) {
            $sql_fields .= ", re.last_password_change";
        }
        
        // Check if employee_roles table exists
        $check_roles = $conn->query("SHOW TABLES LIKE 'employee_roles'");
        if ($check_roles->num_rows > 0) {
            $sql_fields .= ", er.role_name";
        }
        
        $sql = "SELECT $sql_fields
                FROM registrations_emp re";
        
        if ($check_roles->num_rows > 0) {
            $sql .= " LEFT JOIN employee_roles er ON re.role_id = er.role_id";
        }
        
        $sql .= " WHERE re.forgot_password_request = 1 
                AND re.status = 0
                ORDER BY re.created_at DESC";
        
        $result = $conn->query($sql);
        if ($result) {
            $count = $result->num_rows;
            
            $password_reset_requests_refresh = [];
            while ($row = $result->fetch_assoc()) {
                if (!isset($row['role_name'])) {
                    $row['role_name'] = 'Employee';
                }
                $password_reset_requests_refresh[] = $row;
            }
            
            ?>
            <?php if (empty($password_reset_requests_refresh)): ?>
                <div class="emp-dashboard-no-pending">
                    <i class="fas fa-check-circle"></i>
                    <h5>No Password Reset Requests</h5>
                    <p>There are no password reset requests pending at this time.</p>
                </div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-hover emp-dashboard-table approval-table">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Employee Name</th>
                                <th>Employee No</th>
                                <th>CNIC</th>
                                <th>Email</th>
                                <th>Role</th>
                                <th>Request Date</th>
                                <th>Last Password Change</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($password_reset_requests_refresh as $request): ?>
                            <tr id="password-reset-row-<?php echo $request['id']; ?>">
                                <td><?php echo $request['id']; ?></td>
                                <td><strong><?php echo htmlspecialchars($request['full_name'] ?? 'N/A'); ?></strong></td>
                                <td><?php echo htmlspecialchars($request['emp_numb'] ?? 'N/A'); ?></td>
                                <td class="emp-dashboard-cnic-display"><?php echo htmlspecialchars($request['cnic'] ?? 'N/A'); ?></td>
                                <td><?php echo htmlspecialchars($request['employee_email'] ?? 'N/A'); ?></td>
                                <td>
                                    <span class="badge bg-info emp-dashboard-role-badge">
                                        <?php echo htmlspecialchars($request['role_name']); ?>
                                    </span>
                                </td>
                                <td><?php echo date('Y-m-d H:i', strtotime($request['created_at'])); ?></td>
                                <td>
                                    <?php if (!empty($request['last_password_change'])): ?>
                                        <?php echo date('Y-m-d H:i', strtotime($request['last_password_change'])); ?>
                                    <?php else: ?>
                                        <span class="text-muted">Never</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <div class="emp-dashboard-action-buttons">
                                        <button class="btn btn-success emp-dashboard-btn-action" 
                                                onclick="empDashboardApprovePasswordReset(<?php echo $request['id']; ?>)">
                                            <i class="fas fa-check"></i> Approve
                                        </button>
                                        <button class="btn btn-danger emp-dashboard-btn-action" 
                                                onclick="empDashboardRejectPasswordReset(<?php echo $request['id']; ?>)">
                                            <i class="fas fa-times"></i> Reject
                                        </button>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
            <?php
        } else {
            ?>
            <div class="emp-dashboard-no-pending">
                <i class="fas fa-exclamation-triangle"></i>
                <h5>Database Error</h5>
                <p>Unable to load password reset requests due to database error.</p>
                <p class="text-muted small">Error: <?php echo htmlspecialchars($conn->error); ?></p>
            </div>
            <?php
        }
    } else {
        ?>
        <div class="emp-dashboard-no-pending">
            <i class="fas fa-ban"></i>
            <h5>Access Denied</h5>
            <p>You do not have permission to view password reset requests.</p>
        </div>
        <?php
    }
    exit();
}

// Check if this is an AJAX request for registered employees list (ONLY for DEO and MIS)
if (isset($_GET['get_registered_employees']) && $_GET['get_registered_employees'] == 'true' && ($is_deo || $is_mis_admin)) {
    ?>
    <div class="print-header" style="display:none;">
        <div class="text-center">
            <h3>AJ&K Education Department District Kotli</h3>
            <h4>Registered Employees List</h4>
            <p>Generated on: <?php echo date('F j, Y, g:i a'); ?></p>
            <hr>
        </div>
    </div>
    
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h5>Registered Employees (<?php echo count($all_employees); ?>)</h5>
        <button class="btn btn-primary btn-sm" onclick="printRegisteredEmployees()">
            <i class="fas fa-print me-1"></i>Print List
        </button>
    </div>
    
    <?php if (!empty($all_employees)): ?>
        <div class="table-responsive">
            <table class="table table-sm table-hover" id="registeredEmployeesTable">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>Full Name</th>
                        <th>Employee No</th>
                        <th>CNIC</th>
                        <th>Email</th>
                        <th>Role</th>
                        <th>Profile Status</th>
                        <th>Registration Date</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($all_employees as $index => $emp): ?>
                        <tr>
                            <td><?php echo $index + 1; ?></td>
                            <td><strong><?php echo htmlspecialchars($emp['full_name']); ?></strong></td>
                            <td><?php echo htmlspecialchars($emp['emp_numb']); ?></td>
                            <td class="emp-dashboard-cnic-display"><?php echo htmlspecialchars($emp['cnic']); ?></td>
                            <td><?php echo htmlspecialchars($emp['employee_email'] ?? 'N/A'); ?></td>
                            <td>
                                <span class="badge bg-info emp-dashboard-role-badge">
                                    <?php echo htmlspecialchars($emp['role_name'] ?? 'Employee'); ?>
                                </span>
                            </td>
                            <td>
                                <?php if ($emp['profile_completed']): ?>
                                    <span class="badge bg-success">Completed</span>
                                <?php else: ?>
                                    <span class="badge bg-warning">Pending</span>
                                <?php endif; ?>
                            </td>
                            <td><?php echo date('Y-m-d', strtotime($emp['created_at'])); ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php else: ?>
        <p class="text-muted text-center">No registered employees found</p>
    <?php endif; ?>
    <?php
    exit();
}

// Check if this is an AJAX request for completed profiles list (ONLY for DEO and MIS)
if (isset($_GET['get_completed_profiles']) && $_GET['get_completed_profiles'] == 'true' && ($is_deo || $is_mis_admin)) {
    ?>
    <div class="print-header" style="display:none;">
        <div class="text-center">
            <h3>AJ&K Education Department District Kotli</h3>
            <h4>Completed Profiles List</h4>
            <p>Generated on: <?php echo date('F j, Y, g:i a'); ?></p>
            <hr>
        </div>
    </div>
    
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h5>Completed Profiles (<?php echo count($all_completed_profiles); ?>)</h5>
        <button class="btn btn-primary btn-sm" onclick="printCompletedProfiles()">
            <i class="fas fa-print me-1"></i>Print List
        </button>
    </div>
    
    <?php if (!empty($all_completed_profiles)): ?>
        <div class="table-responsive">
            <table class="table table-sm table-hover" id="completedProfilesTable">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>Full Name</th>
                        <th>Employee No</th>
                        <th>CNIC</th>
                        <th>Email</th>
                        <th>Role</th>
                        <th>Registration Date</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($all_completed_profiles as $index => $emp): ?>
                        <tr>
                            <td><?php echo $index + 1; ?></td>
                            <td><strong><?php echo htmlspecialchars($emp['full_name']); ?></strong></td>
                            <td><?php echo htmlspecialchars($emp['emp_numb']); ?></td>
                            <td class="emp-dashboard-cnic-display"><?php echo htmlspecialchars($emp['cnic']); ?></td>
                            <td><?php echo htmlspecialchars($emp['employee_email'] ?? 'N/A'); ?></td>
                            <td>
                                <span class="badge bg-info emp-dashboard-role-badge">
                                    <?php echo htmlspecialchars($emp['role_name'] ?? 'Employee'); ?>
                                </span>
                            </td>
                            <td><?php echo date('Y-m-d', strtotime($emp['created_at'])); ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php else: ?>
        <p class="text-muted text-center">No completed profiles found</p>
    <?php endif; ?>
    <?php
    exit();
}

// Check if this is an AJAX request for pending profiles list (ONLY for DEO and MIS)
if (isset($_GET['get_pending_profiles']) && $_GET['get_pending_profiles'] == 'true' && ($is_deo || $is_mis_admin)) {
    ?>
    <div class="print-header" style="display:none;">
        <div class="text-center">
            <h3>AJ&K Education Department District Kotli</h3>
            <h4>Pending Profiles List</h4>
            <p>Generated on: <?php echo date('F j, Y, g:i a'); ?></p>
            <hr>
        </div>
    </div>
    
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h5>Pending Profiles (<?php echo count($all_pending_profiles); ?>)</h5>
        <button class="btn btn-primary btn-sm" onclick="printPendingProfiles()">
            <i class="fas fa-print me-1"></i>Print List
        </button>
    </div>
    
    <?php if (!empty($all_pending_profiles)): ?>
        <div class="table-responsive">
            <table class="table table-sm table-hover" id="pendingProfilesTable">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>Full Name</th>
                        <th>Employee No</th>
                        <th>CNIC</th>
                        <th>Email</th>
                        <th>Role</th>
                        <th>Registration Date</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($all_pending_profiles as $index => $emp): ?>
                        <tr>
                            <td><?php echo $index + 1; ?></td>
                            <td><strong><?php echo htmlspecialchars($emp['full_name']); ?></strong></td>
                            <td><?php echo htmlspecialchars($emp['emp_numb']); ?></td>
                            <td class="emp-dashboard-cnic-display"><?php echo htmlspecialchars($emp['cnic']); ?></td>
                            <td><?php echo htmlspecialchars($emp['employee_email'] ?? 'N/A'); ?></td>
                            <td>
                                <span class="badge bg-info emp-dashboard-role-badge">
                                    <?php echo htmlspecialchars($emp['role_name'] ?? 'Employee'); ?>
                                </span>
                            </td>
                            <td><?php echo date('Y-m-d', strtotime($emp['created_at'])); ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php else: ?>
        <p class="text-muted text-center">No pending profiles found</p>
    <?php endif; ?>
    <?php
    exit();
}

// Logout handling
if (isset($_GET['logout'])) {
    session_destroy();
    setcookie('remember_employee', '', time() - 3600, "/");
    header("Location: login_emp.php");
    exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AJ&K Education Department District Kotli - Employee Dashboard</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        /* ============ EMPLOYEE DASHBOARD COMPLETE CSS ============ */
        :root {
            --education-blue: #1a3e72;
            --education-gold: #c4a747;
            --education-green: #2e7d32;
            --education-red: #b33939;
            --education-purple: #5e4fa2;
            --education-teal: #008b8b;
            --education-orange: #ff6b4a;
            --education-dark: #2c3e50;
            --education-light: #e9f0f7;
            --education-gray: #6c7a8a;
            --education-success: #28a745;
            --education-warning: #ffc107;
            --education-danger: #dc3545;
            --education-info: #17a2b8;
            --border-radius-sm: 8px;
            --border-radius-md: 12px;
            --border-radius-lg: 16px;
            --border-radius-xl: 20px;
            --box-shadow-sm: 0 2px 8px rgba(0,0,0,0.05);
            --box-shadow-md: 0 5px 20px rgba(0,0,0,0.08);
            --box-shadow-lg: 0 10px 30px rgba(0,0,0,0.12);
            --box-shadow-hover: 0 20px 40px rgba(26,62,114,0.15);
            --transition-fast: all 0.2s ease;
            --transition-normal: all 0.3s ease;
            --transition-slow: all 0.4s cubic-bezier(0.165, 0.84, 0.44, 1);
        }

        body.emp-dashboard-body {
            background-color: #f8fafc;
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            overflow: <?php echo !$profile_exists ? 'hidden' : 'auto'; ?>;
            line-height: 1.6;
            color: var(--education-dark);
        }

        /* ============ PROFILE COMPLETION MODAL ============ */
        .profile-modal-backdrop {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.85);
            z-index: 9999;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
            box-sizing: border-box;
            backdrop-filter: blur(8px);
        }

        .profile-modal {
            background: white;
            border-radius: var(--border-radius-xl);
            box-shadow: 0 25px 80px rgba(0, 0, 0, 0.4);
            width: 90%;
            max-width: 600px;
            max-height: 95vh;
            overflow-y: auto;
            z-index: 10000;
            position: relative;
            animation: modalAppear 0.5s ease-out;
            display: flex;
            flex-direction: column;
        }

        @keyframes modalAppear {
            0% {
                opacity: 0;
                transform: scale(0.9) translateY(-30px);
            }
            100% {
                opacity: 1;
                transform: scale(1) translateY(0);
            }
        }

        .profile-modal-header {
            background: linear-gradient(135deg, var(--education-blue), #2a5ca0);
            color: white;
            border-radius: var(--border-radius-xl) var(--border-radius-xl) 0 0;
            padding: 1.5rem 2rem;
            text-align: center;
            position: relative;
            flex-shrink: 0;
        }

        .profile-modal-header .d-flex {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 15px;
        }

        .profile-modal-header h3 {
            margin: 0;
            font-weight: 700;
            font-size: 1.5rem;
            letter-spacing: -0.5px;
        }

        .profile-modal-body {
            padding: 2rem 2.5rem;
            text-align: center;
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: center;
            overflow-y: auto;
        }

        .profile-icon {
            font-size: 4rem;
            color: var(--education-blue);
            margin-bottom: 1.5rem;
            animation: bounce 2s infinite;
        }

        @keyframes bounce {
            0%, 20%, 50%, 80%, 100% { transform: translateY(0); }
            40% { transform: translateY(-15px); }
            60% { transform: translateY(-8px); }
        }

        .profile-modal-title {
            font-size: 1.8rem;
            font-weight: 800;
            color: var(--education-blue);
            margin-bottom: 1rem;
            line-height: 1.3;
            letter-spacing: -0.5px;
        }

        .profile-modal-text {
            font-size: 1.1rem;
            color: var(--education-gray);
            margin-bottom: 1.8rem;
            line-height: 1.6;
        }

        .profile-alert {
            background: linear-gradient(135deg, #fff3cd, #ffeaa7);
            border: 2px solid var(--education-warning);
            border-radius: var(--border-radius-md);
            padding: 1.2rem 1.5rem;
            margin-bottom: 2rem;
            text-align: center;
            box-shadow: 0 4px 12px rgba(255, 193, 7, 0.2);
        }

        .profile-alert p {
            color: #856404;
            margin: 0;
            font-size: 1rem;
            line-height: 1.5;
        }

        .profile-btn {
            padding: 1rem 2.5rem;
            font-size: 1.1rem;
            font-weight: 700;
            border-radius: var(--border-radius-md);
            background: linear-gradient(135deg, var(--education-blue), #2a5ca0);
            border: none;
            color: white;
            transition: var(--transition-normal);
            box-shadow: 0 6px 20px rgba(26, 62, 114, 0.4);
            margin-bottom: 1.5rem;
            min-height: 60px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 100%;
            letter-spacing: 0.5px;
        }

        .profile-btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 10px 30px rgba(26, 62, 114, 0.5);
            background: linear-gradient(135deg, #2a5ca0, var(--education-blue));
            color: white;
        }

        .profile-btn:active {
            transform: translateY(-1px);
        }

        .pulse-effect {
            animation: pulse 3s infinite;
        }

        @keyframes pulse {
            0% { box-shadow: 0 0 0 0 rgba(26, 62, 114, 0.4); }
            70% { box-shadow: 0 0 0 20px rgba(26, 62, 114, 0); }
            100% { box-shadow: 0 0 0 0 rgba(26, 62, 114, 0); }
        }

        .time-indicator {
            color: var(--education-gray);
            font-size: 0.9rem;
            margin-top: 1rem;
        }

        .profile-security {
            color: var(--education-teal);
            font-size: 0.85rem;
            margin-top: 1rem;
            padding-top: 1rem;
            border-top: 1px solid #e9ecef;
        }

        /* ============ SIDEBAR STYLES ============ */
        .emp-dashboard-sidebar {
            background: linear-gradient(180deg, var(--education-blue) 0%, #0e2a4a 100%) !important;
            color: white;
            min-height: calc(100vh - 56px);
            box-shadow: 4px 0 20px rgba(0, 0, 0, 0.1);
            transition: var(--transition-normal);
        }

        .emp-dashboard-sidebar .position-sticky {
            padding-top: 20px;
        }

        .emp-dashboard-sidebar .nav-link {
            color: rgba(255, 255, 255, 0.85);
            border-left: 4px solid transparent;
            padding: 12px 20px;
            margin-bottom: 2px;
            font-weight: 500;
            transition: var(--transition-fast);
            border-radius: 0 8px 8px 0;
        }

        .emp-dashboard-sidebar .nav-link:hover {
            color: white;
            background: linear-gradient(90deg, rgba(255, 255, 255, 0.15), transparent);
            border-left: 4px solid var(--education-gold);
        }

        .emp-dashboard-sidebar .nav-link.active {
            color: white;
            background: linear-gradient(90deg, rgba(255, 255, 255, 0.2), transparent);
            border-left: 4px solid var(--education-gold);
            font-weight: 600;
        }

        .emp-dashboard-sidebar .nav-link i {
            margin-right: 12px;
            width: 20px;
            text-align: center;
            font-size: 1.1rem;
        }

        .emp-dashboard-sidebar .text-center img {
            border: 3px solid rgba(255, 255, 255, 0.3);
            transition: var(--transition-normal);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
        }

        .emp-dashboard-sidebar .text-center img:hover {
            transform: scale(1.05);
            border-color: var(--education-gold);
        }

        .emp-dashboard-sidebar h6 {
            font-weight: 700;
            margin-bottom: 5px;
            letter-spacing: -0.3px;
        }

        .emp-dashboard-sidebar small {
            opacity: 0.9;
            font-size: 0.8rem;
            display: block;
        }

        /* ============ ENHANCED QUICK STATS CARDS ============ */
        .quick-stats-section {
            margin-bottom: 30px;
        }

        .enhanced-stat-card {
            background: linear-gradient(145deg, #ffffff, #f6f9fc);
            border: none;
            border-radius: var(--border-radius-lg);
            box-shadow: var(--box-shadow-sm);
            transition: var(--transition-slow);
            overflow: hidden;
            position: relative;
            margin-bottom: 15px;
            height: 150px;
            cursor: pointer;
            border: 1px solid rgba(26, 62, 114, 0.05);
        }

        .enhanced-stat-card:before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            border-radius: var(--border-radius-lg);
            border: 1px solid transparent;
            background: linear-gradient(145deg, rgba(26, 62, 114, 0.1), transparent) border-box;
            -webkit-mask: linear-gradient(#fff 0 0) padding-box, linear-gradient(#fff 0 0);
            mask: linear-gradient(#fff 0 0) padding-box, linear-gradient(#fff 0 0);
            -webkit-mask-composite: destination-out;
            mask-composite: exclude;
            pointer-events: none;
        }

        .enhanced-stat-card:hover {
            transform: translateY(-8px);
            box-shadow: var(--box-shadow-hover);
            border-color: var(--education-blue);
        }

        .enhanced-stat-card .card-body {
            padding: 18px;
            position: relative;
            z-index: 1;
            height: 100%;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
        }

        .stat-card-decoration {
            position: absolute;
            top: -15px;
            right: -15px;
            width: 100px;
            height: 100px;
            background: radial-gradient(circle at top right, rgba(26, 62, 114, 0.06), transparent 70%);
            border-radius: 50%;
            z-index: 0;
        }

        .stat-icon-container {
            width: 52px;
            height: 52px;
            border-radius: 14px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 12px;
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
        }

        .stat-icon-container.primary {
            background: linear-gradient(145deg, var(--education-blue), #2a5ca0);
        }

        .stat-icon-container.success {
            background: linear-gradient(145deg, var(--education-green), #43a047);
        }

        .stat-icon-container.warning {
            background: linear-gradient(145deg, var(--education-gold), #d4b34c);
        }

        .stat-icon-container.info {
            background: linear-gradient(145deg, var(--education-teal), #00a0a0);
        }

        .stat-icon-container i {
            font-size: 24px;
            color: white;
        }

        .stat-content {
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
        }

        .stat-value {
            font-size: 2rem;
            font-weight: 800;
            color: var(--education-dark);
            line-height: 1;
            margin-bottom: 5px;
            letter-spacing: -0.8px;
        }

        .stat-label {
            font-size: 0.85rem;
            color: var(--education-gray);
            font-weight: 600;
            margin-bottom: 10px;
            text-transform: uppercase;
            letter-spacing: 0.8px;
        }

        .stat-progress {
            width: 100%;
            height: 6px;
            background-color: #e9ecef;
            border-radius: 10px;
            overflow: hidden;
            margin-top: 8px;
        }

        .stat-progress-bar {
            height: 100%;
            border-radius: 10px;
            transition: width 0.8s cubic-bezier(0.4, 0, 0.2, 1);
        }

        .stat-progress-bar.primary {
            background: linear-gradient(to right, var(--education-blue), #3a6eb0);
        }

        .stat-progress-bar.success {
            background: linear-gradient(to right, var(--education-green), #53a857);
        }

        .stat-progress-bar.warning {
            background: linear-gradient(to right, var(--education-gold), #e4c354);
        }

        .stat-percentage {
            font-size: 0.75rem;
            font-weight: 600;
            margin-top: 5px;
            display: flex;
            justify-content: space-between;
            color: var(--education-gray);
        }

        /* ============ SMART MODULE CARDS - NEW ATTRACTIVE DESIGN ============ */
        .smart-module-card {
            background: white;
            border-radius: var(--border-radius-xl);
            box-shadow: var(--box-shadow-md);
            transition: var(--transition-slow);
            margin-bottom: 25px;
            overflow: hidden;
            position: relative;
            border: none;
            height: 100%;
            border: 1px solid rgba(0, 0, 0, 0.03);
        }

        .smart-module-card:hover {
            transform: translateY(-12px);
            box-shadow: var(--box-shadow-hover);
        }

        .smart-module-card .card-body {
            padding: 2rem 1.5rem;
            position: relative;
            z-index: 1;
            display: flex;
            flex-direction: column;
            align-items: center;
            text-align: center;
        }

        .smart-module-icon {
            width: 80px;
            height: 80px;
            border-radius: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 1.5rem;
            font-size: 2.5rem;
            color: white;
            box-shadow: 0 15px 25px rgba(0, 0, 0, 0.15);
            transition: var(--transition-normal);
        }

        .smart-module-card:hover .smart-module-icon {
            transform: scale(1.1) rotate(5deg);
        }

        .smart-module-title {
            font-size: 1.3rem;
            font-weight: 700;
            margin-bottom: 0.8rem;
            color: var(--education-dark);
            letter-spacing: -0.5px;
        }

        .smart-module-desc {
            font-size: 0.9rem;
            color: var(--education-gray);
            margin-bottom: 1.5rem;
            line-height: 1.6;
            flex-grow: 1;
        }

        .smart-module-badge {
            position: absolute;
            top: 15px;
            right: 15px;
            background: rgba(255, 255, 255, 0.98);
            border-radius: 30px;
            padding: 6px 14px;
            font-size: 0.7rem;
            font-weight: 700;
            color: var(--education-blue);
            box-shadow: var(--box-shadow-sm);
            border: 1px solid rgba(26, 62, 114, 0.15);
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .smart-module-btn {
            background: linear-gradient(145deg, #f8fafc, #edf2f7);
            border: none;
            color: var(--education-blue);
            font-weight: 700;
            padding: 12px 24px;
            border-radius: 40px;
            font-size: 0.85rem;
            transition: var(--transition-normal);
            width: 100%;
            border: 1px solid rgba(26, 62, 114, 0.1);
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .smart-module-btn:hover {
            background: var(--education-blue);
            color: white;
            border-color: var(--education-blue);
            transform: translateY(-3px);
            box-shadow: 0 8px 20px rgba(26, 62, 114, 0.3);
        }

        .smart-module-btn i {
            margin-right: 8px;
        }

        /* Card icon color variants */
        .icon-blue { background: linear-gradient(145deg, #1e3c72, #2a5ca0); }
        .icon-gold { background: linear-gradient(145deg, #c4a747, #d4b34c); }
        .icon-green { background: linear-gradient(145deg, #2e7d32, #43a047); }
        .icon-red { background: linear-gradient(145deg, #b33939, #c94c4c); }
        .icon-purple { background: linear-gradient(145deg, #5e4fa2, #6e60b2); }
        .icon-teal { background: linear-gradient(145deg, #008b8b, #00a0a0); }
        .icon-orange { background: linear-gradient(145deg, #ff6b4a, #ff8a6c); }
        .icon-indigo { background: linear-gradient(145deg, #3f51b5, #5c6bc0); }
        .icon-pink { background: linear-gradient(145deg, #c2185b, #d81b60); }
        .icon-cyan { background: linear-gradient(145deg, #0097a7, #00acc1); }
        .icon-brown { background: linear-gradient(145deg, #5d4037, #6d4c41); }
        .icon-gray { background: linear-gradient(145deg, #546e7a, #607d8b); }

        /* ============ WELCOME BANNER ============ */
        .welcome-banner {
            background: linear-gradient(105deg, var(--education-blue) 0%, #2a5ca0 100%);
            border-radius: var(--border-radius-xl);
            padding: 30px 35px;
            color: white;
            margin-bottom: 35px;
            position: relative;
            overflow: hidden;
            box-shadow: var(--box-shadow-lg);
        }

        .welcome-banner:before {
            content: '';
            position: absolute;
            top: -50%;
            right: -10%;
            width: 350px;
            height: 350px;
            background: radial-gradient(circle, rgba(255, 255, 255, 0.12) 0%, transparent 70%);
            border-radius: 50%;
        }

        .welcome-banner:after {
            content: '';
            position: absolute;
            bottom: -30%;
            left: -5%;
            width: 250px;
            height: 250px;
            background: radial-gradient(circle, rgba(255, 255, 255, 0.08) 0%, transparent 70%);
            border-radius: 50%;
        }

        .welcome-banner h2 {
            font-weight: 800;
            margin-bottom: 12px;
            font-size: 1.8rem;
            letter-spacing: -0.5px;
            position: relative;
            z-index: 2;
        }

        .welcome-banner p {
            opacity: 0.95;
            margin-bottom: 0;
            font-size: 1.1rem;
            position: relative;
            z-index: 2;
        }

        .welcome-banner .badge {
            background: rgba(255, 255, 255, 0.2);
            color: white;
            padding: 8px 16px;
            border-radius: 30px;
            font-weight: 600;
            border: 1px solid rgba(255, 255, 255, 0.3);
        }

        /* ============ SECTION HEADERS ============ */
        .section-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 25px;
            padding-bottom: 15px;
            border-bottom: 2px solid rgba(26, 62, 114, 0.08);
        }

        .section-title {
            font-size: 1.5rem;
            font-weight: 800;
            color: var(--education-dark);
            position: relative;
            padding-left: 18px;
            letter-spacing: -0.5px;
        }

        .section-title:before {
            content: '';
            position: absolute;
            left: 0;
            top: 8px;
            bottom: 8px;
            width: 6px;
            background: var(--education-blue);
            border-radius: 6px;
        }

        .section-icon {
            color: var(--education-blue);
            background: rgba(26, 62, 114, 0.1);
            width: 44px;
            height: 44px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.2rem;
        }

        /* ============ QUICK ACTIONS ============ */
        .quick-actions-wrapper {
            background: white;
            border-radius: var(--border-radius-lg);
            padding: 25px;
            box-shadow: var(--box-shadow-sm);
            margin-bottom: 35px;
            border: 1px solid rgba(0, 0, 0, 0.03);
        }

        .quick-actions-wrapper h5 {
            color: var(--education-dark);
            font-weight: 700;
            margin-bottom: 20px;
            font-size: 1.2rem;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .quick-action-btn {
            padding: 12px 22px;
            border-radius: 40px;
            background: #f8fafc;
            border: 1px solid #edf2f7;
            color: var(--education-dark);
            font-weight: 600;
            transition: var(--transition-normal);
            display: inline-flex;
            align-items: center;
            gap: 12px;
            margin-right: 12px;
            margin-bottom: 12px;
            font-size: 0.9rem;
        }

        .quick-action-btn:hover {
            background: var(--education-blue);
            color: white;
            border-color: var(--education-blue);
            transform: translateY(-4px);
            box-shadow: 0 8px 20px rgba(26, 62, 114, 0.25);
        }

        .quick-action-btn i {
            font-size: 1rem;
        }

        /* ============ MODAL STYLES ============ */
        .emp-dashboard-modal,
        .quick-stats-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.75);
            z-index: 1050;
            display: none;
            justify-content: center;
            align-items: center;
            padding: 20px;
            box-sizing: border-box;
            backdrop-filter: blur(5px);
        }

        .emp-dashboard-modal-content,
        .quick-stats-modal-content {
            background: white;
            border-radius: var(--border-radius-xl);
            box-shadow: 0 30px 80px rgba(0, 0, 0, 0.35);
            width: 95%;
            max-width: 1400px;
            max-height: 90vh;
            overflow-y: auto;
            z-index: 1060;
            position: relative;
            animation: empDashboardModalAppear 0.4s ease-out;
        }

        @keyframes empDashboardModalAppear {
            0% {
                opacity: 0;
                transform: scale(0.95) translateY(-20px);
            }
            100% {
                opacity: 1;
                transform: scale(1) translateY(0);
            }
        }

        .emp-dashboard-modal-header,
        .quick-stats-modal-header {
            background: linear-gradient(135deg, var(--education-blue), #2a5ca0);
            color: white;
            border-radius: var(--border-radius-xl) var(--border-radius-xl) 0 0;
            padding: 1.5rem 2rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: sticky;
            top: 0;
            z-index: 10;
        }

        .emp-dashboard-modal-header h3,
        .quick-stats-modal-header h3 {
            margin: 0;
            font-weight: 700;
            font-size: 1.4rem;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .close-emp-dashboard-modal {
            background: none;
            border: none;
            color: white;
            font-size: 1.6rem;
            cursor: pointer;
            padding: 0;
            line-height: 1;
            transition: var(--transition-fast);
            width: 36px;
            height: 36px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 8px;
        }

        .close-emp-dashboard-modal:hover {
            background: rgba(255, 255, 255, 0.15);
            transform: scale(1.1);
        }

        .emp-dashboard-modal-body,
        .quick-stats-modal-body {
            padding: 2rem;
            max-height: calc(90vh - 120px);
            overflow-y: auto;
        }

        /* ============ TABLE STYLES ============ */
        .emp-dashboard-table.approval-table {
            width: 100%;
            margin-bottom: 0;
            border-collapse: separate;
            border-spacing: 0;
        }

        .emp-dashboard-table.approval-table th {
            background: linear-gradient(135deg, var(--education-blue), #1e4a7a);
            color: white;
            font-weight: 600;
            padding: 14px 18px;
            position: sticky;
            top: 0;
            z-index: 5;
            border: none;
            white-space: nowrap;
            font-size: 0.9rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .emp-dashboard-table.approval-table td {
            padding: 14px 18px;
            vertical-align: middle;
            border-bottom: 1px solid #e9ecef;
            word-wrap: break-word;
            max-width: 200px;
            font-size: 0.95rem;
        }

        .emp-dashboard-table.approval-table tbody tr {
            transition: var(--transition-fast);
        }

        .emp-dashboard-table.approval-table tbody tr:hover {
            background-color: rgba(26, 62, 114, 0.04);
        }

        .emp-dashboard-table.approval-table tbody tr td {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .emp-dashboard-cnic-display {
            font-family: 'Courier New', monospace;
            font-size: 0.9rem;
            white-space: nowrap;
            font-weight: 600;
        }

        .emp-dashboard-role-badge {
            padding: 6px 14px;
            border-radius: 30px;
            font-size: 0.8rem;
            font-weight: 600;
            display: inline-block;
            background: linear-gradient(145deg, #e3f2fd, #bbdef5);
            color: var(--education-blue);
            border: 1px solid rgba(26, 62, 114, 0.1);
        }

        /* ============ ACTION BUTTONS ============ */
        .emp-dashboard-action-buttons {
            display: flex;
            gap: 10px;
            flex-wrap: nowrap;
            min-width: 200px;
        }

        .emp-dashboard-btn-action {
            padding: 8px 16px;
            font-size: 0.85rem;
            border-radius: 8px;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            white-space: nowrap;
            border: none;
            cursor: pointer;
            flex-shrink: 0;
            font-weight: 600;
            transition: var(--transition-fast);
        }

        .emp-dashboard-btn-action.btn-success {
            background: linear-gradient(145deg, #28a745, #218838);
            color: white;
        }

        .emp-dashboard-btn-action.btn-danger {
            background: linear-gradient(145deg, #dc3545, #c82333);
            color: white;
        }

        .emp-dashboard-btn-action:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
        }

        .emp-dashboard-approval-button {
            background: linear-gradient(135deg, rgba(255, 255, 255, 0.2), rgba(255, 255, 255, 0.1));
            border: 1px solid rgba(255, 255, 255, 0.3);
            border-radius: 8px;
            margin-right: 12px;
            transition: var(--transition-normal);
            cursor: pointer;
            position: relative;
            padding: 8px 20px;
            color: white;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            white-space: nowrap;
            font-weight: 600;
        }

        .emp-dashboard-approval-button:hover {
            background: rgba(255, 255, 255, 0.25);
            transform: translateY(-3px);
            box-shadow: 0 8px 20px rgba(0, 0, 0, 0.2);
            color: white;
        }

        /* ============ BADGES & COUNTERS ============ */
        .emp-dashboard-pending-count-badge {
            background: linear-gradient(145deg, #dc3545, #c82333) !important;
            color: white !important;
            font-weight: 700;
            padding: 6px 12px;
            border-radius: 30px;
            font-size: 0.75rem;
            margin-left: 8px;
            box-shadow: 0 3px 8px rgba(220, 53, 69, 0.3);
        }

        .emp-dashboard-warning-badge-pulse {
            background: linear-gradient(145deg, #ffc107, #e0a800) !important;
            color: #212529 !important;
            font-weight: 700;
            padding: 6px 12px;
            border-radius: 30px;
            font-size: 0.75rem;
            margin-left: 8px;
            box-shadow: 0 3px 8px rgba(255, 193, 7, 0.3);
        }

        /* ============ NO PENDING STATE ============ */
        .emp-dashboard-no-pending {
            text-align: center;
            padding: 50px 20px;
            color: var(--education-gray);
        }

        .emp-dashboard-no-pending i {
            font-size: 4rem;
            margin-bottom: 1.2rem;
            color: #cbd5e0;
        }

        .emp-dashboard-no-pending h5 {
            font-size: 1.3rem;
            font-weight: 700;
            margin-bottom: 0.8rem;
            color: var(--education-dark);
        }

        .emp-dashboard-no-pending p {
            color: var(--education-gray);
            font-size: 1rem;
        }

        /* ============ LOADING SPINNER ============ */
        .emp-dashboard-loading-spinner {
            display: none;
            text-align: center;
            padding: 40px 20px;
        }

        .emp-dashboard-spinner-border {
            width: 3.5rem;
            height: 3.5rem;
            color: var(--education-blue);
        }

        /* ============ ACCESS DENIED ============ */
        .access-denied {
            text-align: center;
            padding: 60px 20px;
            background: white;
            border-radius: var(--border-radius-lg);
            box-shadow: var(--box-shadow-sm);
            margin: 20px 0;
        }

        .access-denied i {
            font-size: 4.5rem;
            color: #cbd5e0;
            margin-bottom: 20px;
        }

        .access-denied h4 {
            color: var(--education-dark);
            margin-bottom: 15px;
            font-weight: 700;
            font-size: 1.5rem;
        }

        .access-denied p {
            color: var(--education-gray);
            font-size: 1.1rem;
            line-height: 1.6;
        }

        /* ============ CHANGE PASSWORD MODAL ============ */
        #changePasswordModal .modal-content {
            border-radius: var(--border-radius-xl);
            overflow: hidden;
            border: none;
            box-shadow: 0 15px 50px rgba(0, 0, 0, 0.2);
        }

        #changePasswordModal .modal-header {
            background: linear-gradient(135deg, var(--education-blue), #2a5ca0);
            color: white;
            border-bottom: none;
            padding: 1.8rem 2rem;
        }

        #changePasswordModal .modal-header h5 {
            font-weight: 700;
            font-size: 1.3rem;
        }

        #changePasswordModal .modal-body {
            padding: 2rem;
        }

        .password-input-wrapper {
            position: relative;
            margin-bottom: 1.8rem;
        }

        .password-input-wrapper .form-label {
            display: block;
            margin-bottom: 10px;
            font-weight: 600;
            color: var(--education-dark);
            font-size: 0.95rem;
        }

        .password-input-wrapper .form-control {
            border-radius: 12px;
            padding: 14px 50px 14px 18px;
            border: 2px solid #e9ecef;
            transition: var(--transition-fast);
            line-height: 1.5;
            height: 54px;
            width: 100%;
            box-sizing: border-box;
            font-size: 0.95rem;
        }

        .password-input-wrapper .form-control:focus {
            border-color: var(--education-blue);
            box-shadow: 0 0 0 0.2rem rgba(26, 62, 114, 0.15);
            outline: none;
        }

        .password-toggle-btn {
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%);
            height: 40px;
            display: flex;
            align-items: center;
            background: transparent;
            border: none;
            padding: 0 10px;
            cursor: pointer;
            color: var(--education-gray);
            transition: var(--transition-fast);
        }

        .password-toggle-btn:hover {
            color: var(--education-blue);
        }

        .password-toggle-btn i {
            font-size: 1.1rem;
        }

        #changePasswordModal .btn-primary {
            background: linear-gradient(145deg, var(--education-blue), #2a5ca0);
            border: none;
            padding: 12px 28px;
            border-radius: 10px;
            font-weight: 600;
            transition: var(--transition-normal);
        }

        #changePasswordModal .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(26, 62, 114, 0.3);
        }

        #changePasswordModal .btn-secondary {
            padding: 12px 28px;
            border-radius: 10px;
            font-weight: 600;
        }

        /* ============ PRINT STYLES ============ */
        .print-header {
            display: none;
        }

        @media print {
            body * {
                visibility: hidden;
            }
            .quick-stats-modal-content,
            .quick-stats-modal-content * {
                visibility: visible;
            }
            .quick-stats-modal-content {
                position: absolute;
                left: 0;
                top: 0;
                width: 100%;
                height: auto;
                margin: 0;
                padding: 0;
                box-shadow: none;
                border-radius: 0;
            }
            .quick-stats-modal-header,
            .quick-stats-modal-body {
                position: static;
                padding: 15px;
            }
            .print-header {
                display: block;
            }
        }

        /* ============ RESPONSIVE DESIGN ============ */
        @media (max-width: 1200px) {
            .smart-module-icon {
                width: 70px;
                height: 70px;
                font-size: 2rem;
            }
            .smart-module-title {
                font-size: 1.2rem;
            }
        }

        @media (max-width: 992px) {
            .emp-dashboard-sidebar {
                min-height: auto;
            }
            .welcome-banner h2 {
                font-size: 1.6rem;
            }
            .section-title {
                font-size: 1.3rem;
            }
        }

        @media (max-width: 768px) {
            .profile-modal {
                width: 95%;
                max-height: 95vh;
                border-radius: 15px;
            }
            .profile-modal-header {
                padding: 1.2rem 1.5rem;
            }
            .profile-modal-header h3 {
                font-size: 1.3rem;
            }
            .profile-modal-body {
                padding: 1.5rem 1.8rem;
            }
            .profile-modal-title {
                font-size: 1.4rem;
            }
            .profile-modal-text {
                font-size: 1rem;
            }
            .profile-icon {
                font-size: 3.5rem;
            }
            .profile-btn {
                padding: 0.9rem 2rem;
                font-size: 1rem;
                min-height: 55px;
            }
            
            .smart-module-card .card-body {
                padding: 1.5rem 1rem;
            }
            .smart-module-icon {
                width: 60px;
                height: 60px;
                font-size: 1.8rem;
            }
            .smart-module-title {
                font-size: 1.1rem;
            }
            
            .welcome-banner {
                padding: 20px;
            }
            .welcome-banner h2 {
                font-size: 1.4rem;
            }
            
            .emp-dashboard-table.approval-table {
                display: block;
                overflow-x: auto;
                white-space: nowrap;
            }
            
            .emp-dashboard-action-buttons {
                flex-direction: column;
                gap: 5px;
                min-width: 140px;
            }
            
            .emp-dashboard-btn-action {
                padding: 6px 12px;
                font-size: 0.8rem;
                width: 100%;
                justify-content: center;
            }
            
            .enhanced-stat-card {
                height: 140px;
            }
            .stat-value {
                font-size: 1.6rem;
            }
            
            .quick-actions {
                gap: 8px;
            }
            .quick-action-btn {
                padding: 10px 16px;
                font-size: 0.85rem;
            }
        }

        @media (max-width: 576px) {
            .profile-modal-header {
                padding: 1rem !important;
            }
            .profile-modal-header h3 {
                font-size: 1.2rem;
            }
            .profile-modal-body {
                padding: 1.2rem 1.5rem;
            }
            .profile-modal-title {
                font-size: 1.3rem;
            }
            .profile-modal-text {
                font-size: 0.95rem;
            }
            .profile-icon {
                font-size: 3rem;
            }
            
            .welcome-banner {
                padding: 15px;
            }
            .welcome-banner h2 {
                font-size: 1.2rem;
            }
            .welcome-banner p {
                font-size: 0.95rem;
            }
            
            .section-title {
                font-size: 1.2rem;
            }
            
            .smart-module-card .card-body {
                padding: 1.2rem 0.8rem;
            }
            .smart-module-icon {
                width: 50px;
                height: 50px;
                font-size: 1.5rem;
            }
            .smart-module-title {
                font-size: 1rem;
            }
            .smart-module-desc {
                font-size: 0.8rem;
            }
            .smart-module-btn {
                padding: 10px 16px;
                font-size: 0.75rem;
            }
            
            .enhanced-stat-card {
                height: 130px;
            }
            .stat-value {
                font-size: 1.4rem;
            }
            .stat-icon-container {
                width: 45px;
                height: 45px;
            }
        }

        /* ============ UTILITY CLASSES ============ */
        .cursor-pointer {
            cursor: pointer;
        }

        .text-education-blue {
            color: var(--education-blue);
        }

        .bg-education-light {
            background-color: var(--education-light);
        }

        .border-radius-lg {
            border-radius: var(--border-radius-lg);
        }

        .no-scrollbar::-webkit-scrollbar {
            display: none;
        }

        .no-scrollbar {
            -ms-overflow-style: none;
            scrollbar-width: none;
        }

        /* ============ ANIMATIONS ============ */
        @keyframes slideInUp {
            from {
                transform: translateY(30px);
                opacity: 0;
            }
            to {
                transform: translateY(0);
                opacity: 1;
            }
        }

        .animate-slide-in-up {
            animation: slideInUp 0.5s ease-out;
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        .animate-fade-in {
            animation: fadeIn 0.5s ease-out;
        }

        /* ============ SCROLLBAR STYLING ============ */
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }

        ::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 10px;
        }

        ::-webkit-scrollbar-thumb {
            background: var(--education-blue);
            border-radius: 10px;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: #2a5ca0;
        }
    </style>
</head>
<body class="emp-dashboard-body">
    <!-- Profile Completion Modal -->
    <?php if (!$profile_exists): ?>
    <div class="profile-modal-backdrop">
        <div class="profile-modal pulse-effect">
            <div class="profile-modal-header">
                <div class="d-flex align-items-center justify-content-center">
                    <i class="fas fa-user-shield me-3" style="font-size: 1.8rem;"></i>
                    <h3 class="mb-0">Profile Completion Required</h3>
                </div>
            </div>
            <div class="profile-modal-body">
                <div class="profile-icon">
                    <i class="fas fa-user-plus"></i>
                </div>
                <h2 class="profile-modal-title">Complete Your Employee Profile</h2>
                <p class="profile-modal-text">
                    Welcome to <strong>AJ&K Education Department District Kotli</strong>.  
                    To continue using the system without restrictions, your employee profile must be completed.
                </p>
                <div class="profile-alert">
                    <i class="fas fa-exclamation-circle"></i>
                    <span>
                        Profile completion is <strong class="text-danger">mandatory</strong>.  
                        Access to system features will remain limited until this step is finished.
                    </span>
                </div>
                <button type="button" class="btn profile-btn" onclick="empDashboardRedirectToProfile()">
                    <i class="fas fa-user-edit me-2"></i>
                    Complete My Profile
                </button>
                <div class="time-indicator">
                    <i class="fas fa-clock"></i>
                    Profile completion takes only 2–3 minutes
                </div>
                <div class="profile-security">
                    <i class="fas fa-shield-alt"></i>
                    Your data is protected under AJ&K Data Protection Policy
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <!-- Registration Approval Modal - Accessible to DEO and MIS Admin -->
    <div class="emp-dashboard-modal" id="registrationApprovalModal">
        <div class="emp-dashboard-modal-content">
            <div class="emp-dashboard-modal-header">
                <h3>
                    <i class="fas fa-user-check me-2"></i>Registration Approval Requests
                    <?php if ($pending_count > 0): ?>
                        <span class="badge bg-danger ms-2 emp-dashboard-pending-count-badge"><?php echo $pending_count; ?></span>
                    <?php endif; ?>
                </h3>
                <button class="close-emp-dashboard-modal" id="closeRegistrationModal">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="emp-dashboard-modal-body" id="registrationModalBody">
                <div class="emp-dashboard-loading-spinner" id="registrationLoadingSpinner">
                    <div class="emp-dashboard-spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <p class="mt-3">Loading registration requests...</p>
                </div>
                <div id="registrationRequestsContent"></div>
            </div>
        </div>
    </div>

    <!-- Password Reset Approval Modal - Accessible to DEO and MIS Admin -->
    <div class="emp-dashboard-modal" id="passwordResetApprovalModal">
        <div class="emp-dashboard-modal-content">
            <div class="emp-dashboard-modal-header">
                <h3>
                    <i class="fas fa-key me-2"></i>Password Reset Requests
                    <?php if ($password_reset_count > 0): ?>
                        <span class="badge bg-warning ms-2 emp-dashboard-warning-badge-pulse"><?php echo $password_reset_count; ?></span>
                    <?php endif; ?>
                </h3>
                <button class="close-emp-dashboard-modal" id="closePasswordResetModal">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="emp-dashboard-modal-body" id="passwordResetModalBody">
                <div class="emp-dashboard-loading-spinner" id="passwordResetLoadingSpinner">
                    <div class="emp-dashboard-spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <p class="mt-3">Loading password reset requests...</p>
                </div>
                <div id="passwordResetRequestsContent"></div>
            </div>
        </div>
    </div>

    <!-- Quick Stats Modals - Only for DEO and MIS -->
    <div class="quick-stats-modal" id="registeredEmployeesModal">
        <div class="quick-stats-modal-content">
            <div class="quick-stats-modal-header">
                <h3>
                    <i class="fas fa-users me-2"></i>Registered Employees (<?php echo count($all_employees ?? []); ?>)
                </h3>
                <div class="d-flex align-items-center">
                    <button class="btn btn-primary btn-sm me-2" onclick="printRegisteredEmployees()">
                        <i class="fas fa-print me-1"></i>Print
                    </button>
                    <button class="close-emp-dashboard-modal" onclick="closeRegisteredEmployeesModal()">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </div>
            <div class="quick-stats-modal-body" id="registeredEmployeesContent"></div>
        </div>
    </div>

    <div class="quick-stats-modal" id="completedProfilesModal">
        <div class="quick-stats-modal-content">
            <div class="quick-stats-modal-header">
                <h3>
                    <i class="fas fa-user-check me-2"></i>Completed Profiles (<?php echo count($all_completed_profiles ?? []); ?>)
                </h3>
                <div class="d-flex align-items-center">
                    <button class="btn btn-primary btn-sm me-2" onclick="printCompletedProfiles()">
                        <i class="fas fa-print me-1"></i>Print
                    </button>
                    <button class="close-emp-dashboard-modal" onclick="closeCompletedProfilesModal()">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </div>
            <div class="quick-stats-modal-body" id="completedProfilesContent"></div>
        </div>
    </div>

    <div class="quick-stats-modal" id="pendingProfilesModal">
        <div class="quick-stats-modal-content">
            <div class="quick-stats-modal-header">
                <h3>
                    <i class="fas fa-clock me-2"></i>Pending Profiles (<?php echo count($all_pending_profiles ?? []); ?>)
                </h3>
                <div class="d-flex align-items-center">
                    <button class="btn btn-primary btn-sm me-2" onclick="printPendingProfiles()">
                        <i class="fas fa-print me-1"></i>Print
                    </button>
                    <button class="close-emp-dashboard-modal" onclick="closePendingProfilesModal()">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </div>
            <div class="quick-stats-modal-body" id="pendingProfilesContent"></div>
        </div>
    </div>

    <!-- Navigation Bar -->
    <nav class="navbar navbar-expand-lg navbar-dark" style="background-color: var(--education-blue);">
        <div class="container-fluid">
            <a class="navbar-brand" href="#">
                <img src="images/logo.png" alt="AJ&K Education Department District Kotli" style="border-radius: 50%; width: 50px; height: 50px; object-fit: cover;">
                <span class="ms-2 d-none d-md-inline">AJ&K Education</span>
            </a>
            
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            
            <div class="collapse navbar-collapse" id="navbarNav">
                <?php if ($has_approval_access): // Both DEO and MIS Admin ?>
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link position-relative emp-dashboard-approval-button d-none d-lg-inline-block" href="javascript:void(0)" onclick="empDashboardOpenRegistrationApprovalModal()">
                            <i class="fas fa-user-check me-2"></i> Registration Approvals
                            <?php if ($pending_count > 0): ?>
                                <span class="badge bg-danger emp-dashboard-pending-count-badge"><?php echo $pending_count; ?></span>
                            <?php endif; ?>
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link position-relative emp-dashboard-approval-button d-none d-lg-inline-block" href="javascript:void(0)" onclick="empDashboardOpenPasswordResetApprovalModal()">
                            <i class="fas fa-key me-2"></i> Password Reset
                            <?php if ($password_reset_count > 0): ?>
                                <span class="badge bg-warning emp-dashboard-warning-badge-pulse"><?php echo $password_reset_count; ?></span>
                            <?php endif; ?>
                        </a>
                    </li>
                </ul>
                <?php endif; ?>
                
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle position-relative d-flex align-items-center" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown">
                            <img src="<?php echo htmlspecialchars($profile_pic); ?>" 
                                 class="rounded-circle me-2" 
                                 style="width: 32px; height: 32px; object-fit: cover;"
                                 alt="Profile"
                                 onerror="this.onerror=null; this.src='images/default_profile.png'">
                            <span class="d-none d-md-inline"><?php echo htmlspecialchars($employee['full_name']); ?></span>
                            <span class="d-inline d-md-none">Profile</span>
                        </a>
                        <ul class="dropdown-menu dropdown-menu-end">
                            <li><a class="dropdown-item" href="employee_profile_view.php"><i class="fas fa-user me-2"></i> My Profile</a></li>
                            <li><a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#changePasswordModal"><i class="fas fa-key me-2"></i> Change Password</a></li>
                            
                            <?php if ($has_approval_access): // Both DEO and MIS Admin ?>
                            <li><hr class="dropdown-divider"></li>
                            <li>
                                <a class="dropdown-item text-primary position-relative" href="javascript:void(0)" onclick="empDashboardOpenRegistrationApprovalModal()">
                                    <i class="fas fa-user-check me-2"></i> Registration Approvals
                                    <?php if ($pending_count > 0): ?>
                                        <span class="badge bg-danger ms-2 emp-dashboard-pending-count-badge"><?php echo $pending_count; ?></span>
                                    <?php endif; ?>
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item text-warning position-relative" href="javascript:void(0)" onclick="empDashboardOpenPasswordResetApprovalModal()">
                                    <i class="fas fa-key me-2"></i> Password Reset Requests
                                    <?php if ($password_reset_count > 0): ?>
                                        <span class="badge bg-warning ms-2 emp-dashboard-warning-badge-pulse"><?php echo $password_reset_count; ?></span>
                                    <?php endif; ?>
                                </a>
                            </li>
                            <?php endif; ?>
                            
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item text-danger" href="?logout=1"><i class="fas fa-sign-out-alt me-2"></i> Logout</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <div class="col-md-3 col-lg-2 d-md-block emp-dashboard-sidebar p-0">
                <div class="position-sticky pt-3">
                    <div class="text-center p-3">
                        <img src="<?php echo htmlspecialchars($profile_pic); ?>" 
                             class="rounded-circle mb-2" 
                             style="width: 100px; height: 100px; object-fit: cover; border: 3px solid white;"
                             alt="Profile Image"
                             onerror="this.onerror=null; this.src='data:image/svg+xml;charset=UTF-8,<?php echo urlencode('<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"100\" height=\"100\" viewBox=\"0 0 100 100\"><rect width=\"100\" height=\"100\" fill=\"#1a3e72\"/><text x=\"50\" y=\"55\" text-anchor=\"middle\" fill=\"white\" font-size=\"40\" font-weight=\"bold\">' . $initials . '</text></svg>'); ?>'">
                        <h6 class="text-white"><?php echo htmlspecialchars($employee['full_name']); ?></h6>
                        <small class="text-light"><?php echo htmlspecialchars($employee['role_name']); ?></small>
                    </div>
                    
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link active" href="employee_dashboard.php">
                                <i class="fas fa-tachometer-alt"></i> Dashboard
                            </a>
                        </li>
                        
                        <?php if ($has_hr_access): ?>
                        <li class="nav-item">
                            <a class="nav-link" href="#">
                                <i class="fas fa-user-tie"></i> HR Management
                            </a>
                        </li>
                        <?php endif; ?>
                        
                        <?php if ($has_school_access): ?>
                        <li class="nav-item">
                            <a class="nav-link" href="#">
                                <i class="fas fa-school"></i> School Management
                            </a>
                        </li>
                        <?php endif; ?>
                        
                        <?php if ($has_student_access): ?>
                        <li class="nav-item">
                            <a class="nav-link" href="#">
                                <i class="fas fa-users"></i> Student Management
                            </a>
                        </li>
                        <?php endif; ?>
                        
                        <?php if ($has_finance_access): ?>
                        <li class="nav-item">
                            <a class="nav-link" href="#">
                                <i class="fas fa-money-bill-wave"></i> Finance
                            </a>
                        </li>
                        <?php endif; ?>
                        
                        <?php if ($has_teacher_portal_access): ?>
                        <li class="nav-item">
                            <a class="nav-link" href="#">
                                <i class="fas fa-chalkboard-teacher"></i> Teacher Portal
                            </a>
                        </li>
                        <?php endif; ?>
                        
                        <?php if ($has_reports_access): ?>
                        <li class="nav-item">
                            <a class="nav-link" href="#">
                                <i class="fas fa-chart-bar"></i> Reports
                            </a>
                        </li>
                        <?php endif; ?>
                        
                        <li class="nav-item">
                            <a class="nav-link" href="#">
                                <i class="fas fa-file-alt"></i> Documents
                            </a>
                        </li>
                        
                        <?php if ($has_announcements_access): ?>
                        <li class="nav-item">
                            <a class="nav-link" href="#">
                                <i class="fas fa-bullhorn"></i> Announcements
                            </a>
                        </li>
                        <?php endif; ?>
                        
                        <?php if ($has_approval_access): // Both DEO and MIS Admin ?>
                        <?php if ($pending_count > 0): ?>
                        <li class="nav-item">
                            <a class="nav-link text-warning" href="javascript:void(0)" onclick="empDashboardOpenRegistrationApprovalModal()">
                                <i class="fas fa-user-check"></i> Registration Approvals
                                <?php if ($pending_count > 0): ?>
                                    <span class="badge bg-danger float-end emp-dashboard-pending-count-badge"><?php echo $pending_count; ?></span>
                                <?php endif; ?>
                            </a>
                        </li>
                        <?php endif; ?>
                        <?php if ($password_reset_count > 0): ?>
                        <li class="nav-item">
                            <a class="nav-link text-warning" href="javascript:void(0)" onclick="empDashboardOpenPasswordResetApprovalModal()">
                                <i class="fas fa-key"></i> Password Reset Requests
                                <?php if ($password_reset_count > 0): ?>
                                    <span class="badge bg-warning float-end emp-dashboard-warning-badge-pulse"><?php echo $password_reset_count; ?></span>
                                <?php endif; ?>
                            </a>
                        </li>
                        <?php endif; ?>
                        <?php endif; ?>
                    </ul>
                </div>
            </div>
            
            <!-- Main Content -->
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4 py-4 emp-dashboard-main-content">
                <!-- Welcome Banner -->
                <div class="welcome-banner">
                    <div class="row align-items-center">
                        <div class="col-md-8">
                            <h2><i class="fas fa-hand-wave me-2"></i> Welcome back, <?php echo htmlspecialchars(explode(' ', $employee['full_name'])[0]); ?>!</h2>
                            <p><?php echo date('l, F j, Y'); ?> • <span class="badge bg-light text-dark"><?php echo htmlspecialchars($employee['role_name']); ?></span></p>
                        </div>
                        <div class="col-md-4 text-md-end">
                            <i class="fas fa-graduation-cap" style="font-size: 3rem; opacity: 0.5;"></i>
                        </div>
                    </div>
                </div>
                
                <!-- Profile Completion Alert -->
                <?php if (!$profile_exists): ?>
                <div class="alert alert-warning alert-dismissible fade show" role="alert">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    <strong>Attention!</strong> Your profile is incomplete. Please complete your profile to access all system features.
                    <button type="button" class="btn btn-warning btn-sm ms-3" onclick="empDashboardRedirectToProfile()">
                        <i class="fas fa-user-edit me-1"></i>Complete Profile
                    </button>
                </div>
                <?php endif; ?>
                
                <!-- Pending Requests Alerts - For DEO and MIS Admin -->
                <?php if ($pending_count > 0 && $has_approval_access): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <i class="fas fa-user-check me-2"></i>
                    <strong>Registration Approvals Pending!</strong> You have <?php echo $pending_count; ?> registration request(s) waiting for your approval.
                    <button type="button" class="btn btn-danger btn-sm ms-3" onclick="empDashboardOpenRegistrationApprovalModal()">
                        <i class="fas fa-external-link-alt me-1"></i>Review Now
                    </button>
                </div>
                <?php endif; ?>
                
                <?php if ($password_reset_count > 0 && $has_approval_access): ?>
                <div class="alert alert-warning alert-dismissible fade show" role="alert">
                    <i class="fas fa-key me-2"></i>
                    <strong>Password Reset Requests Pending!</strong> You have <?php echo $password_reset_count; ?> password reset request(s) waiting for your approval.
                    <button type="button" class="btn btn-warning btn-sm ms-3" onclick="empDashboardOpenPasswordResetApprovalModal()">
                        <i class="fas fa-external-link-alt me-1"></i>Review Now
                    </button>
                </div>
                <?php endif; ?>
                
                <!-- QUICK STATS SECTION - Only visible to DEO and MIS/Administrator -->
                <?php if ($show_quick_stats): ?>
                <div class="quick-stats-section">
                    <div class="section-header">
                        <div class="section-title">System Overview Dashboard</div>
                        <div class="section-icon">
                            <i class="fas fa-chart-line"></i>
                        </div>
                    </div>
                    
                    <div class="row mb-4">
                        <!-- Registered Employees Card -->
                        <div class="col-md-4 col-sm-6">
                            <div class="enhanced-stat-card" onclick="openRegisteredEmployeesModal()">
                                <div class="stat-card-decoration"></div>
                                <div class="card-body">
                                    <div class="stat-icon-container primary">
                                        <i class="fas fa-users"></i>
                                    </div>
                                    <div class="stat-content">
                                        <div>
                                            <div class="stat-value"><?php echo $stats['total_registered'] ?? 0; ?></div>
                                            <div class="stat-label">Registered Employees</div>
                                        </div>
                                        <div>
                                            <div class="stat-progress">
                                                <div class="stat-progress-bar primary" style="width: <?php echo min(100, (($stats['total_registered'] ?? 0)/1000)*100); ?>%"></div>
                                            </div>
                                            <div class="stat-percentage text-primary">
                                                Total registered in system
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Completed Profiles Card -->
                        <div class="col-md-4 col-sm-6">
                            <div class="enhanced-stat-card" onclick="openCompletedProfilesModal()">
                                <div class="stat-card-decoration"></div>
                                <div class="card-body">
                                    <div class="stat-icon-container success">
                                        <i class="fas fa-user-check"></i>
                                    </div>
                                    <div class="stat-content">
                                        <div>
                                            <div class="stat-value"><?php echo $stats['profiles_completed'] ?? 0; ?></div>
                                            <div class="stat-label">Profiles Completed</div>
                                        </div>
                                        <div>
                                            <div class="stat-progress">
                                                <div class="stat-progress-bar success" style="width: <?php echo $stats['completion_percentage'] ?? 0; ?>%"></div>
                                            </div>
                                            <div class="stat-percentage text-success">
                                                <?php echo $stats['completion_percentage'] ?? 0; ?>% completion rate
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Pending Profiles Card -->
                        <div class="col-md-4 col-sm-6">
                            <div class="enhanced-stat-card" onclick="openPendingProfilesModal()">
                                <div class="stat-card-decoration"></div>
                                <div class="card-body">
                                    <div class="stat-icon-container warning">
                                        <i class="fas fa-clock"></i>
                                    </div>
                                    <div class="stat-content">
                                        <div>
                                            <div class="stat-value"><?php echo $stats['pending_profiles'] ?? 0; ?></div>
                                            <div class="stat-label">Pending Profiles</div>
                                        </div>
                                        <div>
                                            <div class="stat-progress">
                                                <div class="stat-progress-bar warning" style="width: <?php echo min(100, (($stats['pending_profiles'] ?? 0)/max(1, ($stats['total_registered'] ?? 1)))*100); ?>%"></div>
                                            </div>
                                            <div class="stat-percentage text-warning">
                                                Profiles to be completed
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
                
                <!-- Quick Actions Row (Visible to all) -->
                <div class="quick-actions-wrapper">
                    <h5 class="mb-3"><i class="fas fa-bolt me-2" style="color: var(--education-blue);"></i>Quick Actions</h5>
                    <div class="quick-actions">
                        <?php if ($is_deo || $is_mis_admin): ?>
                            <button class="quick-action-btn" onclick="openRegisteredEmployeesModal()">
                                <i class="fas fa-users"></i> View All Employees
                            </button>
                        <?php endif; ?>
                        <?php if ($has_approval_access): // Both DEO and MIS Admin ?>
                            <button class="quick-action-btn" onclick="empDashboardOpenRegistrationApprovalModal()">
                                <i class="fas fa-user-check"></i> Approvals (<?php echo $pending_count; ?>)
                            </button>
                            <button class="quick-action-btn" onclick="empDashboardOpenPasswordResetApprovalModal()">
                                <i class="fas fa-key"></i> Password Reset (<?php echo $password_reset_count; ?>)
                            </button>
                        <?php endif; ?>
                        <button class="quick-action-btn" onclick="window.location.href='employee_profile_view.php'">
                            <i class="fas fa-user"></i> My Profile
                        </button>
                        <button class="quick-action-btn" data-bs-toggle="modal" data-bs-target="#changePasswordModal">
                            <i class="fas fa-key"></i> Change Password
                        </button>
                        <button class="quick-action-btn" onclick="refreshDashboard()">
                            <i class="fas fa-sync-alt"></i> Refresh
                        </button>
                    </div>
                </div>
                
                <!-- MAIN SYSTEM MODULES SECTION - Core Modules -->
                <div class="section-header mt-4">
                    <div class="section-title">Core System Modules</div>
                    <div class="section-icon">
                        <i class="fas fa-cubes"></i>
                    </div>
                </div>
                
                <div class="row">
                    <!-- HR Management Card -->
                    <?php if ($has_hr_access): ?>
                    <div class="col-lg-3 col-md-4 col-sm-6 mb-4">
                        <div class="smart-module-card">
                            <div class="card-body">
                                <span class="smart-module-badge">Admin</span>
                                <div class="smart-module-icon icon-blue">
                                    <i class="fas fa-user-tie"></i>
                                </div>
                                <h5 class="smart-module-title">HR Management</h5>
                                <p class="smart-module-desc">Manage employee records, transfers, promotions and HR processes</p>
                                <button class="smart-module-btn" onclick="window.location.href='#'">
                                    <i class="fas fa-arrow-right"></i> Access Module
                                </button>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <!-- School Management Card -->
                    <?php if ($has_school_access): ?>
                    <div class="col-lg-3 col-md-4 col-sm-6 mb-4">
                        <div class="smart-module-card">
                            <div class="card-body">
                                <span class="smart-module-badge">Education</span>
                                <div class="smart-module-icon icon-green">
                                    <i class="fas fa-school"></i>
                                </div>
                                <h5 class="smart-module-title">School Management</h5>
                                <p class="smart-module-desc">Manage school information, resources, infrastructure and staff</p>
                                <button class="smart-module-btn" onclick="window.location.href='#'">
                                    <i class="fas fa-arrow-right"></i> Access Module
                                </button>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Student Management Card -->
                    <?php if ($has_student_access): ?>
                    <div class="col-lg-3 col-md-4 col-sm-6 mb-4">
                        <div class="smart-module-card">
                            <div class="card-body">
                                <span class="smart-module-badge">Academics</span>
                                <div class="smart-module-icon icon-teal">
                                    <i class="fas fa-users"></i>
                                </div>
                                <h5 class="smart-module-title">Student Management</h5>
                                <p class="smart-module-desc">Student records, attendance, enrollments and academic progress</p>
                                <button class="smart-module-btn" onclick="window.location.href='#'">
                                    <i class="fas fa-arrow-right"></i> Access Module
                                </button>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Finance Management Card -->
                    <?php if ($has_finance_access): ?>
                    <div class="col-lg-3 col-md-4 col-sm-6 mb-4">
                        <div class="smart-module-card">
                            <div class="card-body">
                                <span class="smart-module-badge">Finance</span>
                                <div class="smart-module-icon icon-gold">
                                    <i class="fas fa-money-bill-wave"></i>
                                </div>
                                <h5 class="smart-module-title">Finance & Budget</h5>
                                <p class="smart-module-desc">Budget planning, expenditures, grants and financial reports</p>
                                <button class="smart-module-btn" onclick="window.location.href='#'">
                                    <i class="fas fa-arrow-right"></i> Access Module
                                </button>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
                
                <!-- ADDITIONAL MODULES SECTION - New Cards -->
                <div class="section-header mt-2">
                    <div class="section-title">Additional Services</div>
                    <div class="section-icon">
                        <i class="fas fa-puzzle-piece"></i>
                    </div>
                </div>
                
                <div class="row">
                    <!-- Teacher Portal Card -->
                    <?php if ($has_teacher_portal_access || $has_teacher_results_access): ?>
                    <div class="col-lg-3 col-md-4 col-sm-6 mb-4">
                        <div class="smart-module-card">
                            <div class="card-body">
                                <span class="smart-module-badge">Teaching</span>
                                <div class="smart-module-icon icon-purple">
                                    <i class="fas fa-chalkboard-teacher"></i>
                                </div>
                                <h5 class="smart-module-title">Teacher Portal</h5>
                                <p class="smart-module-desc">Lesson planning, attendance, assignments and class management</p>
                                <button class="smart-module-btn" onclick="window.location.href='#'">
                                    <i class="fas fa-arrow-right"></i> Open Portal
                                </button>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Results & Examinations Card -->
                    <?php if ($has_teacher_results_access): ?>
                    <div class="col-lg-3 col-md-4 col-sm-6 mb-4">
                        <div class="smart-module-card">
                            <div class="card-body">
                                <span class="smart-module-badge">Exams</span>
                                <div class="smart-module-icon icon-red">
                                    <i class="fas fa-scroll"></i>
                                </div>
                                <h5 class="smart-module-title">Results & Exams</h5>
                                <p class="smart-module-desc">Student results, exam schedules, mark sheets and transcripts</p>
                                <button class="smart-module-btn" onclick="window.location.href='#'">
                                    <i class="fas fa-arrow-right"></i> View Results
                                </button>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <!-- SMC (School Management Committees) Card -->
                    <?php if ($has_smc_access): ?>
                    <div class="col-lg-3 col-md-4 col-sm-6 mb-4">
                        <div class="smart-module-card">
                            <div class="card-body">
                                <span class="smart-module-badge">Governance</span>
                                <div class="smart-module-icon icon-orange">
                                    <i class="fas fa-users-cog"></i>
                                </div>
                                <h5 class="smart-module-title">SMC Management</h5>
                                <p class="smart-module-desc">School Management Committees, meetings, members and decisions</p>
                                <button class="smart-module-btn" onclick="window.location.href='#'">
                                    <i class="fas fa-arrow-right"></i> Manage SMC
                                </button>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Games & Fun Card - Accessible to all -->
                    <?php if ($has_games_access): ?>
                    <div class="col-lg-3 col-md-4 col-sm-6 mb-4">
                        <div class="smart-module-card">
                            <div class="card-body">
                                <span class="smart-module-badge">Recreation</span>
                                <div class="smart-module-icon icon-pink">
                                    <i class="fas fa-gamepad"></i>
                                </div>
                                <h5 class="smart-module-title">Games & Fun</h5>
                                <p class="smart-module-desc">Educational games, puzzles, quizzes and recreational activities</p>
                                <button class="smart-module-btn" onclick="window.location.href='#'">
                                    <i class="fas fa-arrow-right"></i> Play Now
                                </button>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
                
                <div class="row">
                    <!-- Books (Reading & Download) Card - Accessible to all -->
                    <?php if ($has_books_access): ?>
                    <div class="col-lg-3 col-md-4 col-sm-6 mb-4">
                        <div class="smart-module-card">
                            <div class="card-body">
                                <span class="smart-module-badge">Library</span>
                                <div class="smart-module-icon icon-cyan">
                                    <i class="fas fa-book-open"></i>
                                </div>
                                <h5 class="smart-module-title">Digital Library</h5>
                                <p class="smart-module-desc">E-books, textbooks, reference materials and research papers</p>
                                <button class="smart-module-btn" onclick="window.location.href='#'">
                                    <i class="fas fa-download"></i> Read & Download
                                </button>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Softwares & Tools Card -->
                    <?php if ($has_softwares_access): ?>
                    <div class="col-lg-3 col-md-4 col-sm-6 mb-4">
                        <div class="smart-module-card">
                            <div class="card-body">
                                <span class="smart-module-badge">Resources</span>
                                <div class="smart-module-icon icon-indigo">
                                    <i class="fas fa-laptop-code"></i>
                                </div>
                                <h5 class="smart-module-title">Software Repository</h5>
                                <p class="smart-module-desc">Educational software, tools, utilities and licensed applications</p>
                                <button class="smart-module-btn" onclick="window.location.href='#'">
                                    <i class="fas fa-download"></i> Browse Software
                                </button>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Offices Management Card -->
                    <?php if ($has_office_management_access): ?>
                    <div class="col-lg-3 col-md-4 col-sm-6 mb-4">
                        <div class="smart-module-card">
                            <div class="card-body">
                                <span class="smart-module-badge">Administration</span>
                                <div class="smart-module-icon icon-brown">
                                    <i class="fas fa-building"></i>
                                </div>
                                <h5 class="smart-module-title">Offices Management</h5>
                                <p class="smart-module-desc">Department offices, sections, inventory and office resources</p>
                                <button class="smart-module-btn" onclick="window.location.href='#'">
                                    <i class="fas fa-arrow-right"></i> Manage Offices
                                </button>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Documents & Forms Card - Accessible to all -->
                    <?php if ($has_documents_access): ?>
                    <div class="col-lg-3 col-md-4 col-sm-6 mb-4">
                        <div class="smart-module-card">
                            <div class="card-body">
                                <span class="smart-module-badge">Files</span>
                                <div class="smart-module-icon icon-gray">
                                    <i class="fas fa-file-alt"></i>
                                </div>
                                <h5 class="smart-module-title">Documents & Forms</h5>
                                <p class="smart-module-desc">Official documents, application forms, policies and templates</p>
                                <button class="smart-module-btn" onclick="window.location.href='#'">
                                    <i class="fas fa-file-pdf"></i> Access Library
                                </button>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
                
                <div class="row">
                    <!-- Applications & Requests Card - Accessible to all -->
                    <?php if ($has_applications_access): ?>
                    <div class="col-lg-3 col-md-4 col-sm-6 mb-4">
                        <div class="smart-module-card">
                            <div class="card-body">
                                <span class="smart-module-badge">Requests</span>
                                <div class="smart-module-icon icon-teal">
                                    <i class="fas fa-file-signature"></i>
                                </div>
                                <h5 class="smart-module-title">Applications</h5>
                                <p class="smart-module-desc">Submit leave applications, requests, and track status</p>
                                <button class="smart-module-btn" onclick="window.location.href='#'">
                                    <i class="fas fa-pen"></i> Apply Now
                                </button>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Seniority Lists Card -->
                    <?php if ($has_hr_access): ?>
                    <div class="col-lg-3 col-md-4 col-sm-6 mb-4">
                        <div class="smart-module-card">
                            <div class="card-body">
                                <span class="smart-module-badge">HR</span>
                                <div class="smart-module-icon icon-blue">
                                    <i class="fas fa-list-ol"></i>
                                </div>
                                <h5 class="smart-module-title">Seniority Lists</h5>
                                <p class="smart-module-desc">Employee seniority rankings, promotions and gradation</p>
                                <button class="smart-module-btn" onclick="window.location.href='#'">
                                    <i class="fas fa-arrow-right"></i> View Lists
                                </button>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Meetings & Events Card -->
                    <?php if ($has_announcements_access): ?>
                    <div class="col-lg-3 col-md-4 col-sm-6 mb-4">
                        <div class="smart-module-card">
                            <div class="card-body">
                                <span class="smart-module-badge">Calendar</span>
                                <div class="smart-module-icon icon-purple">
                                    <i class="fas fa-calendar-check"></i>
                                </div>
                                <h5 class="smart-module-title">Meetings & Events</h5>
                                <p class="smart-module-desc">Schedule meetings, events, conferences and notifications</p>
                                <button class="smart-module-btn" onclick="window.location.href='#'">
                                    <i class="fas fa-calendar-plus"></i> View Calendar
                                </button>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Reports & Analytics Card -->
                    <?php if ($has_reports_access): ?>
                    <div class="col-lg-3 col-md-4 col-sm-6 mb-4">
                        <div class="smart-module-card">
                            <div class="card-body">
                                <span class="smart-module-badge">Analytics</span>
                                <div class="smart-module-icon icon-red">
                                    <i class="fas fa-chart-pie"></i>
                                </div>
                                <h5 class="smart-module-title">Reports & Analytics</h5>
                                <p class="smart-module-desc">Data analysis, performance metrics and statistical reports</p>
                                <button class="smart-module-btn" onclick="window.location.href='#'">
                                    <i class="fas fa-chart-bar"></i> Generate Reports
                                </button>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
                
                <!-- Approval Cards Section - For DEO and MIS Admin -->
                <?php if ($has_approval_access): ?>
                <div class="section-header mt-2">
                    <div class="section-title">Administration & Approvals</div>
                    <div class="section-icon">
                        <i class="fas fa-shield-alt"></i>
                    </div>
                </div>
                
                <div class="row">
                    <div class="col-lg-3 col-md-4 col-sm-6 mb-4">
                        <div class="smart-module-card">
                            <div class="card-body">
                                <span class="smart-module-badge">Pending: <?php echo $pending_count; ?></span>
                                <div class="smart-module-icon icon-red">
                                    <i class="fas fa-user-check"></i>
                                </div>
                                <h5 class="smart-module-title">Registration Approvals</h5>
                                <p class="smart-module-desc">Review and approve new employee registrations</p>
                                <button class="smart-module-btn" onclick="empDashboardOpenRegistrationApprovalModal()">
                                    <i class="fas fa-check-circle"></i> Review (<?php echo $pending_count; ?>)
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-lg-3 col-md-4 col-sm-6 mb-4">
                        <div class="smart-module-card">
                            <div class="card-body">
                                <span class="smart-module-badge">Pending: <?php echo $password_reset_count; ?></span>
                                <div class="smart-module-icon icon-orange">
                                    <i class="fas fa-key"></i>
                                </div>
                                <h5 class="smart-module-title">Password Reset Requests</h5>
                                <p class="smart-module-desc">Approve or reject password reset requests</p>
                                <button class="smart-module-btn" onclick="empDashboardOpenPasswordResetApprovalModal()">
                                    <i class="fas fa-check-circle"></i> Review (<?php echo $password_reset_count; ?>)
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <?php if ($is_mis_admin): // Only MIS Admin can access system settings ?>
                    <div class="col-lg-3 col-md-4 col-sm-6 mb-4">
                        <div class="smart-module-card">
                            <div class="card-body">
                                <span class="smart-module-badge">System</span>
                                <div class="smart-module-icon icon-gray">
                                    <i class="fas fa-cogs"></i>
                                </div>
                                <h5 class="smart-module-title">System Settings</h5>
                                <p class="smart-module-desc">Configure system parameters, roles and permissions</p>
                                <button class="smart-module-btn" onclick="window.location.href='#'">
                                    <i class="fas fa-sliders-h"></i> Configure
                                </button>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
                <?php endif; ?>
                
                <!-- If user has no modules visible, show appropriate message -->
                <?php 
                $has_any_module = ($has_hr_access || $has_school_access || $has_student_access || $has_finance_access || 
                                  $has_teacher_portal_access || $has_teacher_results_access || $has_smc_access || 
                                  $has_games_access || $has_books_access || $has_softwares_access || 
                                  $has_office_management_access || $has_documents_access || $has_applications_access);
                
                if (!$has_any_module && !$is_mis_admin && !$is_deo): 
                ?>
                <div class="access-denied">
                    <i class="fas fa-lock"></i>
                    <h4>No Modules Available</h4>
                    <p>You don't have access to any system modules at this time.<br>Please contact your system administrator.</p>
                </div>
                <?php endif; ?>
                
                <!-- Recent Activities -->
                <div class="mt-5">
                    <div class="section-header">
                        <div class="section-title">Recent Activities</div>
                        <div class="section-icon">
                            <i class="fas fa-history"></i>
                        </div>
                    </div>
                    <div class="card">
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-striped table-hover">
                                    <thead>
                                        <tr>
                                            <th>Date</th>
                                            <th>Activity</th>
                                            <th>Action</th>
                                            <th>Status</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr>
                                            <td><?php echo date('Y-m-d H:i'); ?></td>
                                            <td>Logged in to the system</td>
                                            <td>Login</td>
                                            <td><span class="badge bg-success">Success</span></td>
                                        </tr>
                                        <?php if ($pending_count > 0 && $has_approval_access): ?>
                                        <tr>
                                            <td><?php echo date('Y-m-d'); ?></td>
                                            <td>Registration approvals pending</td>
                                            <td>Registration Approval</td>
                                            <td>
                                                <span class="badge bg-danger emp-dashboard-pending-count-badge"><?php echo $pending_count; ?> Pending</span>
                                            </td>
                                        </tr>
                                        <?php endif; ?>
                                        <?php if ($password_reset_count > 0 && $has_approval_access): ?>
                                        <tr>
                                            <td><?php echo date('Y-m-d'); ?></td>
                                            <td>Password reset requests pending</td>
                                            <td>Password Reset</td>
                                            <td>
                                                <span class="badge bg-warning emp-dashboard-warning-badge-pulse"><?php echo $password_reset_count; ?> Pending</span>
                                            </td>
                                        </tr>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <!-- Footer -->
    <footer class="footer mt-auto py-3 bg-light">
        <div class="container">
            <div class="row">
                <div class="col-md-6">
                    <span class="text-muted">AJ&K Education Department District Kotli &copy; <?php echo date('Y'); ?></span>
                </div>
                <div class="col-md-6 text-md-end">
                    <span class="text-muted">Version 2.0.0</span>
                </div>
            </div>
        </div>
    </footer>

    <!-- Change Password Modal -->
    <div class="modal fade" id="changePasswordModal" tabindex="-1" aria-labelledby="changePasswordModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="changePasswordModalLabel">
                        <i class="fas fa-key me-2"></i>Change Password
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <?php 
                    if(isset($_SESSION['password_change_success'])): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <i class="fas fa-check-circle me-2"></i>
                        <?php echo $_SESSION['password_change_success']; 
                        unset($_SESSION['password_change_success']); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                    <?php endif; ?>
                    <?php if(isset($_SESSION['password_change_error'])): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <i class="fas fa-exclamation-circle me-2"></i>
                        <?php echo $_SESSION['password_change_error']; 
                        unset($_SESSION['password_change_error']); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                    <?php endif; ?>
                    <form method="POST" id="changePasswordForm" action="change_password_emp.php">
                        <div class="password-input-wrapper mb-3">
                            <label for="current_password" class="form-label">
                                <i class="fas fa-lock me-1"></i>Current Password
                            </label>
                            <div class="position-relative">
                                <input type="password"
                                    class="form-control"
                                    id="current_password"
                                    name="current_password"
                                    autocomplete="current-password"
                                    required
                                    placeholder="Enter your current password">
                                <button type="button"
                                    class="password-toggle-btn"
                                    onclick="togglePassword('current_password')">
                                    <i class="fas fa-eye"></i>
                                </button>
                            </div>
                        </div>
                        <div class="password-input-wrapper mb-3">
                            <label for="new_password" class="form-label">
                                <i class="fas fa-key me-1"></i>New Password
                            </label>
                            <div class="position-relative">
                                <input type="password"
                                    class="form-control"
                                    id="new_password"
                                    name="new_password"
                                    autocomplete="new-password"
                                    required
                                    placeholder="Enter new password (min. 8 characters)">
                                <button type="button"
                                    class="password-toggle-btn"
                                    onclick="togglePassword('new_password')">
                                    <i class="fas fa-eye"></i>
                                </button>
                            </div>
                            <small class="text-danger">
                                Must contain uppercase, lowercase letters and a number.
                            </small>
                        </div>
                        <div class="password-input-wrapper mb-3">
                            <label for="confirm_password" class="form-label">
                                <i class="fas fa-key me-1"></i>Confirm New Password
                            </label>
                            <div class="position-relative">
                                <input type="password"
                                    class="form-control"
                                    id="confirm_password"
                                    name="confirm_password"
                                    autocomplete="new-password"
                                    required
                                    placeholder="Confirm your new password">
                                <button type="button"
                                    class="password-toggle-btn"
                                    onclick="togglePassword('confirm_password')">
                                    <i class="fas fa-eye"></i>
                                </button>
                            </div>
                            <div class="form-text" id="password-match"></div>
                        </div>
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle me-2"></i>
                            <small>After changing password, you'll need to login again with your new password.</small>
                        </div>
                        <div class="d-flex justify-content-between">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save me-2"></i>Update Password
                            </button>
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                                <i class="fas fa-times me-2"></i>Cancel
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Employee Dashboard Specific JavaScript
        (function() {
            'use strict';
            
            // Function to redirect to profile completion page
            function empDashboardRedirectToProfile() {
                window.location.href = 'emp1.php';
            }
            
            // Apply to all profile images
            document.addEventListener('DOMContentLoaded', function() {
                const profileImages = document.querySelectorAll('img[alt*="Profile"], img[alt*="profile"]');
                profileImages.forEach(img => {
                    img.onerror = function() {
                        this.src = 'images/default_profile.png';
                    };
                });
                
                // Setup modal close listeners
                setupModalCloseListeners();
                
                // Initialize modal close buttons
                document.getElementById('closeRegistrationModal')?.addEventListener('click', empDashboardCloseRegistrationModal);
                document.getElementById('closePasswordResetModal')?.addEventListener('click', empDashboardClosePasswordResetModal);
            });
            
            // Setup modal close listeners
            function setupModalCloseListeners() {
                const modals = [
                    'registrationApprovalModal',
                    'passwordResetApprovalModal',
                    'registeredEmployeesModal',
                    'completedProfilesModal',
                    'pendingProfilesModal'
                ];
                
                modals.forEach(modalId => {
                    const modal = document.getElementById(modalId);
                    if (modal) {
                        modal.addEventListener('click', function(e) {
                            if (e.target === this) {
                                closeModal(modalId);
                            }
                        });
                    }
                });
                
                document.addEventListener('keydown', function(e) {
                    if (e.key === 'Escape') {
                        const activeModal = getActiveModal();
                        if (activeModal) {
                            closeModal(activeModal.id);
                        }
                    }
                });
            }
            
            function getActiveModal() {
                const modals = [
                    'registrationApprovalModal',
                    'passwordResetApprovalModal',
                    'registeredEmployeesModal',
                    'completedProfilesModal',
                    'pendingProfilesModal'
                ];
                
                for (const modalId of modals) {
                    const modal = document.getElementById(modalId);
                    if (modal && modal.style.display === 'flex') {
                        return modal;
                    }
                }
                return null;
            }
            
            function closeModal(modalId) {
                const modal = document.getElementById(modalId);
                if (modal) {
                    modal.style.display = 'none';
                    const contentId = modalId.replace('Modal', 'Content');
                    const content = document.getElementById(contentId);
                    if (content) {
                        content.innerHTML = '';
                    }
                }
            }
            
            // Registration Approval Modal Functions - Accessible to DEO and MIS Admin
            function empDashboardOpenRegistrationApprovalModal() {
                document.getElementById('registrationApprovalModal').style.display = 'flex';
                empDashboardLoadRegistrationRequests();
            }
            
            function empDashboardCloseRegistrationModal() {
                closeModal('registrationApprovalModal');
            }
            
            function empDashboardLoadRegistrationRequests() {
                const loadingSpinner = document.getElementById('registrationLoadingSpinner');
                const registrationContent = document.getElementById('registrationRequestsContent');
                
                loadingSpinner.style.display = 'block';
                registrationContent.innerHTML = '';
                
                fetch('employee_dashboard.php?get_pending=true')
                    .then(response => response.text())
                    .then(html => {
                        loadingSpinner.style.display = 'none';
                        registrationContent.innerHTML = html;
                    })
                    .catch(error => {
                        loadingSpinner.style.display = 'none';
                        registrationContent.innerHTML = `
                            <div class="emp-dashboard-no-pending">
                                <i class="fas fa-exclamation-triangle"></i>
                                <h5>Error Loading Requests</h5>
                                <p>Unable to load registration requests. Please try again.</p>
                            </div>
                        `;
                    });
            }
            
            // Password Reset Approval Modal Functions - Accessible to DEO and MIS Admin
            function empDashboardOpenPasswordResetApprovalModal() {
                document.getElementById('passwordResetApprovalModal').style.display = 'flex';
                empDashboardLoadPasswordResetRequests();
            }
            
            function empDashboardClosePasswordResetModal() {
                closeModal('passwordResetApprovalModal');
            }
            
            function empDashboardLoadPasswordResetRequests() {
                const loadingSpinner = document.getElementById('passwordResetLoadingSpinner');
                const passwordResetContent = document.getElementById('passwordResetRequestsContent');
                
                loadingSpinner.style.display = 'block';
                passwordResetContent.innerHTML = '';
                
                const timestamp = new Date().getTime();
                
                fetch('employee_dashboard.php?get_password_reset=true&t=' + timestamp)
                    .then(response => response.text())
                    .then(html => {
                        loadingSpinner.style.display = 'none';
                        passwordResetContent.innerHTML = html;
                    })
                    .catch(error => {
                        loadingSpinner.style.display = 'none';
                        passwordResetContent.innerHTML = `
                            <div class="emp-dashboard-no-pending">
                                <i class="fas fa-exclamation-triangle"></i>
                                <h5>Error Loading Requests</h5>
                                <p>Unable to load password reset requests. Please try again.</p>
                            </div>
                        `;
                    });
            }
            
            // Quick Stats Modal Functions - Only accessible to DEO/MIS
            <?php if ($is_deo || $is_mis_admin): ?>
            function openRegisteredEmployeesModal() {
                const modal = document.getElementById('registeredEmployeesModal');
                const content = document.getElementById('registeredEmployeesContent');
                
                content.innerHTML = `
                    <div class="emp-dashboard-loading-spinner" style="display: block;">
                        <div class="emp-dashboard-spinner-border text-primary" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                        <p class="mt-3">Loading registered employees...</p>
                    </div>
                `;
                
                modal.style.display = 'flex';
                
                const timestamp = new Date().getTime();
                fetch('employee_dashboard.php?get_registered_employees=true&t=' + timestamp)
                    .then(response => response.text())
                    .then(html => {
                        content.innerHTML = html;
                    })
                    .catch(error => {
                        console.error('Error loading registered employees:', error);
                        content.innerHTML = `
                            <div class="emp-dashboard-no-pending">
                                <i class="fas fa-exclamation-triangle"></i>
                                <h5>Error Loading Data</h5>
                                <p>Unable to load registered employees. Please try again.</p>
                            </div>
                        `;
                    });
            }
            
            function openCompletedProfilesModal() {
                const modal = document.getElementById('completedProfilesModal');
                const content = document.getElementById('completedProfilesContent');
                
                content.innerHTML = `
                    <div class="emp-dashboard-loading-spinner" style="display: block;">
                        <div class="emp-dashboard-spinner-border text-primary" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                        <p class="mt-3">Loading completed profiles...</p>
                    </div>
                `;
                
                modal.style.display = 'flex';
                
                const timestamp = new Date().getTime();
                fetch('employee_dashboard.php?get_completed_profiles=true&t=' + timestamp)
                    .then(response => response.text())
                    .then(html => {
                        content.innerHTML = html;
                    })
                    .catch(error => {
                        console.error('Error loading completed profiles:', error);
                        content.innerHTML = `
                            <div class="emp-dashboard-no-pending">
                                <i class="fas fa-exclamation-triangle"></i>
                                <h5>Error Loading Data</h5>
                                <p>Unable to load completed profiles. Please try again.</p>
                            </div>
                        `;
                    });
            }
            
            function openPendingProfilesModal() {
                const modal = document.getElementById('pendingProfilesModal');
                const content = document.getElementById('pendingProfilesContent');
                
                content.innerHTML = `
                    <div class="emp-dashboard-loading-spinner" style="display: block;">
                        <div class="emp-dashboard-spinner-border text-primary" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                        <p class="mt-3">Loading pending profiles...</p>
                    </div>
                `;
                
                modal.style.display = 'flex';
                
                const timestamp = new Date().getTime();
                fetch('employee_dashboard.php?get_pending_profiles=true&t=' + timestamp)
                    .then(response => response.text())
                    .then(html => {
                        content.innerHTML = html;
                    })
                    .catch(error => {
                        console.error('Error loading pending profiles:', error);
                        content.innerHTML = `
                            <div class="emp-dashboard-no-pending">
                                <i class="fas fa-exclamation-triangle"></i>
                                <h5>Error Loading Data</h5>
                                <p>Unable to load pending profiles. Please try again.</p>
                            </div>
                        `;
                    });
            }
            
            function closeRegisteredEmployeesModal() {
                closeModal('registeredEmployeesModal');
            }
            
            function closeCompletedProfilesModal() {
                closeModal('completedProfilesModal');
            }
            
            function closePendingProfilesModal() {
                closeModal('pendingProfilesModal');
            }
            
            // Print Functions
            function printRegisteredEmployees() {
                const printWindow = window.open('', '_blank');
                if (!printWindow) {
                    alert('Please allow pop-ups to print the list.');
                    return;
                }
                
                const content = document.getElementById('registeredEmployeesContent');
                if (!content) return;
                
                printWindow.document.write('<html><head><title>Registered Employees - AJ&K Education Department District Kotli</title>');
                printWindow.document.write('<style>');
                printWindow.document.write(`
                    body { font-family: Arial, sans-serif; margin: 20px; color: #333; }
                    .print-header { text-align: center; margin-bottom: 30px; }
                    .print-header h3 { color: #1a3e72; margin-bottom: 5px; font-size: 24px; }
                    .print-header h4 { color: #2a5ca0; margin-bottom: 10px; font-size: 18px; }
                    .print-header p { color: #666; margin: 5px 0; }
                    .print-header hr { border: 1px solid #ddd; margin: 15px 0; }
                    table { width: 100%; border-collapse: collapse; margin-top: 20px; font-size: 14px; }
                    th { background-color: #1a3e72; color: white; padding: 12px 10px; text-align: left; font-weight: 600; }
                    td { padding: 10px; border-bottom: 1px solid #ddd; }
                    .badge { padding: 3px 8px; border-radius: 12px; font-size: 12px; display: inline-block; }
                    .bg-success { background-color: #d1e7dd; color: #0f5132; }
                    .bg-warning { background-color: #fff3cd; color: #856404; }
                    .bg-info { background-color: #cfe2ff; color: #084298; }
                    .emp-dashboard-cnic-display { font-family: 'Courier New', monospace; }
                `);
                printWindow.document.write('</style></head><body>');
                
                printWindow.document.write('<div class="print-header">');
                printWindow.document.write('<h3>AJ&K Education Department District Kotli</h3>');
                printWindow.document.write('<h4>Registered Employees List</h4>');
                printWindow.document.write('<p>Generated on: <?php echo date("F j, Y, g:i a"); ?></p>');
                printWindow.document.write('<p>Total Employees: <?php echo count($all_employees ?? []); ?></p>');
                printWindow.document.write('<hr>');
                printWindow.document.write('</div>');
                
                const table = content.querySelector('table');
                if (table) {
                    printWindow.document.write(table.outerHTML);
                } else {
                    printWindow.document.write('<p class="text-center text-muted">No data available</p>');
                }
                
                printWindow.document.write('</body></html>');
                printWindow.document.close();
                
                setTimeout(() => {
                    printWindow.focus();
                    printWindow.print();
                    printWindow.onafterprint = function() {
                        printWindow.close();
                    };
                }, 500);
            }
            
            function printCompletedProfiles() {
                const printWindow = window.open('', '_blank');
                if (!printWindow) {
                    alert('Please allow pop-ups to print the list.');
                    return;
                }
                
                const content = document.getElementById('completedProfilesContent');
                if (!content) return;
                
                printWindow.document.write('<html><head><title>Completed Profiles - AJ&K Education Department District Kotli</title>');
                printWindow.document.write('<style>');
                printWindow.document.write(`
                    body { font-family: Arial, sans-serif; margin: 20px; color: #333; }
                    .print-header { text-align: center; margin-bottom: 30px; }
                    .print-header h3 { color: #1a3e72; margin-bottom: 5px; font-size: 24px; }
                    .print-header h4 { color: #28a745; margin-bottom: 10px; font-size: 18px; }
                    .print-header p { color: #666; margin: 5px 0; }
                    .print-header hr { border: 1px solid #ddd; margin: 15px 0; }
                    table { width: 100%; border-collapse: collapse; margin-top: 20px; font-size: 14px; }
                    th { background-color: #28a745; color: white; padding: 12px 10px; }
                    td { padding: 10px; border-bottom: 1px solid #ddd; }
                    .badge { padding: 3px 8px; border-radius: 12px; font-size: 12px; display: inline-block; }
                    .bg-info { background-color: #cfe2ff; color: #084298; }
                    .emp-dashboard-cnic-display { font-family: 'Courier New', monospace; }
                `);
                printWindow.document.write('</style></head><body>');
                
                printWindow.document.write('<div class="print-header">');
                printWindow.document.write('<h3>AJ&K Education Department District Kotli</h3>');
                printWindow.document.write('<h4>Completed Profiles List</h4>');
                printWindow.document.write('<p>Generated on: <?php echo date("F j, Y, g:i a"); ?></p>');
                printWindow.document.write('<p>Total Completed Profiles: <?php echo count($all_completed_profiles ?? []); ?></p>');
                printWindow.document.write('<hr>');
                printWindow.document.write('</div>');
                
                const table = content.querySelector('table');
                if (table) printWindow.document.write(table.outerHTML);
                
                printWindow.document.write('</body></html>');
                printWindow.document.close();
                setTimeout(() => { printWindow.focus(); printWindow.print(); printWindow.close(); }, 500);
            }
            
            function printPendingProfiles() {
                const printWindow = window.open('', '_blank');
                if (!printWindow) {
                    alert('Please allow pop-ups to print the list.');
                    return;
                }
                
                const content = document.getElementById('pendingProfilesContent');
                if (!content) return;
                
                printWindow.document.write('<html><head><title>Pending Profiles - AJ&K Education Department District Kotli</title>');
                printWindow.document.write('<style>');
                printWindow.document.write(`
                    body { font-family: Arial, sans-serif; margin: 20px; color: #333; }
                    .print-header { text-align: center; margin-bottom: 30px; }
                    .print-header h3 { color: #1a3e72; margin-bottom: 5px; font-size: 24px; }
                    .print-header h4 { color: #ffc107; margin-bottom: 10px; font-size: 18px; }
                    .print-header p { color: #666; margin: 5px 0; }
                    .print-header hr { border: 1px solid #ddd; margin: 15px 0; }
                    table { width: 100%; border-collapse: collapse; margin-top: 20px; font-size: 14px; }
                    th { background-color: #ffc107; color: #212529; padding: 12px 10px; }
                    td { padding: 10px; border-bottom: 1px solid #ddd; }
                    .badge { padding: 3px 8px; border-radius: 12px; font-size: 12px; display: inline-block; }
                    .bg-info { background-color: #cfe2ff; color: #084298; }
                    .emp-dashboard-cnic-display { font-family: 'Courier New', monospace; }
                `);
                printWindow.document.write('</style></head><body>');
                
                printWindow.document.write('<div class="print-header">');
                printWindow.document.write('<h3>AJ&K Education Department District Kotli</h3>');
                printWindow.document.write('<h4>Pending Profiles List</h4>');
                printWindow.document.write('<p>Generated on: <?php echo date("F j, Y, g:i a"); ?></p>');
                printWindow.document.write('<p>Total Pending Profiles: <?php echo count($all_pending_profiles ?? []); ?></p>');
                printWindow.document.write('<hr>');
                printWindow.document.write('</div>');
                
                const table = content.querySelector('table');
                if (table) printWindow.document.write(table.outerHTML);
                
                printWindow.document.write('</body></html>');
                printWindow.document.close();
                setTimeout(() => { printWindow.focus(); printWindow.print(); printWindow.close(); }, 500);
            }
            <?php else: ?>
            // Empty functions for non-DEO/non-MIS users
            function openRegisteredEmployeesModal() { alert('You do not have permission to view this data.'); }
            function openCompletedProfilesModal() { alert('You do not have permission to view this data.'); }
            function openPendingProfilesModal() { alert('You do not have permission to view this data.'); }
            function printRegisteredEmployees() { alert('You do not have permission to print this data.'); }
            function printCompletedProfiles() { alert('You do not have permission to print this data.'); }
            function printPendingProfiles() { alert('You do not have permission to print this data.'); }
            <?php endif; ?>
            
            // Registration approval functions - Accessible to DEO and MIS Admin
            function empDashboardApproveRegistration(registrationId) {
                if (!confirm('Are you sure you want to approve this registration? An email notification will be sent to the employee.')) {
                    return;
                }
                
                const formData = new FormData();
                formData.append('action', 'process_approval');
                formData.append('registration_id', registrationId);
                formData.append('action_type', 'approve');
                
                fetch('employee_dashboard.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        if (data.email_sent) {
                            alert('✓ ' + data.message + '\n\n✓ Email notification sent successfully.');
                        } else {
                            alert('✓ ' + data.message);
                        }
                        empDashboardLoadRegistrationRequests();
                    } else {
                        alert('Error: ' + data.message);
                    }
                })
                .catch(error => {
                    alert('Error processing approval. Please try again.');
                });
            }
            
            function empDashboardRejectRegistration(registrationId) {
                if (!confirm('Are you sure you want to reject and delete this registration? This action cannot be undone.')) {
                    return;
                }
                
                const formData = new FormData();
                formData.append('action', 'process_approval');
                formData.append('registration_id', registrationId);
                formData.append('action_type', 'reject');
                
                fetch('employee_dashboard.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert(data.message);
                        empDashboardLoadRegistrationRequests();
                    } else {
                        alert('Error: ' + data.message);
                    }
                })
                .catch(error => {
                    alert('Error processing rejection. Please try again.');
                });
            }
            
            // Password reset approval functions - Accessible to DEO and MIS Admin
            function empDashboardApprovePasswordReset(requestId) {
                if (!confirm('Are you sure you want to approve this password reset? The password will be updated, the user will be APPROVED, and an email with the new password will be sent to the employee.')) {
                    return;
                }
                
                const formData = new FormData();
                formData.append('password_action', 'process_password_reset');
                formData.append('request_id', requestId);
                formData.append('action_type', 'approve_reset');
                
                fetch('employee_dashboard.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        if (data.email_sent) {
                            alert('✓ ' + data.message + '\n\n✓ Email with new password sent successfully.');
                        } else {
                            alert('✓ ' + data.message + '\n\n⚠ Note: Please inform the employee of their new password manually.');
                        }
                        empDashboardLoadPasswordResetRequests();
                    } else {
                        alert('Error: ' + data.message);
                    }
                })
                .catch(error => {
                    alert('Error processing request. Please try again.');
                });
            }
            
            function empDashboardRejectPasswordReset(requestId) {
                if (!confirm('Are you sure you want to reject this password reset request? This will DELETE the entire employee record from the system. This action cannot be undone.')) {
                    return;
                }
                
                const formData = new FormData();
                formData.append('password_action', 'process_password_reset');
                formData.append('request_id', requestId);
                formData.append('action_type', 'reject_reset');
                
                fetch('employee_dashboard.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert(data.message);
                        empDashboardLoadPasswordResetRequests();
                    } else {
                        alert('Error: ' + data.message);
                    }
                })
                .catch(error => {
                    alert('Error processing request. Please try again.');
                });
            }
            
            function refreshDashboard() {
                location.reload();
            }
            
            // Password toggle function
            window.togglePassword = function(inputId) {
                const input = document.getElementById(inputId);
                const button = input.parentElement.querySelector('.password-toggle-btn');
                const icon = button.querySelector('i');
                
                if (input.type === 'password') {
                    input.type = 'text';
                    icon.classList.remove('fa-eye');
                    icon.classList.add('fa-eye-slash');
                } else {
                    input.type = 'password';
                    icon.classList.remove('fa-eye-slash');
                    icon.classList.add('fa-eye');
                }
            };
            
            // Prevent interaction with background when profile modal is shown
            <?php if (!$profile_exists): ?>
            document.addEventListener('DOMContentLoaded', function() {
                document.addEventListener('click', function(e) {
                    if (!e.target.closest('.profile-modal-backdrop') && !e.target.closest('.profile-modal')) {
                        e.preventDefault();
                        e.stopPropagation();
                    }
                }, true);
                
                document.addEventListener('keydown', function(e) {
                    if (e.key === 'Tab' || e.key === 'Escape') {
                        e.preventDefault();
                        e.stopPropagation();
                    }
                });
            });
            <?php endif; ?>
            
            // Make functions available globally
            window.empDashboardRedirectToProfile = empDashboardRedirectToProfile;
            window.empDashboardOpenRegistrationApprovalModal = empDashboardOpenRegistrationApprovalModal;
            window.empDashboardOpenPasswordResetApprovalModal = empDashboardOpenPasswordResetApprovalModal;
            window.empDashboardApproveRegistration = empDashboardApproveRegistration;
            window.empDashboardRejectRegistration = empDashboardRejectRegistration;
            window.empDashboardApprovePasswordReset = empDashboardApprovePasswordReset;
            window.empDashboardRejectPasswordReset = empDashboardRejectPasswordReset;
            window.refreshDashboard = refreshDashboard;
            
            <?php if ($is_deo || $is_mis_admin): ?>
            window.openRegisteredEmployeesModal = openRegisteredEmployeesModal;
            window.openCompletedProfilesModal = openCompletedProfilesModal;
            window.openPendingProfilesModal = openPendingProfilesModal;
            window.printRegisteredEmployees = printRegisteredEmployees;
            window.printCompletedProfiles = printCompletedProfiles;
            window.printPendingProfiles = printPendingProfiles;
            window.closeRegisteredEmployeesModal = closeRegisteredEmployeesModal;
            window.closeCompletedProfilesModal = closeCompletedProfilesModal;
            window.closePendingProfilesModal = closePendingProfilesModal;
            <?php endif; ?>
        })();
    </script>
</body>
</html>