<?php
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 - 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;
}

// 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'];
    }
}

// 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);

// 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);
$has_student_access = ($is_secretary || $is_deo || $is_ddeo || $is_aeo || $is_mis_admin);
$has_reports_access = ($is_secretary || $is_deo || $is_mis_admin);
$has_announcements_access = ($is_secretary || $is_deo || $is_principal || $is_mis_admin);
$has_teacher_portal_access = $is_teacher;

// Check for pending registration approvals
$pending_count = 0;
$pending_registrations = [];
if ($is_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_count = 0;
$password_reset_requests = [];

if ($is_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';
    
    $email_body = "
Dear $full_name,

We are pleased to inform you that your registration with AJ&K Education Department 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 DSIS System.
";

    $headers = [];
    $headers[] = "From: AJ&K Education Department <$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';
    
    $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 DSIS System.
";

    $headers = [];
    $headers[] = "From: AJ&K Education Department <$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 - ONLY FOR MIS ADMIN
if (isset($_POST['action']) && $is_mis_admin) {
    $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
if (isset($_POST['password_action']) && $is_mis_admin) {
    $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
if (isset($_GET['get_pending']) && $_GET['get_pending'] == 'true') {
    if ($is_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
if (isset($_GET['get_password_reset']) && $_GET['get_password_reset'] == 'true') {
    if ($is_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();
}

// 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 - 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 Specific Styles - Isolated with specific IDs/classes */
        :root {
            --education-blue: #1a3e72;
            --education-light: #e9f0f7;
        }
        
        body.emp-dashboard-body {
            background-color: #f5f5f5;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            overflow: <?php echo !$profile_exists ? 'hidden' : 'auto'; ?>;
        }
        
        /* Sidebar matching navbar color */
        .emp-dashboard-sidebar {
            background-color: var(--education-blue) !important;
            color: white;
            min-height: calc(100vh - 56px);
            box-shadow: 2px 0 5px rgba(0,0,0,0.1);
        }
        
        .emp-dashboard-sidebar .nav-link {
            color: rgba(255,255,255,0.8);
            border-left: 3px solid transparent;
            padding: 10px 15px;
            margin-bottom: 2px;
        }
        
        .emp-dashboard-sidebar .nav-link:hover, 
        .emp-dashboard-sidebar .nav-link.active {
            color: white;
            background-color: rgba(255,255,255,0.1);
            border-left: 3px solid #ffc107;
        }
        
        .emp-dashboard-sidebar .nav-link i {
            margin-right: 10px;
            width: 20px;
            text-align: center;
        }
        
        /* Profile Modal Styles from second code */
        .profile-modal-backdrop {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.85);
            z-index: 1040;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
            box-sizing: border-box;
        }
        
        .profile-modal {
            background: white;
            border-radius: 20px;
            box-shadow: 0 25px 80px rgba(0,0,0,0.4);
            width: 90%;
            max-width: 600px;
            max-height: 100vh;
            overflow-y: auto;
            z-index: 1050;
            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: 20px 20px 0 0;
            padding: 1.5rem 2rem;
            text-align: center;
            position: relative;
            flex-shrink: 0;
        }
        
        .profile-modal-header h3 {
            margin: 0;
            font-weight: 600;
            font-size: 1.5rem;
        }
        
        .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(-8px);
            }
            60% {
                transform: translateY(-4px);
            }
        }
        
        .profile-modal-title {
            font-size: 1.6rem;
            font-weight: 700;
            color: var(--education-blue);
            margin-bottom: 1rem;
            line-height: 1.3;
        }
        
        .profile-modal-text {
            font-size: 1.05rem;
            color: #555;
            margin-bottom: 1.5rem;
            line-height: 1.6;
        }
        
        .profile-alert {
            background: linear-gradient(135deg, #fff3cd, #ffeaa7);
            border: 2px solid #ffc107;
            border-radius: 12px;
            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: 600;
            border-radius: 12px;
            background: linear-gradient(135deg, var(--education-blue), #2a5ca0);
            border: none;
            color: white;
            transition: all 0.3s ease;
            box-shadow: 0 6px 20px rgba(26, 62, 114, 0.4);
            margin-bottom: 1rem;
            min-height: 60px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
        }
        
        .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: #6c757d;
            font-size: 0.9rem;
            margin-top: 0.5rem;
        }
        
        /* Registration Approval Modal Styles - Dashboard Specific */
        #registrationApprovalModal.emp-dashboard-modal,
        #passwordResetApprovalModal.emp-dashboard-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.7);
            z-index: 1050;
            display: none;
            justify-content: center;
            align-items: center;
            padding: 20px;
            box-sizing: border-box;
        }
        
        #registrationApprovalModal .emp-dashboard-modal-content,
        #passwordResetApprovalModal .emp-dashboard-modal-content {
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            width: 95%;
            max-width: 1200px;
            max-height: 90vh;
            overflow-y: auto;
            z-index: 1060;
            position: relative;
            animation: empDashboardModalAppear 0.3s ease-out;
        }
        
        @keyframes empDashboardModalAppear {
            0% {
                opacity: 0;
                transform: scale(0.9) translateY(-30px);
            }
            100% {
                opacity: 1;
                transform: scale(1) translateY(0);
            }
        }
        
        #registrationApprovalModal .emp-dashboard-modal-header,
        #passwordResetApprovalModal .emp-dashboard-modal-header {
            background: linear-gradient(135deg, var(--education-blue), #2a5ca0);
            color: white;
            border-radius: 15px 15px 0 0;
            padding: 1.5rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: sticky;
            top: 0;
            z-index: 10;
        }
        
        #registrationApprovalModal .close-emp-dashboard-modal,
        #passwordResetApprovalModal .close-emp-dashboard-modal {
            background: none;
            border: none;
            color: white;
            font-size: 1.5rem;
            cursor: pointer;
            padding: 0;
            line-height: 1;
        }
        
        #registrationApprovalModal .emp-dashboard-modal-body,
        #passwordResetApprovalModal .emp-dashboard-modal-body {
            padding: 1.5rem;
            max-height: calc(90vh - 120px);
            overflow-y: auto;
        }
        
        /* Table Styles - Dashboard Specific */
        .emp-dashboard-table.approval-table {
            width: 100%;
            margin-bottom: 0;
            border-collapse: separate;
            border-spacing: 0;
        }
        
        .emp-dashboard-table.approval-table th {
            background-color: var(--education-blue);
            color: white;
            font-weight: 600;
            padding: 12px 15px;
            position: sticky;
            top: 0;
            z-index: 5;
            border: none;
            white-space: nowrap; /* Prevent line breaks in headers */
        }
        
        .emp-dashboard-table.approval-table td {
            padding: 12px 15px;
            vertical-align: middle;
            border-bottom: 1px solid #dee2e6;
            word-wrap: break-word;
            max-width: 200px; /* Prevent too wide columns */
        }
        
        /* Fix for password reset modal - ensure single line display */
        .emp-dashboard-table.approval-table tbody tr td {
            white-space: nowrap; /* Keep content on single line */
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        /* Allow role badges to show fully */
        .emp-dashboard-table.approval-table tbody tr td .emp-dashboard-role-badge {
            white-space: nowrap;
            display: inline-block;
        }
        
        .emp-dashboard-table.approval-table tbody tr {
            transition: all 0.2s ease;
        }
        
        .emp-dashboard-table.approval-table tbody tr:hover {
            background-color: rgba(26, 62, 114, 0.05);
        }
        
        /* Action Buttons - Dashboard Specific */
        .emp-dashboard-action-buttons {
            display: flex;
            gap: 8px;
            flex-wrap: nowrap;
            min-width: 180px; /* Ensure buttons stay together */
        }
        
        .emp-dashboard-btn-action {
            padding: 5px 12px;
            font-size: 0.85rem;
            border-radius: 4px;
            display: inline-flex;
            align-items: center;
            gap: 5px;
            white-space: nowrap;
            border: none;
            cursor: pointer;
            flex-shrink: 0; /* Prevent buttons from shrinking */
        }
        
        /* No Pending Styles */
        .emp-dashboard-no-pending {
            text-align: center;
            padding: 3rem;
            color: #6c757d;
        }
        
        .emp-dashboard-no-pending i {
            font-size: 3rem;
            margin-bottom: 1rem;
            color: #adb5bd;
        }
        
        /* Loading Spinner */
        .emp-dashboard-loading-spinner {
            display: none;
            text-align: center;
            padding: 2rem;
        }
        
        .emp-dashboard-spinner-border {
            width: 3rem;
            height: 3rem;
        }
        
        /* Badge Styles */
        .emp-dashboard-pending-count-badge {
            animation: none !important;
        }
        
        .emp-dashboard-warning-badge-pulse {
            animation: none !important;
        }
        
        /* Role Badge */
        .emp-dashboard-role-badge {
            padding: 4px 10px;
            border-radius: 12px;
            font-size: 0.8rem;
            font-weight: 500;
            display: inline-block;
        }
        
        /* CNIC Display */
        .emp-dashboard-cnic-display {
            font-family: 'Courier New', monospace;
            font-size: 0.9rem;
            white-space: nowrap;
        }
        
        /* Approval Buttons - Dashboard Specific */
        .emp-dashboard-approval-button {
            background: linear-gradient(135deg, var(--education-blue), #2a5ca0);
            border: 1px solid rgba(255, 255, 255, 0.3);
            border-radius: 5px;
            margin-right: 10px;
            transition: all 0.3s ease;
            cursor: pointer;
            position: relative;
            padding: 5px 15px;
            color: white;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            white-space: nowrap;
        }
        
        .emp-dashboard-approval-button:hover {
            background: linear-gradient(135deg, #2a5ca0, var(--education-blue));
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
            color: white;
        }
        
        /* Alert Cards - Dashboard Specific */
        .emp-dashboard-alert-card {
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            transition: transform 0.3s;
            border: none;
            margin-bottom: 20px;
            height: 100%;
        }
        
        .emp-dashboard-alert-card:hover {
            transform: translateY(-5px);
        }
        
        /* Scrollbar Styling - Dashboard Specific */
        #registrationApprovalModal .emp-dashboard-modal-body::-webkit-scrollbar,
        #passwordResetApprovalModal .emp-dashboard-modal-body::-webkit-scrollbar {
            width: 8px;
        }
        
        #registrationApprovalModal .emp-dashboard-modal-body::-webkit-scrollbar-track,
        #passwordResetApprovalModal .emp-dashboard-modal-body::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 4px;
        }
        
        #registrationApprovalModal .emp-dashboard-modal-body::-webkit-scrollbar-thumb,
        #passwordResetApprovalModal .emp-dashboard-modal-body::-webkit-scrollbar-thumb {
            background: var(--education-blue);
            border-radius: 4px;
        }
        
        #registrationApprovalModal .emp-dashboard-modal-body::-webkit-scrollbar-thumb:hover,
        #passwordResetApprovalModal .emp-dashboard-modal-body::-webkit-scrollbar-thumb:hover {
            background: #2a5ca0;
        }
        
        /* Responsive Design - Dashboard Specific */
        @media (max-width: 768px) {
            /* Profile Modal Responsive */
            .profile-modal-backdrop {
                padding: 15px;
            }
            
            .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;
            }
            
            .profile-alert {
                padding: 1rem 1.2rem;
            }
            
            /* Other Modals */
            #registrationApprovalModal.emp-dashboard-modal,
            #passwordResetApprovalModal.emp-dashboard-modal {
                padding: 10px;

            }
            
            #registrationApprovalModal .emp-dashboard-modal-content,
            #passwordResetApprovalModal .emp-dashboard-modal-content {
                width: 98%;
                max-height: 85vh;
            }
            
            .emp-dashboard-table.approval-table {
                display: block;
                overflow-x: auto;
                white-space: nowrap;
            }
            
            .emp-dashboard-table.approval-table th,
            .emp-dashboard-table.approval-table td {
                white-space: nowrap;
            }
            
            .emp-dashboard-action-buttons {
                flex-direction: column;
                gap: 5px;
                min-width: 140px;
            }
            
            .emp-dashboard-btn-action {
                padding: 4px 8px;
                font-size: 0.8rem;
                width: 100%;
                justify-content: center;
            }
            
            .emp-dashboard-approval-button {
                margin: 5px;
                width: calc(100% - 10px);
            }
            
            .emp-dashboard-sidebar {
                min-height: auto;
            }
        }
        
        @media (max-width: 480px) {
            /* Profile Modal */
            .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;
                margin-bottom: 1rem;
            }
            
            .profile-btn {
                padding: 0.8rem 1.5rem;
                font-size: 0.95rem;
                min-height: 50px;
            }
            
            .profile-alert {
                padding: 0.8rem 1rem;
                margin-bottom: 1.5rem;
            }
            
            /* Other Modals */
            #registrationApprovalModal .emp-dashboard-modal-header h3,
            #passwordResetApprovalModal .emp-dashboard-modal-header h3 {
                font-size: 1.2rem;
            }
            
            .emp-dashboard-no-pending {
                padding: 2rem 1rem;
            }
            
            .emp-dashboard-no-pending h5 {
                font-size: 1.1rem;
            }
            
            .emp-dashboard-table.approval-table td {
                padding: 8px 10px;
                font-size: 0.9rem;
            }
        }
        
        /* Prevent conflicts with other pages */
        .emp-dashboard-specific {
            /* All dashboard-specific styles are prefixed */
        }
        
        /* Main content area */
        .emp-dashboard-main-content {
            min-height: calc(100vh - 56px - 73px); /* Subtract navbar and footer height */
        }
		
		 /* Password Modal Styles - Improved */
      #changePasswordModal .modal-content {
      border-radius: 15px;
      overflow: hidden;
      border: none;
      box-shadow: 0 10px 40px rgba(0,0,0,0.2);
      }
      #changePasswordModal .modal-header {
      background: linear-gradient(135deg, var(--education-blue), #2a5ca0);
      color: white;
      border-bottom: none;
      padding: 1.5rem 2rem;
      }
      #changePasswordModal .modal-body {
      padding: 2rem;
      }
      /* Password input field styling */
      .password-input-wrapper {
      position: relative;
      margin-bottom: 1.5rem;
      }
      .password-input-wrapper .form-control {
      border-radius: 8px;
      padding: 12px 50px 12px 15px;
      border: 1px solid #ddd;
      transition: all 0.3s;
      line-height: 1.5;
      height: 48px;
      width: 100%;
      box-sizing: border-box;
      }
      .password-input-wrapper .form-control:focus {
      border-color: var(--education-blue);
      box-shadow: 0 0 0 0.2rem rgba(26, 62, 114, 0.25);
      outline: none;
      }
      /* Password toggle button styling - FIXED VERTICAL CENTERING */
      .password-toggle-btn {
      position: absolute;
      right: 12px;
      top: 50%;
      transform: translateY(-50%);
      height: 100%;
      display: flex;
      align-items: center;
      background: transparent;
      border: none;
      padding: 0;
      cursor: pointer;
      }
      /* Adjust label position */
      .password-input-wrapper .form-label {
      display: block;
      margin-bottom: 8px;
      font-weight: 500;
      }
      /* Hover and active states */
      .password-toggle-btn:hover {
      color: var(--education-blue);
      background-color: rgba(26, 62, 114, 0.1);
      }
      .password-toggle-btn:active {
      transform: translateY(-50%) scale(0.95);
      }
      .password-toggle-btn i {
      font-size: 1rem;
      line-height: 1;
      }
      /* Button styling */
      #changePasswordModal .btn-primary {
      background: linear-gradient(135deg, var(--education-blue), #2a5ca0);
      border: none;
      padding: 10px 25px;
      border-radius: 8px;
      font-weight: 600;
      transition: all 0.3s;
      height: 48px;
      }
      #changePasswordModal .btn-primary:hover {
      transform: translateY(-2px);
      box-shadow: 0 5px 15px rgba(26, 62, 114, 0.3);
      }
      #changePasswordModal .btn-secondary {
      padding: 10px 25px;
      border-radius: 8px;
      font-weight: 600;
      height: 48px;
      }
      .form-text {
      margin-top: 4px;
      font-size: 0.85rem;
      color: #6c757d;
      padding-left: 2px;
      }
      /* Ensure the info alert stays visible */
      #changePasswordModal .alert-info {
      margin-top: 1.5rem;
      margin-bottom: 1.5rem;
      border-radius: 8px;
      border: 1px solid #bee5eb;
      background-color: #d1ecf1;
      }
      #changePasswordModal .alert {
      border-radius: 8px;
      padding: 12px 16px;
      margin-bottom: 1rem;
      }
      #changePasswordModal .alert .btn-close {
      padding: 0.75rem;
      }
      /* Password strength validation styles */
      .password-strength {
      margin-top: 10px;
      padding: 10px;
      background-color: #f8f9fa;
      border-radius: 6px;
      border-left: 4px solid #ddd;
      }
      .password-strength .form-text {
      margin-top: 5px;
      line-height: 1.4;
      }
      .password-strength span {
      transition: color 0.3s ease;
      display: inline-block;
      margin-bottom: 2px;
      }
      .password-strength .text-success {
      font-weight: 500;
      }
      .password-strength .text-success:before {
      content: "✓ ";
      }
      .password-strength .text-danger:before {
      content: "✗ ";
      }
      #password-match {
      margin-top: 5px;
      font-weight: 500;
      padding-left: 5px;
      }
      #password-match i {
      margin-right: 5px;
      }
	  
    </style>
</head>
<body class="emp-dashboard-body">
    <!-- Profile Completion Modal - Updated from second code -->
    <?php if (!$profile_exists): ?>
<div class="profile-modal-backdrop">
    <div class="profile-modal pulse-effect">
        
        <!-- Header - Icon and Text in Single Row -->
<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>

        <!-- Body -->
        <div class="profile-modal-body">

            <!-- Main Icon -->
            <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</strong>.  
                To continue using the system without restrictions, your employee profile must be completed.
            </p>

            <!-- Alert -->
            <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>

            <!-- Action Button -->
            <button type="button" class="btn profile-btn" onclick="empDashboardRedirectToProfile()">
                <i class="fas fa-user-edit me-2"></i>
                Complete My Profile
            </button>

            <!-- Time Note -->
            <div class="time-indicator">
                <i class="fas fa-clock"></i>
                Profile completion takes only 2–3 minutes
            </div>

            <!-- Security Note -->
            <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 -->
    <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">
                <!-- Loading spinner -->
                <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>
                
                <!-- Content will be loaded here -->
                <div id="registrationRequestsContent"></div>
            </div>
        </div>
    </div>

    <!-- Password Reset Approval Modal -->
    <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">
                <!-- Loading spinner -->
                <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>
                
                <!-- Content will be loaded here -->
                <div id="passwordResetRequestsContent"></div>
            </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" 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>
            
            <!-- Mobile View Toggle Button -->
            <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">
                <!-- Separate Approval Buttons - Desktop View -->
                <?php if ($is_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; ?>
                
                <!-- User Profile Dropdown -->
                <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>
                            <!-- FIXED: Change Password link now opens modal -->
                            <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 ($is_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">
                    <!-- Sidebar Profile Section -->
                    <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>
                        
                        <!-- HR Management -->
                        <?php if ($has_hr_access): ?>
                        <li class="nav-item">
                            <a class="nav-link" href="hr_management.php">
                                <i class="fas fa-user-tie"></i> HR Management
                            </a>
                        </li>
                        <?php endif; ?>
                        
                        <!-- School Management -->
                        <?php if ($has_school_access): ?>
                        <li class="nav-item">
                            <a class="nav-link" href="school_management.php">
                                <i class="fas fa-school"></i> School Management
                            </a>
                        </li>
                        <?php endif; ?>
                        
                        <!-- Student Management -->
                        <?php if ($has_student_access): ?>
                        <li class="nav-item">
                            <a class="nav-link" href="student_management.php">
                                <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="finance_management.php">
                                <i class="fas fa-money-bill-wave"></i> Finance
                            </a>
                        </li>
                        <?php endif; ?>
                        
                        <!-- Teacher Portal -->
                        <?php if ($has_teacher_portal_access): ?>
                        <li class="nav-item">
                            <a class="nav-link" href="teacher_portal.php">
                                <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="reports.php">
                                <i class="fas fa-chart-bar"></i> Reports
                            </a>
                        </li>
                        <?php endif; ?>
                        
                        <!-- Documents accessible to all -->
                        <li class="nav-item">
                            <a class="nav-link" href="documents.php">
                                <i class="fas fa-file-alt"></i> Documents
                            </a>
                        </li>
                        
                        <?php if ($has_announcements_access): ?>
                        <li class="nav-item">
                            <a class="nav-link" href="announcements.php">
                                <i class="fas fa-bullhorn"></i> Announcements
                            </a>
                        </li>
                        <?php endif; ?>
                        
                        <?php if ($is_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">
                <!-- 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; ?>
                
                <!-- Separate Pending Requests Alerts -->
                <?php if ($pending_count > 0 && $is_mis_admin): ?>
                <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 && $is_mis_admin): ?>
                <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 Actions -->
                <h4 class="mb-3">Quick Actions</h4>
                <div class="row">
                    <!-- HR Management Card -->
                    <?php if ($has_hr_access): ?>
                    <div class="col-md-4 mb-3">
                        <div class="card emp-dashboard-alert-card">
                            <div class="card-body text-center">
                                <i class="fas fa-user-tie card-icon text-warning" style="font-size: 2rem;"></i>
                                <h5 class="card-title">HR Management</h5>
                                <p class="card-text">Manage employee records and HR processes</p>
                                <a href="hr_management.php" class="btn btn-warning btn-sm">Go to Module</a>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <!-- School Management Card -->
                    <?php if ($has_school_access): ?>
                    <div class="col-md-4 mb-3">
                        <div class="card emp-dashboard-alert-card">
                            <div class="card-body text-center">
                                <i class="fas fa-school card-icon text-success" style="font-size: 2rem;"></i>
                                <h5 class="card-title">School Management</h5>
                                <p class="card-text">Manage school information and resources</p>
                                <a href="school_management.php" class="btn btn-success btn-sm">Go to Module</a>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Student Management Card -->
                    <?php if ($has_student_access): ?>
                    <div class="col-md-4 mb-3">
                        <div class="card emp-dashboard-alert-card">
                            <div class="card-body text-center">
                                <i class="fas fa-users card-icon text-primary" style="font-size: 2rem;"></i>
                                <h5 class="card-title">Student Management</h5>
                                <p class="card-text">Manage student records and information</p>
                                <a href="student_management.php" class="btn btn-primary btn-sm">Go to Module</a>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Separate Approval Cards -->
                    <?php if ($is_mis_admin): ?>
                    <div class="col-md-4 mb-3">
                        <div class="card emp-dashboard-alert-card">
                            <div class="card-body text-center">
                                <i class="fas fa-user-check card-icon" style="color: #dc3545; font-size: 2rem;"></i>
                                <h5 class="card-title">Registration Approvals</h5>
                                <p class="card-text">Review and approve new employee registrations</p>
                                <?php if ($pending_count > 0): ?>
                                    <div class="mb-2">
                                        <span class="badge bg-danger emp-dashboard-pending-count-badge"><?php echo $pending_count; ?> Pending</span>
                                    </div>
                                <?php endif; ?>
                                <button class="btn btn-danger btn-sm" onclick="empDashboardOpenRegistrationApprovalModal()">Review Now</button>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-4 mb-3">
                        <div class="card emp-dashboard-alert-card">
                            <div class="card-body text-center">
                                <i class="fas fa-key card-icon" style="color: #ffc107; font-size: 2rem;"></i>
                                <h5 class="card-title">Password Reset Requests</h5>
                                <p class="card-text">Approve or reject password reset requests</p>
                                <?php if ($password_reset_count > 0): ?>
                                    <div class="mb-2">
                                        <span class="badge bg-warning emp-dashboard-warning-badge-pulse"><?php echo $password_reset_count; ?> Pending</span>
                                    </div>
                                <?php endif; ?>
                                <button class="btn btn-warning btn-sm" onclick="empDashboardOpenPasswordResetApprovalModal()">Review Now</button>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>

                <!-- Recent Activities -->
                <div class="mt-5">
                    <h4>Recent Activities</h4>
                    <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 && $is_mis_admin): ?>
                                        <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 && $is_mis_admin): ?>
                                        <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 &copy; <?php echo date('Y'); ?></span>
                </div>
                <div class="col-md-6 text-md-end">
                    <span class="text-muted">Version 1.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 
              // Display success/error messages from session
              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>
// Prevent browser password save prompt
(function() {
    const modal = document.getElementById('changePasswordModal');
    const form = document.getElementById('changePasswordForm');
    
    if (!modal || !form) return;
    
    // Flag to track if we should save
    let shouldSavePassword = false;
    
    // When user submits the form
    form.addEventListener('submit', function() {
        shouldSavePassword = true;
    });
    
    // When modal starts hiding
    modal.addEventListener('hide.bs.modal', function() {
        if (!shouldSavePassword) {
            // Clear all password fields
            const inputs = form.querySelectorAll('input[type="password"], input[type="text"]');
            inputs.forEach(input => {
                // Temporarily disable autocomplete
                input.setAttribute('autocomplete', 'off');
                input.value = '';
                
                // Reset to password type if needed
                if (input.type === 'text' && 
                    ['current_password', 'new_password', 'confirm_password'].includes(input.id)) {
                    input.type = 'password';
                    const toggleBtn = input.parentElement.querySelector('.password-toggle-btn i');
                    if (toggleBtn) {
                        toggleBtn.className = 'fas fa-eye';
                    }
                }
            });
        }
        shouldSavePassword = false;
    });
    
    // Reset when modal fully closes
    modal.addEventListener('hidden.bs.modal', function() {
        form.reset();
        // Restore proper autocomplete attributes
        document.getElementById('current_password').setAttribute('autocomplete', 'current-password');
        document.getElementById('new_password').setAttribute('autocomplete', 'new-password');
        document.getElementById('confirm_password').setAttribute('autocomplete', 'new-password');
    });
})();
</script>
    <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';
            }
            
            // Handle broken profile images
            function empDashboardHandleImageError(img) {
                img.src = 'images/default_profile.png';
                img.onerror = null;
            }
            
            // 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';
                    };
                });
            });
            
            // Registration Approval Modal Functions
            function empDashboardOpenRegistrationApprovalModal() {
                document.getElementById('registrationApprovalModal').style.display = 'flex';
                empDashboardLoadRegistrationRequests();
            }
            
            function empDashboardCloseRegistrationModal() {
                document.getElementById('registrationApprovalModal').style.display = 'none';
                document.getElementById('registrationRequestsContent').innerHTML = '';
            }
            
            // Password Reset Approval Modal Functions
            function empDashboardOpenPasswordResetApprovalModal() {
                document.getElementById('passwordResetApprovalModal').style.display = 'flex';
                empDashboardLoadPasswordResetRequests();
            }
            
            function empDashboardClosePasswordResetModal() {
                document.getElementById('passwordResetApprovalModal').style.display = 'none';
                document.getElementById('passwordResetRequestsContent').innerHTML = '';
            }
            
            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>
                        `;
                    });
            }
            
            function empDashboardLoadPasswordResetRequests() {
                const loadingSpinner = document.getElementById('passwordResetLoadingSpinner');
                const passwordResetContent = document.getElementById('passwordResetRequestsContent');
                
                loadingSpinner.style.display = 'block';
                passwordResetContent.innerHTML = '';
                
                // Add timestamp to prevent caching
                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>
                        `;
                    });
            }
            
            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 => {
        if (!response.ok) {
            throw new Error('Network response was not ok: ' + response.status);
        }
        return response.json();
    })
    .then(data => {
        if (data.success) {
            if (data.email_sent) {
                alert('✓ ' + data.message + '\n\n✓ Email notification sent successfully.');
            } else {
                alert('✓ ' + data.message);
            }
            // Remove the approved row from the table
            const row = document.getElementById('registration-row-' + registrationId);
            if (row) {
                row.remove();
            }
            // Update pending counts
            empDashboardUpdateRegistrationPendingCount();
            // Check if table is empty
            empDashboardCheckRegistrationEmptyTable();
            // Refresh alerts
            empDashboardRefreshRegistrationAlerts();
        } else {
            alert('Error: ' + data.message);
            console.error('Registration approval error details:', data);
        }
    })
    .catch(error => {
        alert('Error processing approval. Please try again.\nTechnical details: ' + error.message);
        console.error('Fetch error:', error);
    });
}
            
            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 => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok: ' + response.status);
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.success) {
                        alert(data.message);
                        // Remove the rejected row from the table
                        const row = document.getElementById('registration-row-' + registrationId);
                        if (row) {
                            row.remove();
                        }
                        // Update pending counts
                        empDashboardUpdateRegistrationPendingCount();
                        // Check if table is empty
                        empDashboardCheckRegistrationEmptyTable();
                        // Refresh alerts
                        empDashboardRefreshRegistrationAlerts();
                    } else {
                        alert('Error: ' +data.message);
                        console.error('Registration rejection error details:', data);
                    }
                })
                .catch(error => {
                    alert('Error processing rejection. Please try again.\nTechnical details: ' + error.message);
                    console.error('Fetch error:', error);
                });
            }
            
            // Function to approve password reset (UPDATE password and approve user)
            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 => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok: ' + response.status);
                    }
                    return 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.');
                        }
                        // Remove the row from the table
                        const row = document.getElementById('password-reset-row-' + requestId);
                        if (row) {
                            row.remove();
                        }
                        // Update pending counts
                        empDashboardUpdatePasswordResetPendingCount();
                        // Check if table is empty
                        empDashboardCheckPasswordResetEmptyTable();
                        // Refresh alerts
                        empDashboardRefreshPasswordResetAlerts();
                    } else {
                        alert('Error: ' + data.message);
                        console.error('Password reset error details:', data);
                    }
                })
                .catch(error => {
                    alert('Error processing request. Please try again.\nTechnical details: ' + error.message);
                    console.error('Fetch error:', error);
                });
            }
            
            // Function to reject password reset (DELETE record)
            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 => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok: ' + response.status);
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.success) {
                        alert(data.message);
                        // Remove the row from the table
                        const row = document.getElementById('password-reset-row-' + requestId);
                        if (row) {
                            row.remove();
                        }
                        // Update pending counts
                        empDashboardUpdatePasswordResetPendingCount();
                        // Check if table is empty
                        empDashboardCheckPasswordResetEmptyTable();
                        // Refresh alerts
                        empDashboardRefreshPasswordResetAlerts();
                    } else {
                        alert('Error: ' + data.message);
                        console.error('Password reset rejection error details:', data);
                    }
                })
                .catch(error => {
                    alert('Error processing request. Please try again.\nTechnical details: ' + error.message);
                    console.error('Fetch error:', error);
                });
            }
            
            function empDashboardUpdateRegistrationPendingCount() {
                // Count current registration rows in table
                const regRows = document.querySelectorAll('#registrationRequestsContent .emp-dashboard-table.approval-table tbody tr');
                const newCount = regRows.length;
                
                // Update all registration badges
                const regBadges = document.querySelectorAll('.emp-dashboard-pending-count-badge');
                regBadges.forEach(badge => {
                    badge.textContent = newCount;
                    if (newCount === 0) {
                        badge.remove();
                    }
                });
                
                // Update modal title badge
                const modalBadge = document.querySelector('#registrationApprovalModal .emp-dashboard-modal-header .badge');
                if (modalBadge) {
                    modalBadge.textContent = newCount;
                    if (newCount === 0) {
                        modalBadge.remove();
                    }
                }
            }
            
            function empDashboardUpdatePasswordResetPendingCount() {
                // Count current password reset rows in table
                const passRows = document.querySelectorAll('#passwordResetRequestsContent .emp-dashboard-table.approval-table tbody tr');
                const newCount = passRows.length;
                
                // Update all password reset badges
                const passBadges = document.querySelectorAll('.emp-dashboard-warning-badge-pulse');
                passBadges.forEach(badge => {
                    badge.textContent = newCount;
                    if (newCount === 0) {
                        badge.remove();
                    }
                });
                
                // Update modal title badge
                const modalBadge = document.querySelector('#passwordResetApprovalModal .emp-dashboard-modal-header .badge');
                if (modalBadge) {
                    modalBadge.textContent = newCount;
                    if (newCount === 0) {
                        modalBadge.remove();
                    }
                }
            }
            
            function empDashboardCheckRegistrationEmptyTable() {
                const tableBody = document.querySelector('#registrationRequestsContent .emp-dashboard-table.approval-table tbody');
                if (tableBody && tableBody.children.length === 0) {
                    const tableContainer = document.getElementById('registrationRequestsContent');
                    tableContainer.innerHTML = `
                        <div class="emp-dashboard-no-pending">
                            <i class="fas fa-check-circle"></i>
                            <h5>No Registration Requests</h5>
                            <p>All registration requests have been processed.</p>
                        </div>
                    `;
                }
            }
            
            function empDashboardCheckPasswordResetEmptyTable() {
                const tableBody = document.querySelector('#passwordResetRequestsContent .emp-dashboard-table.approval-table tbody');
                if (tableBody && tableBody.children.length === 0) {
                    const tableContainer = document.getElementById('passwordResetRequestsContent');
                    tableContainer.innerHTML = `
                        <div class="emp-dashboard-no-pending">
                            <i class="fas fa-check-circle"></i>
                            <h5>No Password Reset Requests</h5>
                            <p>All password reset requests have been processed.</p>
                        </div>
                    `;
                }
            }
            
            function empDashboardRefreshRegistrationAlerts() {
                const regRows = document.querySelectorAll('#registrationRequestsContent .emp-dashboard-table.approval-table tbody tr');
                const newCount = regRows.length;
                
                // Update alert
                const alert = document.querySelector('.alert-danger');
                if (alert) {
                    if (newCount === 0) {
                        alert.style.display = 'none';
                    } else {
                        const alertText = alert.querySelector('strong');
                        if (alertText) {
                            alertText.innerHTML = `Registration Approvals Pending! You have ${newCount} registration request(s) waiting for your approval.`;
                        }
                        const badge = alert.querySelector('.badge');
                        if (badge) {
                            badge.textContent = newCount;
                        }
                    }
                }
                
                // Update card
                const card = document.querySelector('.emp-dashboard-alert-card .badge.bg-danger');
                if (card && card.closest('.emp-dashboard-alert-card') && card.closest('.emp-dashboard-alert-card').querySelector('h5').innerText.includes('Registration')) {
                    card.textContent = newCount + ' Pending';
                    if (newCount === 0) {
                        card.remove();
                    }
                }
            }
            
            function empDashboardRefreshPasswordResetAlerts() {
                const passRows = document.querySelectorAll('#passwordResetRequestsContent .emp-dashboard-table.approval-table tbody tr');
                const newCount = passRows.length;
                
                // Update alert
                const alert = document.querySelector('.alert-warning');
                if (alert) {
                    if (newCount === 0) {
                        alert.style.display = 'none';
                    } else {
                        const alertText = alert.querySelector('strong');
                        if (alertText) {
                            alertText.innerHTML = `Password Reset Requests Pending! You have ${newCount} password reset request(s) waiting for your approval.`;
                        }
                        const badge = alert.querySelector('.badge');
                        if (badge) {
                            badge.textContent = newCount;
                        }
                    }
                }
                
                // Update card
                const card = document.querySelector('.emp-dashboard-alert-card .badge.bg-warning');
                if (card && card.closest('.emp-dashboard-alert-card') && card.closest('.emp-dashboard-alert-card').querySelector('h5').innerText.includes('Password')) {
                    card.textContent = newCount + ' Pending';
                    if (newCount === 0) {
                        card.remove();
                    }
                }
            }
            
            // Close modals when clicking outside
            document.getElementById('registrationApprovalModal').addEventListener('click', function(e) {
                if (e.target === this) {
                    empDashboardCloseRegistrationModal();
                }
            });
            
            document.getElementById('passwordResetApprovalModal').addEventListener('click', function(e) {
                if (e.target === this) {
                    empDashboardClosePasswordResetModal();
                }
            });
            
            // Close modals with escape key
            document.addEventListener('keydown', function(e) {
                if (e.key === 'Escape') {
                    if (document.getElementById('registrationApprovalModal').style.display === 'flex') {
                        empDashboardCloseRegistrationModal();
                    }
                    if (document.getElementById('passwordResetApprovalModal').style.display === 'flex') {
                        empDashboardClosePasswordResetModal();
                    }
                }
            });
            
            // Initialize modal close buttons
            document.getElementById('closeRegistrationModal').addEventListener('click', empDashboardCloseRegistrationModal);
            document.getElementById('closePasswordResetModal').addEventListener('click', empDashboardClosePasswordResetModal);
            
            // Prevent any interaction with background content when profile modal is shown
            <?php if (!$profile_exists): ?>
            document.addEventListener('DOMContentLoaded', function() {
                // Disable all links and buttons when profile is incomplete
                document.addEventListener('click', function(e) {
                    if (!e.target.closest('.profile-modal-backdrop') && !e.target.closest('.profile-modal')) {
                        e.preventDefault();
                        e.stopPropagation();
                    }
                }, true);
                
                // Prevent keyboard navigation
                document.addEventListener('keydown', function(e) {
                    if (e.key === 'Tab' || e.key === 'Escape') {
                        e.preventDefault();
                        e.stopPropagation();
                    }
                });
            });
            <?php endif; ?>
            
            // Make functions available globally with unique names
            window.empDashboardRedirectToProfile = empDashboardRedirectToProfile;
            window.empDashboardOpenRegistrationApprovalModal = empDashboardOpenRegistrationApprovalModal;
            window.empDashboardOpenPasswordResetApprovalModal = empDashboardOpenPasswordResetApprovalModal;
            window.empDashboardApproveRegistration = empDashboardApproveRegistration;
            window.empDashboardRejectRegistration = empDashboardRejectRegistration;
            window.empDashboardApprovePasswordReset = empDashboardApprovePasswordReset;
            window.empDashboardRejectPasswordReset = empDashboardRejectPasswordReset;
            
        })();
		
		// Password toggle function
function togglePassword(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');
    }
}
    </script>
    
</body>
</html>