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

// Database connection
include_once 'connect.php';

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

// Handle redirect from successful submission - IMPORTANT: This should be at the TOP
if (isset($_GET['new_emp']) && isset($_GET['cnic'])) {
    $new_emp_id = (int)$_GET['new_emp'];
    $new_cnic = $_GET['cnic'];
    
    // First, check if employee exists in employees table (newly created profile)
    $verify_stmt = $conn->prepare("SELECT * FROM employees WHERE employee_id = ? AND cnic = ?");
    $verify_stmt->bind_param("is", $new_emp_id, $new_cnic);
    $verify_stmt->execute();
    $verify_result = $verify_stmt->get_result();
    
    if ($verify_result->num_rows > 0) {
        $new_employee = $verify_result->fetch_assoc();
        
        // Store in session
        $_SESSION['employee_id'] = $new_employee['employee_id'];
        $_SESSION['cnic'] = $new_employee['cnic'];
        $_SESSION['full_name'] = $new_employee['full_name'];
        
        // Also check if they exist in registrations_emp table
        $reg_stmt = $conn->prepare("SELECT * FROM registrations_emp WHERE cnic = ?");
        $reg_stmt->bind_param("s", $new_employee['cnic']);
        $reg_stmt->execute();
        $reg_result = $reg_stmt->get_result();
        
        if ($reg_result->num_rows > 0) {
            // User exists in both tables - normal login
            $reg_data = $reg_result->fetch_assoc();
            $_SESSION['reg_emp_id'] = $reg_data['id'];
            $_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
            ];
        } else {
            // User only exists in employees table (newly created profile)
            $_SESSION['employee_data'] = [
                'full_name' => $new_employee['full_name'],
                'emp_numb' => $new_employee['personal_no'],
                'cnic' => $new_employee['cnic'],
                'dob' => $new_employee['date_of_birth'],
                'photo_path' => $new_employee['photo_path'] ?? null
            ];
        }
        $reg_stmt->close();
        
        // Mark profile as complete
        $_SESSION['profile_incomplete'] = false;
        $_SESSION['profile_created'] = true;
        
        // 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'])) {
    $employee_exists = true;
    $employee = [
        'full_name' => $_SESSION['full_name'],
        'cnic' => $_SESSION['cnic'],
        'role_id' => $_SESSION['employee_data']['role_id'] ?? 6,
        'role_name' => $_SESSION['employee_data']['role_name'] ?? 'Employee',
        'photo_path' => $_SESSION['employee_data']['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;
    
    if ($profile_exists) {
        $profile_data = $profile_result->fetch_assoc();
        $_SESSION['employee_id'] = $profile_data['employee_id'];
        $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'])) {
        $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();
            
            $employee['role_name'] = 'Employee';
            $employee['role_id'] = 6;
        } else {
            // FIXED: Removed e.current_school_emis from query as it may not exist
            $stmt = $conn->prepare("SELECT re.*, er.role_name, er.role_id, e.photo_path 
                                   FROM registrations_emp re
                                   LEFT JOIN employee_roles er ON re.role_id = er.role_id
                                   LEFT JOIN employees e ON re.cnic = e.cnic
                                   WHERE re.id = ? AND re.cnic = ?");
            if (!$stmt) {
                die("Error preparing query: " . $conn->error);
            }
            $stmt->bind_param("is", $_SESSION['employee_id'], $_SESSION['cnic']);
            $stmt->execute();
            $result = $stmt->get_result();

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

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

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

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

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

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

// Define access levels based on role_id
$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);

$has_approval_access = ($is_deo || $is_mis_admin);

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

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

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

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

    // Get all registered employees
    $all_employees = [];
    $all_pending_profiles = [];
    $all_completed_profiles = [];

    // Registered employees with profile status
    $employees_query = $conn->query("SELECT re.id, re.full_name, re.emp_numb, re.cnic, re.employee_email, re.created_at, er.role_name,
                                    (SELECT COUNT(*) FROM employees e WHERE e.cnic = re.cnic) as profile_completed
                                     FROM registrations_emp re 
                                     LEFT JOIN employee_roles er ON re.role_id = er.role_id 
                                     WHERE re.status = 1 
                                     ORDER BY re.created_at DESC");
    
    if ($employees_query) {
        while ($row = $employees_query->fetch_assoc()) {
            $row['profile_completed'] = $row['profile_completed'] > 0;
            
            // FIXED: Safely check for school data without causing errors
            $row['school_name'] = 'Not assigned';
            
            $all_employees[] = $row;
            
            if ($row['profile_completed']) {
                $all_completed_profiles[] = $row;
            } else {
                $all_pending_profiles[] = $row;
            }
        }
        $employees_query->close();
    }
    
    // Get all available roles for dropdown
    $roles = [];
    $roles_query = $conn->query("SELECT role_id, role_name FROM employee_roles ORDER BY role_name");
    if ($roles_query) {
        while ($role = $roles_query->fetch_assoc()) {
            $roles[] = $role;
        }
        $roles_query->close();
    }
}

// Access control
$has_hr_access = ($is_secretary || $is_deo || $is_mis_admin);
$has_finance_access = ($is_secretary || $is_deo || $is_mis_admin);
$has_school_access = ($is_secretary || $is_deo || $is_mis_admin || $is_aeo || $is_principal);
$has_student_access = ($is_secretary || $is_deo || $is_mis_admin || $is_aeo || $is_teacher);
$has_reports_access = ($is_secretary || $is_deo || $is_mis_admin || $is_aeo);
$has_announcements_access = ($is_secretary || $is_deo || $is_principal || $is_mis_admin);
$has_teacher_portal_access = $is_teacher;
$has_teacher_results_access = ($is_teacher || $is_principal || $is_aeo || $is_ddeo || $is_deo || $is_mis_admin);
$has_smc_access = ($is_principal || $is_aeo || $is_ddeo || $is_deo || $is_mis_admin);
$has_games_access = true;
$has_books_access = true;
$has_softwares_access = ($is_mis_admin || $is_deo || $is_teacher);
$has_office_management_access = ($is_clerk || $is_staff || $is_mis_admin || $is_deo);
$has_documents_access = true;
$has_applications_access = true;

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

$initials = getInitials($employee['full_name'] ?? 'User');

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

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

// Check for pending registration approvals
$pending_count = 0;
$pending_registrations = [];
if ($has_approval_access) {
    $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, er.role_id, 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 
                                        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';
                }
                if (!isset($row['role_id'])) {
                    $row['role_id'] = 6;
                }
                $pending_registrations[] = $row;
            }
            $check_pending->close();
        }
    }
}

// Password reset requests
$password_reset_count = 0;
$password_reset_requests = [];

if ($has_approval_access) {
    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;
            }
        }
    } catch (Exception $e) {
        error_log("Error in password reset processing: " . $e->getMessage());
    }
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// Handle bulk approve registration actions
if (isset($_POST['bulk_action']) && $_POST['bulk_action'] == 'bulk_approve_registrations' && $has_approval_access) {
    $response = ['success' => false, 'message' => '', 'success_count' => 0, 'failed_count' => 0, 'email_sent_count' => 0];
    
    if (isset($_POST['registration_ids']) && !empty($_POST['registration_ids'])) {
        $registration_ids = json_decode($_POST['registration_ids'], true);
        $role_ids = isset($_POST['role_ids']) ? json_decode($_POST['role_ids'], true) : [];
        $success_count = 0;
        $failed_count = 0;
        $email_sent_count = 0;
        
        $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'];
        }
        
        $current_time = date('Y-m-d H:i:s');
        
        foreach ($registration_ids as $registration_id) {
            $registration_id = intval($registration_id);
            $role_id = isset($role_ids[$registration_id]) ? intval($role_ids[$registration_id]) : null;
            
            $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();
                if ($emp_result->num_rows > 0) {
                    $emp_data = $emp_result->fetch_assoc();
                    
                    if ($role_id) {
                        $update_stmt = $conn->prepare("UPDATE registrations_emp SET status = 1, role_id = ?, forgot_password_request = 0, reg_approved_by = ?, reg_approved_time = ? WHERE id = ?");
                        $update_stmt->bind_param("issi", $role_id, $admin_name, $current_time, $registration_id);
                    } else {
                        $update_stmt = $conn->prepare("UPDATE registrations_emp SET status = 1, forgot_password_request = 0, reg_approved_by = ?, reg_approved_time = ? WHERE id = ?");
                        $update_stmt->bind_param("ssi", $admin_name, $current_time, $registration_id);
                    }
                    
                    if ($update_stmt && $update_stmt->execute()) {
                        $success_count++;
                        if (!empty($emp_data['employee_email']) && filter_var($emp_data['employee_email'], FILTER_VALIDATE_EMAIL)) {
                            if (sendRegistrationApprovalEmail($emp_data['employee_email'], $emp_data['full_name'], $emp_data['emp_numb'], $emp_data['cnic'], $admin_name)) {
                                $email_sent_count++;
                            }
                        }
                    } else {
                        $failed_count++;
                    }
                    if ($update_stmt) $update_stmt->close();
                }
                $get_emp_stmt->close();
            } else {
                $failed_count++;
            }
        }
        
        $response['success'] = true;
        $response['success_count'] = $success_count;
        $response['failed_count'] = $failed_count;
        $response['email_sent_count'] = $email_sent_count;
        $response['message'] = "Successfully approved $success_count registration(s)";
        
        // Reset pending count for response
        $response['new_pending_count'] = $pending_count - $success_count;
        $response['new_reset_count'] = $password_reset_count;
    }
    
    header('Content-Type: application/json');
    echo json_encode($response);
    exit();
}

// Handle bulk approve password reset actions
if (isset($_POST['bulk_action']) && $_POST['bulk_action'] == 'bulk_approve_password_resets' && $has_approval_access) {
    $response = ['success' => false, 'message' => '', 'success_count' => 0, 'failed_count' => 0, 'email_sent_count' => 0];
    
    if (isset($_POST['request_ids']) && !empty($_POST['request_ids'])) {
        $request_ids = json_decode($_POST['request_ids'], true);
        $success_count = 0;
        $failed_count = 0;
        $email_sent_count = 0;
        
        $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'];
        }
        
        $current_time = date('Y-m-d H:i:s');
        
        foreach ($request_ids as $request_id) {
            $request_id = intval($request_id);
            
            $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'];
                        
                        if (!empty($new_password)) {
                            $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
                            
                            $check_columns = $conn->query("SHOW COLUMNS FROM registrations_emp");
                            $columns = [];
                            while ($col = $check_columns->fetch_assoc()) {
                                $columns[$col['Field']] = true;
                            }
                            
                            $sql = "UPDATE registrations_emp SET 
                                    password = ?, 
                                    status = 1,
                                    forgot_password_request = 0,
                                    forgot_password_new = NULL,
                                    reset_approved_by = ?,
                                    reset_approved_time = ?";
                            
                            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()) {
                                    $success_count++;
                                    if (!empty($password_data['employee_email']) && filter_var($password_data['employee_email'], FILTER_VALIDATE_EMAIL)) {
                                        if (sendPasswordResetApprovalEmail($password_data['employee_email'], $password_data['full_name'], $password_data['emp_numb'], $password_data['cnic'], $admin_name, $new_password)) {
                                            $email_sent_count++;
                                        }
                                    }
                                } else {
                                    $failed_count++;
                                }
                                $update_stmt->close();
                            } else {
                                $failed_count++;
                            }
                        } else {
                            $failed_count++;
                        }
                    } else {
                        $failed_count++;
                    }
                } else {
                    $failed_count++;
                }
                $get_password_stmt->close();
            } else {
                $failed_count++;
            }
        }
        
        $response['success'] = true;
        $response['success_count'] = $success_count;
        $response['failed_count'] = $failed_count;
        $response['email_sent_count'] = $email_sent_count;
        $response['message'] = "Successfully approved $success_count password reset request(s)";
        
        // Reset pending counts for response
        $response['new_pending_count'] = $pending_count;
        $response['new_reset_count'] = $password_reset_count - $success_count;
    }
    
    header('Content-Type: application/json');
    echo json_encode($response);
    exit();
}

// Handle single approval/reject actions
if (isset($_POST['action']) && $has_approval_access) {
    $response = ['success' => false, 'message' => '', 'email_sent' => false];
    
    if (isset($_POST['registration_id']) && isset($_POST['action_type'])) {
        $registration_id = intval($_POST['registration_id']);
        $action_type = $_POST['action_type'];
        
        if ($action_type === 'approve') {
            $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'];
            }
            
            $current_time = date('Y-m-d H:i:s');
            $role_id = isset($_POST['role_id']) ? intval($_POST['role_id']) : null;
            
            $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();
                
                if ($role_id) {
                    $update_stmt = $conn->prepare("UPDATE registrations_emp SET status = 1, role_id = ?, forgot_password_request = 0, reg_approved_by = ?, reg_approved_time = ? WHERE id = ?");
                    $update_stmt->bind_param("issi", $role_id, $admin_name, $current_time, $registration_id);
                } else {
                    $update_stmt = $conn->prepare("UPDATE registrations_emp SET status = 1, forgot_password_request = 0, reg_approved_by = ?, reg_approved_time = ? WHERE id = ?");
                    $update_stmt->bind_param("ssi", $admin_name, $current_time, $registration_id);
                }
                
                if ($update_stmt) {
                    if ($update_stmt->execute()) {
                        if (!empty($emp_data['employee_email']) && filter_var($emp_data['employee_email'], FILTER_VALIDATE_EMAIL)) {
                            $email_sent = sendRegistrationApprovalEmail($emp_data['employee_email'], $emp_data['full_name'], $emp_data['emp_numb'], $emp_data['cnic'], $admin_name);
                            $response['email_sent'] = $email_sent;
                        }
                        $response['success'] = true;
                        $response['message'] = 'Registration approved successfully';
                    } else {
                        $response['message'] = 'Error approving registration';
                    }
                    $update_stmt->close();
                }
            }
            
        } elseif ($action_type === 'reject') {
            $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';
                }
                $delete_stmt->close();
            }
        }
    }
    
    // Update counts for response
    $response['new_pending_count'] = max(0, $pending_count - 1);
    $response['new_reset_count'] = $password_reset_count;
    
    header('Content-Type: application/json');
    echo json_encode($response);
    exit();
}

// Handle password reset approval/reject actions
if (isset($_POST['password_action']) && $has_approval_access) {
    $response = ['success' => false, 'message' => '', 'email_sent' => false];
    
    if (isset($_POST['request_id']) && isset($_POST['action_type'])) {
        $request_id = intval($_POST['request_id']);
        $action_type = $_POST['action_type'];
        
        if ($action_type === 'approve_reset') {
            $get_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'];
                        
                        if (!empty($new_password)) {
                            $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
                            
                            $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'];
                            }
                            
                            $current_time = date('Y-m-d H:i:s');
                            
                            $check_columns = $conn->query("SHOW COLUMNS FROM registrations_emp");
                            $columns = [];
                            while ($col = $check_columns->fetch_assoc()) {
                                $columns[$col['Field']] = true;
                            }
                            
                            $sql = "UPDATE registrations_emp SET 
                                    password = ?, 
                                    status = 1,
                                    forgot_password_request = 0,
                                    forgot_password_new = NULL,
                                    reset_approved_by = ?,
                                    reset_approved_time = ?";
                            
                            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()) {
                                    if (!empty($password_data['employee_email']) && filter_var($password_data['employee_email'], FILTER_VALIDATE_EMAIL)) {
                                        $email_sent = sendPasswordResetApprovalEmail($password_data['employee_email'], $password_data['full_name'], $password_data['emp_numb'], $password_data['cnic'], $admin_name, $new_password);
                                        $response['email_sent'] = $email_sent;
                                    }
                                    $response['success'] = true;
                                    $response['message'] = 'Password reset approved successfully';
                                }
                                $update_stmt->close();
                            }
                        }
                    }
                }
                $get_password_stmt->close();
            }
            
        } elseif ($action_type === 'reject_reset') {
            $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!';
                }
                $delete_stmt->close();
            }
        }
    }
    
    // Update counts for response
    $response['new_pending_count'] = $pending_count;
    $response['new_reset_count'] = max(0, $password_reset_count - 1);
    
    header('Content-Type: application/json');
    echo json_encode($response);
    exit();
}

// AJAX request for pending registrations
if (isset($_GET['get_pending']) && $_GET['get_pending'] == 'true') {
    if ($has_approval_access) {
        // Get all available roles for dropdown
        $roles = [];
        $roles_query = $conn->query("SELECT role_id, role_name FROM employee_roles ORDER BY role_name");
        if ($roles_query) {
            while ($role = $roles_query->fetch_assoc()) {
                $roles[] = $role;
            }
            $roles_query->close();
        }
        
        $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, er.role_id, 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 
                                            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';
                    }
                    if (!isset($row['role_id'])) {
                        $row['role_id'] = 6;
                    }
                    $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="d-flex justify-content-between align-items-center mb-3">
                <div>
                    <span class="fw-bold"><?php echo count($pending_registrations_refresh); ?> pending request(s)</span>
                </div>
                <div>
                    <button class="btn btn-primary btn-sm" onclick="selectAllRegistrationRows()">
                        <i class="fas fa-check-double me-1"></i>Select All
                    </button>
                    <button class="btn btn-success btn-sm" onclick="bulkApproveRegistrations()">
                        <i class="fas fa-check-circle me-1"></i>Approve Selected
                    </button>
                </div>
            </div>
            <div class="table-responsive">
                <table class="table table-hover emp-dashboard-table approval-table" id="registrationApprovalTable">
                    <thead>
                        <tr>
                            <th width="40">
                                <input type="checkbox" id="selectAllRegistration" onchange="toggleAllRegistrationCheckboxes(this.checked)">
                            </th>
                            <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>
                                <input type="checkbox" name="registration_select[]" value="<?php echo $registration['id']; ?>" class="registration-checkbox">
                            </td>
                            <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>
                                <select class="form-select form-select-sm role-select" data-registration-id="<?php echo $registration['id']; ?>" style="width: 140px;">
                                    <?php foreach ($roles as $role): ?>
                                        <option value="<?php echo $role['role_id']; ?>" <?php echo ($role['role_id'] == $registration['role_id']) ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($role['role_name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </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>
            <script>
                // Make functions available globally without window prefix to avoid conflicts
                function getRoleId(registrationId) {
                    const select = document.querySelector(`.role-select[data-registration-id="${registrationId}"]`);
                    return select ? select.value : null;
                }
            </script>
        <?php endif; ?>
        <?php
        exit();
    }
}

// AJAX request for password reset requests
if (isset($_GET['get_password_reset']) && $_GET['get_password_reset'] == 'true') {
    if ($has_approval_access) {
        $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_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="d-flex justify-content-between align-items-center mb-3">
                    <div>
                        <span class="fw-bold"><?php echo count($password_reset_requests_refresh); ?> pending request(s)</span>
                    </div>
                    <div>
                        <button class="btn btn-primary btn-sm" onclick="selectAllPasswordResetRows()">
                            <i class="fas fa-check-double me-1"></i>Select All
                        </button>
                        <button class="btn btn-success btn-sm" onclick="bulkApprovePasswordResets()">
                            <i class="fas fa-check-circle me-1"></i>Approve Selected
                        </button>
                    </div>
                </div>
                <div class="table-responsive">
                    <table class="table table-hover emp-dashboard-table approval-table" id="passwordResetApprovalTable">
                        <thead>
                            <tr>
                                <th width="40">
                                    <input type="checkbox" id="selectAllPasswordReset" onchange="toggleAllPasswordResetCheckboxes(this.checked)">
                                </th>
                                <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>
                                    <input type="checkbox" name="password_reset_select[]" value="<?php echo $request['id']; ?>" class="password-reset-checkbox">
                                </td>
                                <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
        }
    }
    exit();
}

// AJAX request for registered employees list
if (isset($_GET['get_registered_employees']) && $_GET['get_registered_employees'] == 'true' && ($is_deo || $is_mis_admin)) {
    ?>
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h5>Registered Employees (<?php echo count($all_employees); ?>)</h5>
        <div>
            <button class="btn btn-success btn-sm me-2" onclick="showExportOptions('registered')">
                <i class="fas fa-file-excel me-1"></i>Export to Excel
            </button>
            <button class="btn btn-primary btn-sm" onclick="printRegisteredEmployees()">
                <i class="fas fa-print me-1"></i>Print List
            </button>
        </div>
    </div>
    
    <?php if (!empty($all_employees)): ?>
        <div class="table-responsive">
            <table class="table table-sm table-hover" id="registeredEmployeesTable">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>Full Name</th>
                        <th>Employee No</th>
                        <th>CNIC</th>
                        <th>Email</th>
                        <th>Role</th>
                        <th>Profile Status</th>
                        <th>Registration Date</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($all_employees as $index => $emp): ?>
                        <tr>
                            <td><?php echo $index + 1; ?></td>
                            <td><strong><?php echo htmlspecialchars($emp['full_name']); ?></strong></td>
                            <td><?php echo htmlspecialchars($emp['emp_numb']); ?></td>
                            <td class="emp-dashboard-cnic-display"><?php echo htmlspecialchars($emp['cnic']); ?></td>
                            <td><?php echo htmlspecialchars($emp['employee_email'] ?? 'N/A'); ?></td>
                            <td>
                                <span class="badge bg-info emp-dashboard-role-badge">
                                    <?php echo htmlspecialchars($emp['role_name'] ?? 'Employee'); ?>
                                </span>
                            </td>
                            <td>
                                <?php if ($emp['profile_completed']): ?>
                                    <span class="badge bg-success">Completed</span>
                                <?php else: ?>
                                    <span class="badge bg-warning">Pending</span>
                                <?php endif; ?>
                            </td>
                            <td><?php echo date('Y-m-d', strtotime($emp['created_at'])); ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php else: ?>
        <p class="text-muted text-center">No registered employees found</p>
    <?php endif; ?>
    <?php
    exit();
}

// AJAX request for completed profiles list - FIXED
if (isset($_GET['get_completed_profiles']) && $_GET['get_completed_profiles'] == 'true' && ($is_deo || $is_mis_admin)) {
    // Get all completed profiles with school names
    $all_completed_profiles = [];
    
    $completed_query = $conn->query("SELECT re.id, re.full_name, re.emp_numb, re.cnic, re.employee_email, re.created_at, er.role_name
                                    FROM registrations_emp re 
                                    LEFT JOIN employee_roles er ON re.role_id = er.role_id 
                                    INNER JOIN employees e ON re.cnic = e.cnic
                                    WHERE re.status = 1 
                                    ORDER BY re.created_at DESC");
    
    if ($completed_query) {
        while ($row = $completed_query->fetch_assoc()) {
            // FIXED: Use school_emis table instead of schools
            $school_name = 'Not assigned';
            
            $all_completed_profiles[] = $row;
        }
        $completed_query->close();
    }
    ?>
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h5>Completed Profiles (<?php echo count($all_completed_profiles); ?>)</h5>
        <div>
            <button class="btn btn-success btn-sm me-2" onclick="showExportOptions('completed')">
                <i class="fas fa-file-excel me-1"></i>Export to Excel
            </button>
            <button class="btn btn-primary btn-sm" onclick="printCompletedProfiles()">
                <i class="fas fa-print me-1"></i>Print List
            </button>
        </div>
    </div>
    
    <?php if (!empty($all_completed_profiles)): ?>
        <div class="table-responsive">
            <table class="table table-sm table-hover" id="completedProfilesTable">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>Full Name</th>
                        <th>Employee No</th>
                        <th>CNIC</th>
                        <th>School Name</th>
                        <th>Role</th>
                        <th>Registration Date</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($all_completed_profiles as $index => $emp): ?>
                        <tr>
                            <td><?php echo $index + 1; ?></td>
                            <td><strong><?php echo htmlspecialchars($emp['full_name']); ?></strong></td>
                            <td><?php echo htmlspecialchars($emp['emp_numb']); ?></td>
                            <td class="emp-dashboard-cnic-display"><?php echo htmlspecialchars($emp['cnic']); ?></td>
                            <td>Not assigned</td>
                            <td>
                                <span class="badge bg-info emp-dashboard-role-badge">
                                    <?php echo htmlspecialchars($emp['role_name'] ?? 'Employee'); ?>
                                </span>
                            </td>
                            <td><?php echo date('Y-m-d', strtotime($emp['created_at'])); ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php else: ?>
        <p class="text-muted text-center">No completed profiles found</p>
    <?php endif; ?>
    <?php
    exit();
}

// AJAX request for pending profiles list
if (isset($_GET['get_pending_profiles']) && $_GET['get_pending_profiles'] == 'true' && ($is_deo || $is_mis_admin)) {
    ?>
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h5>Pending Profiles (<?php echo count($all_pending_profiles); ?>)</h5>
        <div>
            <button class="btn btn-success btn-sm me-2" onclick="showExportOptions('pending')">
                <i class="fas fa-file-excel me-1"></i>Export to Excel
            </button>
            <button class="btn btn-primary btn-sm" onclick="printPendingProfiles()">
                <i class="fas fa-print me-1"></i>Print List
            </button>
        </div>
    </div>
    
    <?php if (!empty($all_pending_profiles)): ?>
        <div class="table-responsive">
            <table class="table table-sm table-hover" id="pendingProfilesTable">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>Full Name</th>
                        <th>Employee No</th>
                        <th>CNIC</th>
                        <th>Email</th>
                        <th>Role</th>
                        <th>Registration Date</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($all_pending_profiles as $index => $emp): ?>
                        <tr>
                            <td><?php echo $index + 1; ?></td>
                            <td><strong><?php echo htmlspecialchars($emp['full_name']); ?></strong></td>
                            <td><?php echo htmlspecialchars($emp['emp_numb']); ?></td>
                            <td class="emp-dashboard-cnic-display"><?php echo htmlspecialchars($emp['cnic']); ?></td>
                            <td><?php echo htmlspecialchars($emp['employee_email'] ?? 'N/A'); ?></td>
                            <td>
                                <span class="badge bg-info emp-dashboard-role-badge">
                                    <?php echo htmlspecialchars($emp['role_name'] ?? 'Employee'); ?>
                                </span>
                            </td>
                            <td><?php echo date('Y-m-d', strtotime($emp['created_at'])); ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php else: ?>
        <p class="text-muted text-center">No pending profiles found</p>
    <?php endif; ?>
    <?php
    exit();
}

// Export to Excel with page range support
if (isset($_GET['export_excel']) && ($is_deo || $is_mis_admin)) {
    $export_type = $_GET['export_excel'];
    $pages_param = isset($_GET['pages']) ? $_GET['pages'] : 'all';
    $items_per_page = 50; // Items per page
    
    // Parse page range
    $start_page = 1;
    $end_page = null;
    $limit_sql = '';
    $page_info = '';
    
    if ($pages_param !== 'all') {
        if (strpos($pages_param, 'range:') === 0) {
            $range = str_replace('range:', '', $pages_param);
            $range_parts = explode('-', $range);
            if (count($range_parts) == 2) {
                $start_page = max(1, intval($range_parts[0]));
                $end_page = intval($range_parts[1]);
                $offset = ($start_page - 1) * $items_per_page;
                $limit = ($end_page - $start_page + 1) * $items_per_page;
                $limit_sql = " LIMIT $offset, $limit";
                $page_info = "Pages $start_page to $end_page";
            }
        }
    } else {
        $page_info = "All Pages";
    }
    
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment; filename="' . $export_type . '_profiles_' . date('Y-m-d') . '.xls"');
    header('Pragma: no-cache');
    header('Expires: 0');
    
    echo '<html><head>';
    echo '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">';
    echo '<style>';
    echo 'body { font-family: Arial, sans-serif; }';
    echo 'h1 { color: #1a3e72; font-size: 24px; margin-bottom: 5px; }';
    echo 'h2 { color: #333; font-size: 18px; margin-top: 0; }';
    echo '.header-info { margin-bottom: 20px; }';
    echo 'table { border-collapse: collapse; width: 100%; margin-top: 20px; }';
    echo 'th { background-color: #1a3e72; color: white; padding: 10px; text-align: left; }';
    echo 'td { padding: 8px; border-bottom: 1px solid #ddd; }';
    echo 'tr:nth-child(even) { background-color: #f2f2f2; }';
    echo '.footer { margin-top: 30px; text-align: center; font-size: 12px; color: #666; border-top: 1px solid #ddd; padding-top: 10px; }';
    echo '</style>';
    echo '</head><body>';
    
    echo '<div class="header-info">';
    echo '<h1>AJ&K Education Department District Kotli</h1>';
    echo '<h2>' . ucfirst(str_replace('_', ' ', $export_type)) . ' List</h2>';
    echo '<p>Generated on: ' . date('F j, Y, g:i a') . '</p>';
    echo '<p>Export Range: ' . $page_info . '</p>';
    echo '</div>';
    
    if ($export_type == 'registered') {
        echo '<table border="1">';
        echo '<tr><th>#</th><th>Full Name</th><th>Employee No</th><th>CNIC</th><th>Email</th><th>Role</th><th>Profile Status</th><th>Registration Date</th></tr>';
        
        $offset = ($pages_param !== 'all') ? ($start_page - 1) * $items_per_page : 0;
        
        $export_query = $conn->query("SELECT re.full_name, re.emp_numb, re.cnic, re.employee_email, re.created_at, er.role_name,
                                     (SELECT COUNT(*) FROM employees e WHERE e.cnic = re.cnic) as profile_completed
                                     FROM registrations_emp re 
                                     LEFT JOIN employee_roles er ON re.role_id = er.role_id 
                                     WHERE re.status = 1 
                                     ORDER BY re.created_at DESC" . $limit_sql);
        
        $index = $offset + 1;
        while ($row = $export_query->fetch_assoc()) {
            echo '<tr>';
            echo '<td>' . $index++ . '</td>';
            echo '<td>' . htmlspecialchars($row['full_name']) . '</td>';
            echo '<td>' . htmlspecialchars($row['emp_numb']) . '</td>';
            echo '<td>' . htmlspecialchars($row['cnic']) . '</td>';
            echo '<td>' . htmlspecialchars($row['employee_email'] ?? 'N/A') . '</td>';
            echo '<td>' . htmlspecialchars($row['role_name'] ?? 'Employee') . '</td>';
            echo '<td>' . ($row['profile_completed'] > 0 ? 'Completed' : 'Pending') . '</td>';
            echo '<td>' . date('Y-m-d', strtotime($row['created_at'])) . '</td>';
            echo '</tr>';
        }
    } elseif ($export_type == 'completed') {
        echo '<table border="1">';
        echo '<tr><th>#</th><th>Full Name</th><th>Employee No</th><th>CNIC</th><th>School Name</th><th>Role</th><th>Registration Date</th></tr>';
        
        $offset = ($pages_param !== 'all') ? ($start_page - 1) * $items_per_page : 0;
        
        $export_query = $conn->query("SELECT re.full_name, re.emp_numb, re.cnic, re.created_at, er.role_name
                                     FROM registrations_emp re 
                                     LEFT JOIN employee_roles er ON re.role_id = er.role_id 
                                     INNER JOIN employees e ON re.cnic = e.cnic
                                     WHERE re.status = 1 
                                     ORDER BY re.created_at DESC" . $limit_sql);
        
        $index = $offset + 1;
        while ($row = $export_query->fetch_assoc()) {
            $school_name = 'Not assigned';
            
            echo '<tr>';
            echo '<td>' . $index++ . '</td>';
            echo '<td>' . htmlspecialchars($row['full_name']) . '</td>';
            echo '<td>' . htmlspecialchars($row['emp_numb']) . '</td>';
            echo '<td>' . htmlspecialchars($row['cnic']) . '</td>';
            echo '<td>' . htmlspecialchars($school_name) . '</td>';
            echo '<td>' . htmlspecialchars($row['role_name'] ?? 'Employee') . '</td>';
            echo '<td>' . date('Y-m-d', strtotime($row['created_at'])) . '</td>';
            echo '</tr>';
        }
    } elseif ($export_type == 'pending') {
        echo '<table border="1">';
        echo '<tr><th>#</th><th>Full Name</th><th>Employee No</th><th>CNIC</th><th>Email</th><th>Role</th><th>Registration Date</th></tr>';
        
        $offset = ($pages_param !== 'all') ? ($start_page - 1) * $items_per_page : 0;
        
        $export_query = $conn->query("SELECT re.full_name, re.emp_numb, re.cnic, re.employee_email, re.created_at, er.role_name
                                     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.status = 1 AND e.cnic IS NULL
                                     ORDER BY re.created_at DESC" . $limit_sql);
        
        $index = $offset + 1;
        while ($row = $export_query->fetch_assoc()) {
            echo '<tr>';
            echo '<td>' . $index++ . '</td>';
            echo '<td>' . htmlspecialchars($row['full_name']) . '</td>';
            echo '<td>' . htmlspecialchars($row['emp_numb']) . '</td>';
            echo '<td>' . htmlspecialchars($row['cnic']) . '</td>';
            echo '<td>' . htmlspecialchars($row['employee_email'] ?? 'N/A') . '</td>';
            echo '<td>' . htmlspecialchars($row['role_name'] ?? 'Employee') . '</td>';
            echo '<td>' . date('Y-m-d', strtotime($row['created_at'])) . '</td>';
            echo '</tr>';
        }
    }
    
    echo '</table>';
    
    // Add footer
    echo '<div class="footer">';
    echo 'Designed by Wajid Muzaffar (Computer Instructor)<br>';
    echo 'AJ&K Education Department District Kotli - DSIS System<br>';
    echo '© ' . date('Y') . ' All Rights Reserved';
    echo '</div>';
    
    echo '</body></html>';
    exit();
}

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

        body.emp-dashboard-body {
            background: linear-gradient(135deg, #f5f7fa 0%, #e9ecf0 100%);
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            overflow: <?php echo !$profile_exists ? 'hidden' : 'auto'; ?>;
            line-height: 1.6;
            color: var(--education-dark);
            min-height: 100vh;
        }

        /* Toast Notifications */
        .toast-notification {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 9999;
            min-width: 350px;
            max-width: 450px;
            background: white;
            border-radius: var(--border-radius-lg);
            box-shadow: 0 15px 40px rgba(0, 0, 0, 0.2);
            padding: 0;
            overflow: hidden;
            animation: slideIn 0.5s ease-out forwards;
            border-left: 5px solid transparent;
        }

        .toast-notification.success {
            border-left-color: var(--education-success);
        }

        .toast-notification.error {
            border-left-color: var(--education-danger);
        }

        .toast-notification.warning {
            border-left-color: var(--education-warning);
        }

        .toast-notification.info {
            border-left-color: var(--education-info);
        }

        .toast-header {
            padding: 15px 20px;
            background: linear-gradient(145deg, #f8fafc, #edf2f7);
            display: flex;
            align-items: center;
            justify-content: space-between;
            border-bottom: 1px solid #e9ecef;
        }

        .toast-header i {
            font-size: 1.2rem;
            margin-right: 10px;
        }

        .toast-header.success i {
            color: var(--education-success);
        }

        .toast-header.error i {
            color: var(--education-danger);
        }

        .toast-body {
            padding: 15px 20px;
            background: white;
            font-size: 0.95rem;
        }

        .toast-close {
            background: none;
            border: none;
            font-size: 1.2rem;
            cursor: pointer;
            color: var(--education-gray);
            transition: var(--transition-fast);
        }

        .toast-close:hover {
            color: var(--education-danger);
            transform: scale(1.1);
        }

        @keyframes slideIn {
            0% { transform: translateX(100%); opacity: 0; }
            100% { transform: translateX(0); opacity: 1; }
        }

        @keyframes slideOut {
            0% { transform: translateX(0); opacity: 1; }
            100% { transform: translateX(100%); opacity: 0; }
        }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        /* Enhanced Stat Cards */
        .enhanced-stat-card {
            background: white;
            border: none;
            border-radius: var(--border-radius-lg);
            box-shadow: var(--box-shadow-md);
            transition: var(--transition-slow);
            overflow: hidden;
            position: relative;
            margin-bottom: 15px;
            height: 150px;
            cursor: pointer;
            border: 1px solid rgba(26, 62, 114, 0.05);
            position: relative;
        }

        .enhanced-stat-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 5px;
            background: linear-gradient(90deg, var(--education-blue), var(--education-gold));
            z-index: 1;
        }

        .enhanced-stat-card:hover {
            transform: translateY(-10px);
            box-shadow: var(--box-shadow-hover);
        }

        .enhanced-stat-card .card-body {
            padding: 18px;
            position: relative;
            z-index: 1;
            height: 100%;
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .stat-icon-container {
            width: 70px;
            height: 70px;
            border-radius: 18px;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 15px 25px rgba(0, 0, 0, 0.15);
            transition: var(--transition-normal);
        }

        .enhanced-stat-card:hover .stat-icon-container {
            transform: scale(1.1) rotate(5deg);
        }

        .stat-icon-container.primary { background: var(--card-gradient-blue); }
        .stat-icon-container.success { background: var(--card-gradient-green); }
        .stat-icon-container.warning { background: var(--card-gradient-gold); }
        .stat-icon-container.purple { background: var(--card-gradient-purple); }
        .stat-icon-container.orange { background: var(--card-gradient-orange); }
        .stat-icon-container.teal { background: var(--card-gradient-teal); }

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

        .stat-content {
            flex: 1;
        }

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

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

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

        .stat-progress-bar {
            height: 100%;
            background: linear-gradient(90deg, var(--education-blue), var(--education-gold));
            border-radius: 10px;
            transition: width 1s ease;
        }

        .stat-percentage {

            font-size: 0.8rem;
            font-weight: 600;
            color: var(--education-blue);
            display: flex;
            justify-content: space-between;
            margin-top: 5px;
        }

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

        .smart-module-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 5px;
            background: linear-gradient(90deg, var(--education-blue), var(--education-gold));
            z-index: 1;
        }

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

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

        .smart-module-icon {
            width: 90px;
            height: 90px;
            border-radius: 22px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 1.5rem;
            font-size: 3rem;
            color: white;
            box-shadow: 0 20px 30px rgba(0, 0, 0, 0.2);
            transition: var(--transition-normal);
            background: var(--card-gradient-blue);
        }

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

        .smart-module-icon.icon-blue { background: var(--card-gradient-blue); }
        .smart-module-icon.icon-green { background: var(--card-gradient-green); }
        .smart-module-icon.icon-gold { background: var(--card-gradient-gold); }
        .smart-module-icon.icon-purple { background: var(--card-gradient-purple); }
        .smart-module-icon.icon-orange { background: var(--card-gradient-orange); }
        .smart-module-icon.icon-teal { background: var(--card-gradient-teal); }
        .smart-module-icon.icon-red { background: linear-gradient(145deg, #b33939, #d9534f); }
        .smart-module-icon.icon-info { background: linear-gradient(145deg, #17a2b8, #20c2d8); }

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

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

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

        .smart-module-badge.pending {
            background: linear-gradient(145deg, #ffc107, #e0a800);
            color: #212529;
        }

        .smart-module-badge.new {
            background: linear-gradient(145deg, #28a745, #218838);
            color: white;
        }

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

        .smart-module-btn::before {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            width: 0;
            height: 0;
            border-radius: 50%;
            background: rgba(26, 62, 114, 0.1);
            transform: translate(-50%, -50%);
            transition: width 0.6s, height 0.6s;
        }

        .smart-module-btn:hover::before {
            width: 300px;
            height: 300px;
        }

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

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

        .welcome-banner::before {
            content: '';
            position: absolute;
            top: -50%;
            right: -20%;
            width: 500px;
            height: 500px;
            background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
            border-radius: 50%;
            z-index: 1;
        }

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

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

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

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

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

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

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

        /* Quick Actions */
        .quick-actions-wrapper {
            background: white;
            border-radius: var(--border-radius-lg);
            padding: 25px;
            box-shadow: var(--box-shadow-sm);
            margin-bottom: 35px;
            border: 1px solid rgba(0, 0, 0, 0.03);
            position: relative;
            overflow: hidden;
        }

        .quick-actions-wrapper::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 3px;
            background: linear-gradient(90deg, var(--education-blue), var(--education-gold));
        }

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

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

        .quick-action-btn::before {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            width: 0;
            height: 0;
            border-radius: 50%;
            background: rgba(26, 62, 114, 0.1);
            transform: translate(-50%, -50%);
            transition: width 0.6s, height 0.6s;
        }

        .quick-action-btn:hover::before {
            width: 300px;
            height: 300px;
        }

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

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

        .export-options-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.75);
            z-index: 9999;
            display: none;
            justify-content: center;
            align-items: center;
            padding: 20px;
            box-sizing: border-box;
            backdrop-filter: blur(5px);
        }

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

        .export-options-modal-content {
            max-width: 600px;
            z-index: 10000;
        }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        @keyframes pulse {
            0% { box-shadow: 0 0 0 0 rgba(255, 193, 7, 0.7); }
            70% { box-shadow: 0 0 0 10px rgba(255, 193, 7, 0); }
            100% { box-shadow: 0 0 0 0 rgba(255, 193, 7, 0); }
        }

        .emp-dashboard-no-pending {
            text-align: center;
            padding: 50px 20px;
            color: var(--education-gray);
        }

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

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

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

        .emp-dashboard-loading-spinner {
            display: none;
            text-align: center;
            padding: 40px 20px;
        }

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

        .role-select {
            border-radius: 6px;
            border: 1px solid #ced4da;
            padding: 4px 8px;
            font-size: 0.85rem;
        }
        
        .role-select:focus {
            border-color: var(--education-blue);
            box-shadow: 0 0 0 0.2rem rgba(26, 62, 114, 0.25);
        }

        /* Export Modal Styles */
        .hover-shadow:hover {
            background-color: white !important;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1) !important;
            border-color: #1a3e72 !important;
            cursor: pointer;
        }

        .page-range-inputs {
            transition: all 0.3s ease;
        }

        .export-summary {
            background: linear-gradient(145deg, #f8fafc, #ffffff);
        }

        /* Print Styles */
        @media print {
            body * {
                visibility: hidden;
            }
            .quick-stats-modal-content,
            .quick-stats-modal-content *,
            .emp-dashboard-modal-content,
            .emp-dashboard-modal-content * {
                visibility: visible;
            }
            .quick-stats-modal-content,
            .emp-dashboard-modal-content {
                position: absolute;
                left: 0;
                top: 0;
                width: 100%;
                margin: 0;
                padding: 20px;
                box-shadow: none;
                background: white;
            }
            .print-header {
                display: block !important;
                text-align: center;
                margin-bottom: 30px;
                padding: 20px;
                border-bottom: 2px solid var(--education-blue);
            }
            .print-header h1 {
                color: var(--education-blue);
                font-size: 24px;
                margin-bottom: 5px;
            }
            .print-header h2 {
                color: #333;
                font-size: 18px;
                margin-top: 0;
            }
            .print-footer {
                position: fixed;
                bottom: 0;
                left: 0;
                right: 0;
                text-align: center;
                font-size: 10px;
                color: #666;
                padding: 10px;
                border-top: 1px solid #ddd;
            }
            .no-print {
                display: none !important;
            }
        }
    </style>
</head>
<body class="emp-dashboard-body">
    <!-- Toast Notifications Container -->
    <div id="toastContainer" style="position: fixed; top: 20px; right: 20px; z-index: 9999;"></div>

    <!-- Profile Completion Modal -->
    <?php if (!$profile_exists): ?>
    <div class="profile-modal-backdrop">
        <div class="profile-modal">
            <div class="profile-modal-header">
                <div class="d-flex align-items-center justify-content-center">
                    <i class="fas fa-user-shield me-3" style="font-size: 1.8rem;"></i>
                    <h3 class="mb-0">Profile Completion Required</h3>
                </div>
            </div>
            <div class="profile-modal-body">
                <div class="profile-icon">
                    <i class="fas fa-user-plus"></i>
                </div>
                <h2 class="profile-modal-title">Complete Your Employee Profile</h2>
                <p class="profile-modal-text">
                    Welcome to <strong>AJ&K Education Department District Kotli</strong>.  
                    To continue using the system, your employee profile must be completed.
                </p>
                <div class="profile-alert">
                    <i class="fas fa-exclamation-circle"></i>
                    <span>Profile completion is <strong class="text-danger">mandatory</strong>.</span>
                </div>
                <button type="button" class="btn profile-btn" onclick="empDashboardRedirectToProfile()">
                    <i class="fas fa-user-edit me-2"></i>Complete My Profile
                </button>
            </div>
        </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
                    <span class="badge bg-danger ms-2 emp-dashboard-pending-count-badge" id="registrationCount"><?php echo $pending_count; ?></span>
                </h3>
                <button class="close-emp-dashboard-modal" id="closeRegistrationModal">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="emp-dashboard-modal-body" id="registrationModalBody">
                <div class="emp-dashboard-loading-spinner" id="registrationLoadingSpinner">
                    <div class="emp-dashboard-spinner-border" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <p class="mt-3">Loading registration requests...</p>
                </div>
                <div id="registrationRequestsContent"></div>
            </div>
        </div>
    </div>

    <!-- Password Reset Approval Modal -->
    <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
                    <span class="badge bg-warning ms-2 emp-dashboard-warning-badge-pulse" id="passwordResetCount"><?php echo $password_reset_count; ?></span>
                </h3>
                <button class="close-emp-dashboard-modal" id="closePasswordResetModal">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="emp-dashboard-modal-body" id="passwordResetModalBody">
                <div class="emp-dashboard-loading-spinner" id="passwordResetLoadingSpinner">
                    <div class="emp-dashboard-spinner-border" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <p class="mt-3">Loading password reset requests...</p>
                </div>
                <div id="passwordResetRequestsContent"></div>
            </div>
        </div>
    </div>

    <!-- Export Options Modal with Page Range -->
    <div class="export-options-modal" id="exportOptionsModal">
        <div class="export-options-modal-content">
            <div class="export-options-modal-header">
                <h3><i class="fas fa-file-excel me-2"></i>Export Options</h3>
                <button class="close-emp-dashboard-modal" onclick="closeExportOptionsModal()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="export-options-modal-body">
                <div class="text-center mb-4">
                    <div class="export-icon-container mb-3">
                        <i class="fas fa-file-excel" style="font-size: 4rem; color: #1a3e72;"></i>
                    </div>
                    <h4 class="mt-3 fw-bold" id="exportModalTitle">Export Registered Employees</h4>
                    <p class="text-muted">Select your export preferences below</p>
                </div>
                
                <div class="alert alert-info d-flex align-items-center">
                    <i class="fas fa-info-circle me-3 fs-4"></i>
                    <div>
                        <strong>Note:</strong> Exporting large datasets may take a few moments. 
                        You can choose to export all pages or a specific range.
                    </div>
                </div>
                
                <div class="export-options-container p-4 border rounded-3 bg-light">
                    <div class="mb-4">
                        <label class="form-label fw-bold fs-6 mb-3">Select Export Range:</label>
                        
                        <div class="form-check mb-3 p-3 border rounded-3 hover-shadow" style="transition: all 0.3s ease;">
                            <input class="form-check-input" type="radio" name="exportPages" id="exportAllPages" value="all" checked>
                            <label class="form-check-label w-100" for="exportAllPages">
                                <div class="d-flex align-items-center">
                                    <div class="me-3">
                                        <i class="fas fa-globe text-primary fs-4"></i>
                                    </div>
                                    <div>
                                        <strong class="fs-6">All Pages</strong>
                                        <p class="text-muted mb-0 small">Export the complete dataset (all records)</p>
                                    </div>
                                </div>
                            </label>
                        </div>
                        
                        <div class="form-check mb-3 p-3 border rounded-3 hover-shadow" style="transition: all 0.3s ease;">
                            <input class="form-check-input" type="radio" name="exportPages" id="exportPageRange" value="range">
                            <label class="form-check-label w-100" for="exportPageRange">
                                <div class="d-flex align-items-center mb-2">
                                    <div class="me-3">
                                        <i class="fas fa-layer-group text-success fs-4"></i>
                                    </div>
                                    <div>
                                        <strong class="fs-6">Page Range</strong>
                                        <p class="text-muted mb-0 small">Export specific pages only</p>
                                    </div>
                                </div>
                            </label>
                            
                            <div class="page-range-inputs mt-3 ms-4 ps-2">
                                <div class="row g-3 align-items-center">
                                    <div class="col-md-5">
                                        <label class="form-label small fw-bold mb-1">From Page:</label>
                                        <input type="number" class="form-control form-control-sm" id="pageStart" 
                                               min="1" max="100" value="1" disabled
                                               onchange="validatePageRange()">
                                    </div>
                                    <div class="col-md-5">
                                        <label class="form-label small fw-bold mb-1">To Page:</label>
                                        <input type="number" class="form-control form-control-sm" id="pageEnd" 
                                               min="1" max="100" value="100" disabled
                                               onchange="validatePageRange()">
                                    </div>
                                    <div class="col-md-2 text-center">
                                        <span class="badge bg-info p-2">of <span id="totalPagesInfo">100</span></span>
                                    </div>
                                </div>
                                <div class="mt-2 small text-muted">
                                    <i class="fas fa-info-circle me-1"></i>
                                    Total available pages: <span id="maxPageEnd">100</span>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="export-summary mt-4 p-3 bg-white rounded-3 border">
                        <h6 class="fw-bold mb-2"><i class="fas fa-chart-simple me-2"></i>Export Summary</h6>
                        <div class="row g-2 small">
                            <div class="col-6">
                                <span class="text-muted">Export Type:</span>
                            </div>
                            <div class="col-6">
                                <strong id="summaryExportType">Registered Employees</strong>
                            </div>
                            <div class="col-6">
                                <span class="text-muted">Format:</span>
                            </div>
                            <div class="col-6">
                                <strong>Microsoft Excel (.xls)</strong>
                            </div>
                            <div class="col-6">
                                <span class="text-muted">Estimated Size:</span>
                            </div>
                            <div class="col-6">
                                <strong id="estimatedSize">~500 KB</strong>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="d-flex justify-content-between mt-4">
                    <button class="btn btn-outline-secondary px-4" onclick="closeExportOptionsModal()">
                        <i class="fas fa-times me-2"></i>Cancel
                    </button>
                    <button class="btn btn-success px-5" onclick="confirmExport()">
                        <i class="fas fa-check me-2"></i>Export Now
                    </button>
                </div>
                
                <div class="text-center mt-3">
                    <small class="text-muted">
                        <i class="fas fa-lock me-1"></i>
                        Your data is securely exported
                    </small>
                </div>
            </div>
        </div>
    </div>

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

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

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

    <!-- Navigation Bar -->
    <nav class="navbar navbar-expand-lg navbar-dark" style="background: linear-gradient(135deg, var(--education-blue) 0%, #0e2a4a 100%);">
        <div class="container-fluid">
            <a class="navbar-brand" href="#">
                <img src="images/logo.png" alt="AJ&K Education" style="border-radius: 50%; width: 50px; height: 50px; object-fit: cover;">
                <span class="ms-2 d-none d-md-inline fw-bold">AJ&K Education Department</span>
            </a>
            
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            
            <div class="collapse navbar-collapse" id="navbarNav">
                <?php if ($has_approval_access): ?>
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link position-relative emp-dashboard-approval-button" href="javascript:void(0)" onclick="empDashboardOpenRegistrationApprovalModal()">
                            <i class="fas fa-user-check me-2"></i> Registration Approvals
                            <span class="badge bg-danger ms-2" id="navRegistrationCount"><?php echo $pending_count; ?></span>
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link position-relative emp-dashboard-approval-button" href="javascript:void(0)" onclick="empDashboardOpenPasswordResetApprovalModal()">
                            <i class="fas fa-key me-2"></i> Password Reset
                            <span class="badge bg-warning ms-2" id="navPasswordResetCount"><?php echo $password_reset_count; ?></span>
                        </a>
                    </li>
                </ul>
                <?php endif; ?>
                
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle 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; border: 2px solid white;"
                                 alt="Profile"
                                 onerror="this.src='images/default_profile.png'">
                            <span class="d-none d-md-inline"><?php echo htmlspecialchars($employee['full_name'] ?? 'User'); ?></span>
                        </a>
                        <ul class="dropdown-menu dropdown-menu-end">
                            <li><a class="dropdown-item" href="employee_profile_view.php"><i class="fas fa-user me-2"></i> My Profile</a></li>
                            <li><a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#changePasswordModal"><i class="fas fa-key me-2"></i> Change Password</a></li>
                            <?php if ($has_approval_access): ?>
                            <li><hr class="dropdown-divider"></li>
                            <li>
                                <a class="dropdown-item" href="javascript:void(0)" onclick="empDashboardOpenRegistrationApprovalModal()">
                                    <i class="fas fa-user-check me-2"></i> Registration Approvals

                                    <span class="badge bg-danger ms-2" id="dropdownRegistrationCount"><?php echo $pending_count; ?></span>
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item" href="javascript:void(0)" onclick="empDashboardOpenPasswordResetApprovalModal()">
                                    <i class="fas fa-key me-2"></i> Password Reset
                                    <span class="badge bg-warning ms-2" id="dropdownPasswordResetCount"><?php echo $password_reset_count; ?></span>
                                </a>
                            </li>
                            <?php endif; ?>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item text-danger" href="?logout=1"><i class="fas fa-sign-out-alt me-2"></i> Logout</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <div class="col-md-3 col-lg-2 d-md-block emp-dashboard-sidebar p-0">
                <div class="position-sticky pt-3">
                    <div class="text-center p-3">
                        <img src="<?php echo htmlspecialchars($profile_pic); ?>" 
                             class="rounded-circle mb-2" 
                             style="width: 100px; height: 100px; object-fit: cover; border: 3px solid white;"
                             alt="Profile"
                             onerror="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'] ?? 'User'); ?></h6>
                        <small class="text-light"><?php echo htmlspecialchars($employee['role_name'] ?? 'Employee'); ?></small>
                    </div>
                    
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link active" href="employee_dashboard.php">
                                <i class="fas fa-tachometer-alt"></i> Dashboard
                            </a>
                        </li>
                        <?php if ($has_hr_access): ?>
                        <li class="nav-item"><a class="nav-link" href="#"><i class="fas fa-user-tie"></i> HR Management</a></li>
                        <?php endif; ?>
                        <?php if ($has_school_access): ?>
                        <li class="nav-item"><a class="nav-link" href="#"><i class="fas fa-school"></i> School Management</a></li>
                        <?php endif; ?>
                        <?php if ($has_student_access): ?>
                        <li class="nav-item"><a class="nav-link" href="#"><i class="fas fa-users"></i> Student Management</a></li>
                        <?php endif; ?>
                        <?php if ($has_finance_access): ?>
                        <li class="nav-item"><a class="nav-link" href="#"><i class="fas fa-money-bill-wave"></i> Finance</a></li>
                        <?php endif; ?>
                        <?php if ($has_teacher_portal_access): ?>
                        <li class="nav-item"><a class="nav-link" href="#"><i class="fas fa-chalkboard-teacher"></i> Teacher Portal</a></li>
                        <?php endif; ?>
                        <?php if ($has_reports_access): ?>
                        <li class="nav-item"><a class="nav-link" href="#"><i class="fas fa-chart-bar"></i> Reports</a></li>
                        <?php endif; ?>
                        <li class="nav-item"><a class="nav-link" href="#"><i class="fas fa-file-alt"></i> Documents</a></li>
                        <?php if ($has_announcements_access): ?>
                        <li class="nav-item"><a class="nav-link" href="#"><i class="fas fa-bullhorn"></i> Announcements</a></li>
                        <?php endif; ?>
                        <?php if ($has_approval_access): ?>
                            <?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
                                    <span class="badge bg-danger float-end" id="sidebarRegistrationCount"><?php echo $pending_count; ?></span>
                                </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
                                    <span class="badge bg-warning float-end" id="sidebarPasswordResetCount"><?php echo $password_reset_count; ?></span>
                                </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">
                <!-- Welcome Banner -->
                <div class="welcome-banner">
                    <div class="row align-items-center">
                        <div class="col-md-8">
                            <h2><i class="fas fa-hand-wave me-2"></i> Welcome back, <?php echo htmlspecialchars(explode(' ', $employee['full_name'] ?? 'User')[0]); ?>!</h2>
                            <p><?php echo date('l, F j, Y'); ?> • <span class="badge bg-light text-dark"><?php echo htmlspecialchars($employee['role_name'] ?? 'Employee'); ?></span></p>
                        </div>
                        <div class="col-md-4 text-md-end">
                            <i class="fas fa-graduation-cap" style="font-size: 3rem; opacity: 0.5;"></i>
                        </div>
                    </div>
                </div>
                
                <!-- Profile Completion Alert -->
                <?php if (!$profile_exists): ?>
                <div class="alert alert-warning alert-dismissible fade show" role="alert">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    <strong>Attention!</strong> Your profile is incomplete. Please complete your profile to access all system features.
                    <button type="button" class="btn btn-warning btn-sm ms-3" onclick="empDashboardRedirectToProfile()">
                        <i class="fas fa-user-edit me-1"></i>Complete Profile
                    </button>
                </div>
                <?php endif; ?>
                
                <!-- Pending Requests Alerts -->
                <?php if ($pending_count > 0 && $has_approval_access): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert" id="pendingRegistrationAlert">
                    <i class="fas fa-user-check me-2"></i>
                    <strong>Registration Approvals Pending!</strong> You have <span id="alertRegistrationCount"><?php echo $pending_count; ?></span> registration request(s) waiting for your approval.
                    <button type="button" class="btn btn-danger btn-sm ms-3" onclick="empDashboardOpenRegistrationApprovalModal()">
                        <i class="fas fa-external-link-alt me-1"></i>Review Now
                    </button>
                </div>
                <?php endif; ?>
                
                <?php if ($password_reset_count > 0 && $has_approval_access): ?>
                <div class="alert alert-warning alert-dismissible fade show" role="alert" id="pendingResetAlert">
                    <i class="fas fa-key me-2"></i>
                    <strong>Password Reset Requests Pending!</strong> You have <span id="alertResetCount"><?php echo $password_reset_count; ?></span> password reset request(s) waiting for your approval.
                    <button type="button" class="btn btn-warning btn-sm ms-3" onclick="empDashboardOpenPasswordResetApprovalModal()">
                        <i class="fas fa-external-link-alt me-1"></i>Review Now
                    </button>
                </div>
                <?php endif; ?>
                
                <!-- QUICK STATS SECTION -->
                <?php if ($show_quick_stats): ?>
                <div class="quick-stats-section">
                    <div class="section-header">
                        <div class="section-title">System Overview Dashboard</div>
                        <div class="section-icon"><i class="fas fa-chart-line"></i></div>
                    </div>
                    
                    <div class="row mb-4">
                        <div class="col-md-4 col-sm-6">
                            <div class="enhanced-stat-card" onclick="openRegisteredEmployeesModal()">
                                <div class="card-body">
                                    <div class="stat-icon-container primary">
                                        <i class="fas fa-users"></i>
                                    </div>
                                    <div class="stat-content">
                                        <div class="stat-value"><?php echo $stats['total_registered'] ?? 0; ?></div>
                                        <div class="stat-label">Registered Employees</div>
                                        <div class="stat-progress">
                                            <div class="stat-progress-bar" style="width: 100%"></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-4 col-sm-6">
                            <div class="enhanced-stat-card" onclick="openCompletedProfilesModal()">
                                <div class="card-body">
                                    <div class="stat-icon-container success">
                                        <i class="fas fa-user-check"></i>
                                    </div>
                                    <div class="stat-content">
                                        <div class="stat-value"><?php echo $stats['profiles_completed'] ?? 0; ?></div>
                                        <div class="stat-label">Profiles Completed</div>
                                        <div class="stat-progress">
                                            <div class="stat-progress-bar" style="width: <?php echo $stats['completion_percentage'] ?? 0; ?>%"></div>
                                        </div>
                                        <div class="stat-percentage">
                                            <span><?php echo $stats['completion_percentage'] ?? 0; ?>% complete</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-4 col-sm-6">
                            <div class="enhanced-stat-card" onclick="openPendingProfilesModal()">
                                <div class="card-body">
                                    <div class="stat-icon-container warning">
                                        <i class="fas fa-clock"></i>
                                    </div>
                                    <div class="stat-content">
                                        <div class="stat-value"><?php echo $stats['pending_profiles'] ?? 0; ?></div>
                                        <div class="stat-label">Pending Profiles</div>
                                        <div class="stat-progress">
                                            <div class="stat-progress-bar" style="width: <?php echo 100 - ($stats['completion_percentage'] ?? 0); ?>%"></div>
                                        </div>
                                        <div class="stat-percentage">
                                            <span><?php echo 100 - ($stats['completion_percentage'] ?? 0); ?>% pending</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
                
                <!-- Quick Actions -->
                <div class="quick-actions-wrapper">
                    <h5 class="mb-3"><i class="fas fa-bolt me-2" style="color: var(--education-blue);"></i>Quick Actions</h5>
                    <div class="quick-actions">
                        <?php if ($is_deo || $is_mis_admin): ?>
                            <button class="quick-action-btn" onclick="openRegisteredEmployeesModal()">
                                <i class="fas fa-users"></i> View All Employees
                            </button>
                        <?php endif; ?>
                        <?php if ($has_approval_access): ?>
                            <button class="quick-action-btn" onclick="empDashboardOpenRegistrationApprovalModal()">
                                <i class="fas fa-user-check"></i> Approvals (<span id="quickRegistrationCount"><?php echo $pending_count; ?></span>)
                            </button>
                            <button class="quick-action-btn" onclick="empDashboardOpenPasswordResetApprovalModal()">
                                <i class="fas fa-key"></i> Password Reset (<span id="quickResetCount"><?php echo $password_reset_count; ?></span>)
                            </button>
                        <?php endif; ?>
                        <button class="quick-action-btn" onclick="window.location.href='employee_profile_view.php'">
                            <i class="fas fa-user"></i> My Profile
                        </button>
                        <button class="quick-action-btn" data-bs-toggle="modal" data-bs-target="#changePasswordModal">
                            <i class="fas fa-key"></i> Change Password
                        </button>
                        <button class="quick-action-btn" onclick="location.reload()">
                            <i class="fas fa-sync-alt"></i> Refresh
                        </button>
                    </div>
                </div>
                
                <!-- Core Modules -->
                <div class="section-header mt-4">
                    <div class="section-title">Core System Modules</div>
                    <div class="section-icon"><i class="fas fa-cubes"></i></div>
                </div>
                
                <div class="row">
                    <?php if ($has_hr_access): ?>
                    <div class="col-lg-3 col-md-4 col-sm-6 mb-4">
                        <div class="smart-module-card">
                            <div class="card-body">
                                <span class="smart-module-badge">Admin</span>
                                <div class="smart-module-icon icon-blue">
                                    <i class="fas fa-user-tie"></i>
                                </div>
                                <h5 class="smart-module-title">HR Management</h5>
                                <p class="smart-module-desc">Manage employee records, transfers, promotions</p>
                                <button class="smart-module-btn" onclick="window.location.href='#'">
                                    <i class="fas fa-arrow-right"></i> Access Module
                                </button>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <?php if ($has_school_access): ?>
                    <div class="col-lg-3 col-md-4 col-sm-6 mb-4">
                        <div class="smart-module-card">
                            <div class="card-body">
                                <span class="smart-module-badge">Education</span>
                                <div class="smart-module-icon icon-green">
                                    <i class="fas fa-school"></i>
                                </div>
                                <h5 class="smart-module-title">School Management</h5>
                                <p class="smart-module-desc">Manage school information and resources</p>
                                <button class="smart-module-btn" onclick="window.location.href='#'">
                                    <i class="fas fa-arrow-right"></i> Access Module
                                </button>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <?php if ($has_student_access): ?>
                    <div class="col-lg-3 col-md-4 col-sm-6 mb-4">
                        <div class="smart-module-card">
                            <div class="card-body">
                                <span class="smart-module-badge">Academics</span>
                                <div class="smart-module-icon icon-teal">
                                    <i class="fas fa-users"></i>
                                </div>
                                <h5 class="smart-module-title">Student Management</h5>
                                <p class="smart-module-desc">Student records, attendance, enrollments</p>
                                <button class="smart-module-btn" onclick="window.location.href='#'">
                                    <i class="fas fa-arrow-right"></i> Access Module
                                </button>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <?php if ($has_finance_access): ?>
                    <div class="col-lg-3 col-md-4 col-sm-6 mb-4">
                        <div class="smart-module-card">
                            <div class="card-body">
                                <span class="smart-module-badge">Finance</span>
                                <div class="smart-module-icon icon-gold">
                                    <i class="fas fa-money-bill-wave"></i>
                                </div>
                                <h5 class="smart-module-title">Finance & Budget</h5>
                                <p class="smart-module-desc">Budget planning, expenditures, grants</p>
                                <button class="smart-module-btn" onclick="window.location.href='#'">
                                    <i class="fas fa-arrow-right"></i> Access Module
                                </button>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
                
                <!-- Approval Cards Section -->
                <?php if ($has_approval_access): ?>
                <div class="section-header mt-2">
                    <div class="section-title">Administration & Approvals</div>
                    <div class="section-icon"><i class="fas fa-shield-alt"></i></div>
                </div>
                
                <div class="row">
                    <div class="col-lg-3 col-md-4 col-sm-6 mb-4">
                        <div class="smart-module-card">
                            <div class="card-body">
                                <span class="smart-module-badge pending">Pending: <span id="cardRegistrationCount"><?php echo $pending_count; ?></span></span>
                                <div class="smart-module-icon icon-red">
                                    <i class="fas fa-user-check"></i>
                                </div>
                                <h5 class="smart-module-title">Registration Approvals</h5>
                                <p class="smart-module-desc">Review and approve new employee registrations</p>
                                <button class="smart-module-btn" onclick="empDashboardOpenRegistrationApprovalModal()">
                                    <i class="fas fa-check-circle"></i> Review (<span id="cardRegistrationCount2"><?php echo $pending_count; ?></span>)
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-lg-3 col-md-4 col-sm-6 mb-4">
                        <div class="smart-module-card">
                            <div class="card-body">
                                <span class="smart-module-badge pending">Pending: <span id="cardResetCount"><?php echo $password_reset_count; ?></span></span>
                                <div class="smart-module-icon icon-orange">
                                    <i class="fas fa-key"></i>
                                </div>
                                <h5 class="smart-module-title">Password Reset Requests</h5>
                                <p class="smart-module-desc">Approve or reject password reset requests</p>
                                <button class="smart-module-btn" onclick="empDashboardOpenPasswordResetApprovalModal()">
                                    <i class="fas fa-check-circle"></i> Review (<span id="cardResetCount2"><?php echo $password_reset_count; ?></span>)
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
                
                <!-- Recent Activities -->
                <div class="mt-5">
                    <div class="section-header">
                        <div class="section-title">Recent Activities</div>
                        <div class="section-icon"><i class="fas fa-history"></i></div>
                    </div>
                    <div class="card">
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-striped table-hover">
                                    <thead>
                                        <tr>
                                            <th>Date</th>
                                            <th>Activity</th>
                                            <th>Action</th>
                                            <th>Status</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr>
                                            <td><?php echo date('Y-m-d H:i'); ?></td>
                                            <td>Logged in to the system</td>
                                            <td>Login</td>
                                            <td><span class="badge bg-success">Success</span></td>
                                        </tr>
                                        <?php if ($pending_count > 0 && $has_approval_access): ?>
                                        <tr>
                                            <td><?php echo date('Y-m-d'); ?></td>
                                            <td>Registration approvals pending</td>
                                            <td>Registration Approval</td>
                                            <td><span class="badge bg-danger" id="activityRegistrationCount"><?php echo $pending_count; ?> Pending</span></td>
                                        </tr>
                                        <?php endif; ?>
                                        <?php if ($password_reset_count > 0 && $has_approval_access): ?>
                                        <tr>
                                            <td><?php echo date('Y-m-d'); ?></td>
                                            <td>Password reset requests pending</td>
                                            <td>Password Reset</td>
                                            <td><span class="badge bg-warning" id="activityResetCount"><?php echo $password_reset_count; ?> Pending</span></td>
                                        </tr>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>

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

    <!-- Change Password Modal -->
    <div class="modal fade" id="changePasswordModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><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">
                    <form method="POST" action="change_password_emp.php">
                        <div class="mb-3">
                            <label class="form-label">Current Password</label>
                            <input type="password" class="form-control" name="current_password" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">New Password</label>
                            <input type="password" class="form-control" name="new_password" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Confirm New Password</label>
                            <input type="password" class="form-control" name="confirm_password" required>
                        </div>
                        <div class="d-flex justify-content-between">
                            <button type="submit" class="btn btn-primary">Update Password</button>
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // ============ TOAST NOTIFICATION SYSTEM ============
        
        function showToast(message, type = 'success', title = '') {
            const toastContainer = document.getElementById('toastContainer');
            const toastId = 'toast-' + Date.now();
            
            const icons = {
                success: 'fa-check-circle',
                error: 'fa-exclamation-circle',
                warning: 'fa-exclamation-triangle',
                info: 'fa-info-circle'
            };
            
            const titles = {
                success: 'Success',
                error: 'Error',
                warning: 'Warning',
                info: 'Information'
            };
            
            const toastHTML = `
                <div id="${toastId}" class="toast-notification ${type}">
                    <div class="toast-header ${type}">
                        <i class="fas ${icons[type]} me-2"></i>
                        <strong class="me-auto">${title || titles[type]}</strong>
                        <button class="toast-close" onclick="document.getElementById('${toastId}').remove()">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                    <div class="toast-body">
                        ${message}
                    </div>
                </div>
            `;
            
            toastContainer.insertAdjacentHTML('beforeend', toastHTML);
            
            // Auto remove after 5 seconds
            setTimeout(() => {
                const toast = document.getElementById(toastId);
                if (toast) {
                    toast.style.animation = 'slideOut 0.5s ease-out forwards';
                    setTimeout(() => toast.remove(), 500);
                }
            }, 5000);
        }

        // ============ UPDATE COUNTS FUNCTION ============
        
        function updatePendingCounts(registrationCount, resetCount) {
            // Update all instances of registration counts
            const registrationElements = [
                'registrationCount', 'navRegistrationCount', 'dropdownRegistrationCount',
                'sidebarRegistrationCount', 'quickRegistrationCount', 'cardRegistrationCount',
                'cardRegistrationCount2', 'activityRegistrationCount', 'alertRegistrationCount'
            ];
            
            registrationElements.forEach(id => {
                const element = document.getElementById(id);
                if (element) element.textContent = registrationCount;
            });
            
            // Update all instances of reset counts
            const resetElements = [
                'passwordResetCount', 'navPasswordResetCount', 'dropdownPasswordResetCount',
                'sidebarPasswordResetCount', 'quickResetCount', 'cardResetCount',
                'cardResetCount2', 'activityResetCount', 'alertResetCount'
            ];
            
            resetElements.forEach(id => {
                const element = document.getElementById(id);
                if (element) element.textContent = resetCount;
            });
            
            // Hide alerts if counts are zero
            if (registrationCount == 0) {
                const alert = document.getElementById('pendingRegistrationAlert');
                if (alert) alert.style.display = 'none';
            }
            
            if (resetCount == 0) {
                const alert = document.getElementById('pendingResetAlert');
                if (alert) alert.style.display = 'none';
            }
        }

        // ============ PROFILE REDIRECT ============
        
        function empDashboardRedirectToProfile() {
            window.location.href = 'emp1.php';
        }

        // ============ REGISTRATION APPROVAL FUNCTIONS ============
        
        function empDashboardOpenRegistrationApprovalModal() {
            document.getElementById('registrationApprovalModal').style.display = 'flex';
            empDashboardLoadRegistrationRequests();
        }

        function empDashboardCloseRegistrationModal() {
            document.getElementById('registrationApprovalModal').style.display = 'none';
        }

        function empDashboardLoadRegistrationRequests() {
            document.getElementById('registrationLoadingSpinner').style.display = 'block';
            document.getElementById('registrationRequestsContent').innerHTML = '';
            
            fetch('employee_dashboard.php?get_pending=true&t=' + new Date().getTime())
                .then(response => response.text())
                .then(html => {
                    document.getElementById('registrationLoadingSpinner').style.display = 'none';
                    document.getElementById('registrationRequestsContent').innerHTML = html;
                })
                .catch(error => {
                    document.getElementById('registrationLoadingSpinner').style.display = 'none';
                    document.getElementById('registrationRequestsContent').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.</p>
                        </div>
                    `;
                });
        }

        function empDashboardApproveRegistration(registrationId) {
            if (!confirm('Are you sure you want to approve this registration?')) return;
            
            const roleSelect = document.querySelector(`.role-select[data-registration-id="${registrationId}"]`);
            const roleId = roleSelect ? roleSelect.value : null;
            
            const formData = new FormData();
            formData.append('action', 'process_approval');
            formData.append('registration_id', registrationId);
            formData.append('action_type', 'approve');
            if (roleId) formData.append('role_id', roleId);
            
            fetch('employee_dashboard.php', { 
                method: 'POST', 
                body: formData 
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showToast('✓ Registration approved successfully', 'success');
                        if (data.new_pending_count !== undefined) {
                            updatePendingCounts(data.new_pending_count, data.new_reset_count);
                        }
                        empDashboardLoadRegistrationRequests();
                    } else {
                        showToast('Error: ' + data.message, 'error');
                    }
                })
                .catch(error => {
                    showToast('Error processing approval', 'error');
                });
        }

        function empDashboardRejectRegistration(registrationId) {
            if (!confirm('Are you sure you want to reject and delete this registration?')) return;
            
            const formData = new FormData();
            formData.append('action', 'process_approval');
            formData.append('registration_id', registrationId);
            formData.append('action_type', 'reject');
            
            fetch('employee_dashboard.php', { 
                method: 'POST', 
                body: formData 
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showToast('✓ Registration rejected and deleted', 'success');
                        if (data.new_pending_count !== undefined) {
                            updatePendingCounts(data.new_pending_count, data.new_reset_count);
                        }
                        empDashboardLoadRegistrationRequests();
                    } else {
                        showToast('Error: ' + data.message, 'error');
                    }
                })
                .catch(error => {
                    showToast('Error processing rejection', 'error');
                });
        }

        // ============ PASSWORD RESET APPROVAL FUNCTIONS ============
        
        function empDashboardOpenPasswordResetApprovalModal() {
            document.getElementById('passwordResetApprovalModal').style.display = 'flex';
            empDashboardLoadPasswordResetRequests();
        }

        function empDashboardClosePasswordResetModal() {
            document.getElementById('passwordResetApprovalModal').style.display = 'none';
        }

        function empDashboardLoadPasswordResetRequests() {
            document.getElementById('passwordResetLoadingSpinner').style.display = 'block';
            document.getElementById('passwordResetRequestsContent').innerHTML = '';
            
            fetch('employee_dashboard.php?get_password_reset=true&t=' + new Date().getTime())
                .then(response => response.text())
                .then(html => {
                    document.getElementById('passwordResetLoadingSpinner').style.display = 'none';
                    document.getElementById('passwordResetRequestsContent').innerHTML = html;
                })
                .catch(error => {
                    document.getElementById('passwordResetLoadingSpinner').style.display = 'none';
                    document.getElementById('passwordResetRequestsContent').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.</p>
                        </div>
                    `;
                });
        }

        function empDashboardApprovePasswordReset(requestId) {
            if (!confirm('Are you sure you want to approve this password reset?')) return;
            
            const formData = new FormData();
            formData.append('password_action', 'process_password_reset');
            formData.append('request_id', requestId);
            formData.append('action_type', 'approve_reset');
            
            fetch('employee_dashboard.php', { 
                method: 'POST', 
                body: formData 
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showToast('✓ Password reset approved successfully', 'success');
                        if (data.new_reset_count !== undefined) {
                            updatePendingCounts(data.new_pending_count, data.new_reset_count);
                        }
                        empDashboardLoadPasswordResetRequests();
                    } else {
                        showToast('Error: ' + data.message, 'error');
                    }
                })
                .catch(error => {
                    showToast('Error processing approval', 'error');
                });
        }

        function empDashboardRejectPasswordReset(requestId) {
            if (!confirm('Are you sure you want to reject this password reset request?')) return;
            
            const formData = new FormData();
            formData.append('password_action', 'process_password_reset');
            formData.append('request_id', requestId);
            formData.append('action_type', 'reject_reset');
            
            fetch('employee_dashboard.php', { 
                method: 'POST', 
                body: formData 
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showToast('✓ Password reset request rejected', 'success');
                        if (data.new_reset_count !== undefined) {
                            updatePendingCounts(data.new_pending_count, data.new_reset_count);
                        }
                        empDashboardLoadPasswordResetRequests();
                    } else {
                        showToast('Error: ' + data.message, 'error');
                    }
                })
                .catch(error => {
                    showToast('Error processing rejection', 'error');
                });
        }

        // ============ BULK REGISTRATION FUNCTIONS ============
        
        function toggleAllRegistrationCheckboxes(checked) {
            document.querySelectorAll('.registration-checkbox').forEach(cb => cb.checked = checked);
        }

        function selectAllRegistrationRows() {
            const checkboxes = document.querySelectorAll('.registration-checkbox');
            const allChecked = Array.from(checkboxes).every(cb => cb.checked);
            checkboxes.forEach(cb => cb.checked = !allChecked);
            const selectAll = document.getElementById('selectAllRegistration');
            if (selectAll) selectAll.checked = !allChecked;
        }

        function bulkApproveRegistrations() {
            const checkboxes = document.querySelectorAll('.registration-checkbox:checked');
            if (checkboxes.length === 0) {
                showToast('Please select at least one registration to approve.', 'warning');
                return;
            }
            
            if (!confirm(`Approve ${checkboxes.length} selected registration(s)?`)) return;

            const registrationIds = [];
            const roleIds = {};
            
            checkboxes.forEach(cb => {
                const id = cb.value;
                registrationIds.push(id);
                const select = document.querySelector(`.role-select[data-registration-id="${id}"]`);
                if (select) roleIds[id] = select.value;
            });
            
            const formData = new FormData();
            formData.append('bulk_action', 'bulk_approve_registrations');
            formData.append('registration_ids', JSON.stringify(registrationIds));
            formData.append('role_ids', JSON.stringify(roleIds));
            
            fetch('employee_dashboard.php', { 
                method: 'POST', 
                body: formData 
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showToast(`✓ Successfully approved ${data.success_count} registration(s)`, 'success');
                        if (data.new_pending_count !== undefined) {
                            updatePendingCounts(data.new_pending_count, data.new_reset_count);
                        }
                        empDashboardLoadRegistrationRequests();
                    } else {
                        showToast('Error: ' + data.message, 'error');
                    }
                })
                .catch(error => {
                    showToast('Error processing bulk approval', 'error');
                });
        }

        // ============ BULK PASSWORD RESET FUNCTIONS ============
        
        function toggleAllPasswordResetCheckboxes(checked) {
            document.querySelectorAll('.password-reset-checkbox').forEach(cb => cb.checked = checked);
        }

        function selectAllPasswordResetRows() {
            const checkboxes = document.querySelectorAll('.password-reset-checkbox');
            const allChecked = Array.from(checkboxes).every(cb => cb.checked);
            checkboxes.forEach(cb => cb.checked = !allChecked);
            const selectAll = document.getElementById('selectAllPasswordReset');
            if (selectAll) selectAll.checked = !allChecked;
        }

        function bulkApprovePasswordResets() {
            const checkboxes = document.querySelectorAll('.password-reset-checkbox:checked');
            if (checkboxes.length === 0) {
                showToast('Please select at least one password reset request.', 'warning');
                return;
            }
            
            if (!confirm(`Approve ${checkboxes.length} selected request(s)?`)) return;
            
            const requestIds = [];
            checkboxes.forEach(cb => requestIds.push(cb.value));
            
            const formData = new FormData();
            formData.append('bulk_action', 'bulk_approve_password_resets');
            formData.append('request_ids', JSON.stringify(requestIds));
            
            fetch('employee_dashboard.php', { 
                method: 'POST', 
                body: formData 
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showToast(`✓ Successfully approved ${data.success_count} password reset(s)`, 'success');
                        if (data.new_reset_count !== undefined) {
                            updatePendingCounts(data.new_pending_count, data.new_reset_count);
                        }
                        empDashboardLoadPasswordResetRequests();
                    } else {
                        showToast('Error: ' + data.message, 'error');
                    }
                })
                .catch(error => {
                    showToast('Error processing bulk approval', 'error');
                });
        }

        // ============ EXPORT FUNCTIONS WITH PAGE RANGE ============

        let currentExportType = 'registered';
        let totalPages = 1;

        // Calculate total pages based on data
        function calculateTotalPages(type) {
            const itemsPerPage = 50;
            
            <?php if ($is_deo || $is_mis_admin): ?>
            if (type === 'registered') {
                return Math.ceil(<?php echo count($all_employees ?? []); ?> / itemsPerPage) || 1;
            } else if (type === 'completed') {
                return Math.ceil(<?php echo count($all_completed_profiles ?? []); ?> / itemsPerPage) || 1;
            } else if (type === 'pending') {
                return Math.ceil(<?php echo count($all_pending_profiles ?? []); ?> / itemsPerPage) || 1;
            }
            <?php endif; ?>
            
            return 1;
        }

        // Update summary when type changes
        function updateExportSummary(type) {
            const titles = {
                'registered': 'Registered Employees',
                'completed': 'Completed Profiles', 
                'pending': 'Pending Profiles'
            };
            document.getElementById('summaryExportType').textContent = titles[type];
            
            <?php if ($is_deo || $is_mis_admin): ?>
            let count = 0;
            if (type === 'registered') count = <?php echo count($all_employees ?? []); ?>;
            else if (type === 'completed') count = <?php echo count($all_completed_profiles ?? []); ?>;
            else if (type === 'pending') count = <?php echo count($all_pending_profiles ?? []); ?>;
            
            const estimatedSize = Math.ceil(count * 0.5) + ' KB';
            document.getElementById('estimatedSize').textContent = '~' + estimatedSize;
            <?php endif; ?>
        }

        function showExportOptions(type) {
            currentExportType = type;
            
            // Calculate total pages
            totalPages = calculateTotalPages(type);
            
            // Set title based on type
            const titles = {
                'registered': 'Export Registered Employees',
                'completed': 'Export Completed Profiles',
                'pending': 'Export Pending Profiles'
            };
            document.getElementById('exportModalTitle').textContent = titles[type];
            
            // Update summary
            updateExportSummary(type);
            
            // Update total pages info
            document.getElementById('totalPagesInfo').textContent = totalPages;
            document.getElementById('maxPageEnd').textContent = totalPages;
            
            // Set max values for range inputs
            document.getElementById('pageStart').max = totalPages;
            document.getElementById('pageEnd').max = totalPages;
            document.getElementById('pageEnd').value = totalPages;
            
            // Reset range inputs
            document.getElementById('pageStart').value = 1;
            document.getElementById('pageEnd').value = totalPages;
            
            // Show the modal with higher z-index
            const modal = document.getElementById('exportOptionsModal');
            modal.style.display = 'flex';
            modal.style.zIndex = '9999';
        }

        function closeExportOptionsModal() {
            document.getElementById('exportOptionsModal').style.display = 'none';
        }

        function validatePageRange() {
            const start = parseInt(document.getElementById('pageStart').value) || 1;
            const end = parseInt(document.getElementById('pageEnd').value) || totalPages;
            
            if (start < 1) document.getElementById('pageStart').value = 1;
            if (end > totalPages) document.getElementById('pageEnd').value = totalPages;
            if (start > end) document.getElementById('pageEnd').value = start;
        }

        function confirmExport() {
            const exportAll = document.getElementById('exportAllPages').checked;
            const exportRange = document.getElementById('exportPageRange').checked;
            
            let pageParam = 'all';
            
            if (exportRange) {
                const start = parseInt(document.getElementById('pageStart').value) || 1;
                const end = parseInt(document.getElementById('pageEnd').value) || totalPages;
                
                if (start < 1 || end > totalPages || start > end) {
                    showToast('Please enter a valid page range (1-' + totalPages + ')', 'warning');
                    return;
                }
                
                pageParam = `range:${start}-${end}`;
            }
            
            // Show confirmation toast
            showToast(`Preparing export of ${currentExportType} data...`, 'info', 'Export Started');
            
            // Redirect to export with page range parameter
            window.location.href = `employee_dashboard.php?export_excel=${currentExportType}&pages=${pageParam}&t=${new Date().getTime()}`;
            
            // Close modal after a short delay
            setTimeout(() => {
                closeExportOptionsModal();
            }, 500);
        }

        // Enable/disable range inputs based on radio selection
        document.addEventListener('DOMContentLoaded', function() {
            const exportAllRadio = document.getElementById('exportAllPages');
            const exportRangeRadio = document.getElementById('exportPageRange');
            const pageStart = document.getElementById('pageStart');
            const pageEnd = document.getElementById('pageEnd');
            
            if (exportAllRadio && exportRangeRadio && pageStart && pageEnd) {
                exportAllRadio.addEventListener('change', function() {
                    pageStart.disabled = true;
                    pageEnd.disabled = true;
                });
                
                exportRangeRadio.addEventListener('change', function() {
                    pageStart.disabled = false;
                    pageEnd.disabled = false;
                });
            }
        });

        // ============ QUICK STATS FUNCTIONS ============
        
        <?php if ($is_deo || $is_mis_admin): ?>
        
        function openRegisteredEmployeesModal() {
            const modal = document.getElementById('registeredEmployeesModal');
            const content = document.getElementById('registeredEmployeesContent');
            modal.style.display = 'flex';
            content.innerHTML = '<div class="emp-dashboard-loading-spinner" style="display:block;"><div class="emp-dashboard-spinner-border"></div><p class="mt-3">Loading...</p></div>';
            
            fetch('employee_dashboard.php?get_registered_employees=true&t=' + new Date().getTime())
                .then(response => response.text())
                .then(html => content.innerHTML = html)
                .catch(() => {
                    content.innerHTML = '<div class="emp-dashboard-no-pending"><i class="fas fa-exclamation-triangle"></i><h5>Error</h5><p>Unable to load data.</p></div>';
                    showToast('Error loading registered employees', 'error');
                });
        }

        function openCompletedProfilesModal() {
            const modal = document.getElementById('completedProfilesModal');
            const content = document.getElementById('completedProfilesContent');
            modal.style.display = 'flex';
            content.innerHTML = '<div class="emp-dashboard-loading-spinner" style="display:block;"><div class="emp-dashboard-spinner-border"></div><p class="mt-3">Loading...</p></div>';
            
            fetch('employee_dashboard.php?get_completed_profiles=true&t=' + new Date().getTime())
                .then(response => response.text())
                .then(html => content.innerHTML = html)
                .catch(() => {
                    content.innerHTML = '<div class="emp-dashboard-no-pending"><i class="fas fa-exclamation-triangle"></i><h5>Error</h5><p>Unable to load data.</p></div>';
                    showToast('Error loading completed profiles', 'error');
                });
        }

        function openPendingProfilesModal() {
            const modal = document.getElementById('pendingProfilesModal');
            const content = document.getElementById('pendingProfilesContent');
            modal.style.display = 'flex';
            content.innerHTML = '<div class="emp-dashboard-loading-spinner" style="display:block;"><div class="emp-dashboard-spinner-border"></div><p class="mt-3">Loading...</p></div>';
            
            fetch('employee_dashboard.php?get_pending_profiles=true&t=' + new Date().getTime())
                .then(response => response.text())
                .then(html => content.innerHTML = html)
                .catch(() => {
                    content.innerHTML = '<div class="emp-dashboard-no-pending"><i class="fas fa-exclamation-triangle"></i><h5>Error</h5><p>Unable to load data.</p></div>';
                    showToast('Error loading pending profiles', 'error');
                });
        }

        function closeRegisteredEmployeesModal() {
            document.getElementById('registeredEmployeesModal').style.display = 'none';
        }

        function closeCompletedProfilesModal() {
            document.getElementById('completedProfilesModal').style.display = 'none';
        }

        function closePendingProfilesModal() {
            document.getElementById('pendingProfilesModal').style.display = 'none';
        }

        // ============ PRINT FUNCTIONS - PROFESSIONAL ============
        
        function printRegisteredEmployees() {
            const content = document.getElementById('registeredEmployeesContent').innerHTML;
            const printWindow = window.open('', '_blank');
            printWindow.document.write(`
                <html>
                <head>
                    <title>Registered Employees - AJ&K Education Department</title>
                    <style>
                        body {
                            font-family: Arial, sans-serif;
                            line-height: 1.6;
                            color: #333;
                            margin: 0;
                            padding: 20px;
                        }
                        .print-header {
                            text-align: center;
                            margin-bottom: 30px;
                            padding-bottom: 20px;
                            border-bottom: 2px solid #1a3e72;
                        }
                        .print-header h1 {
                            color: #1a3e72;
                            font-size: 24px;
                            margin-bottom: 5px;
                        }
                        .print-header h2 {
                            color: #666;
                            font-size: 18px;
                            margin-top: 0;
                            font-weight: normal;
                        }
                        .print-header p {
                            color: #999;
                            font-size: 12px;
                        }
                        table {
                            width: 100%;
                            border-collapse: collapse;
                            margin-top: 20px;
                        }
                        th {
                            background-color: #1a3e72;
                            color: white;
                            padding: 12px;
                            text-align: left;
                            font-size: 12px;
                            text-transform: uppercase;
                            letter-spacing: 0.5px;
                        }
                        td {
                            padding: 10px;
                            border-bottom: 1px solid #ddd;
                            font-size: 11px;
                        }
                        tr:nth-child(even) {
                            background-color: #f9f9f9;
                        }
                        .badge {
                            padding: 3px 8px;
                            border-radius: 3px;
                            font-size: 10px;
                            font-weight: bold;
                        }
                        .badge-success {
                            background-color: #28a745;
                            color: white;
                        }
                        .badge-warning {
                            background-color: #ffc107;
                            color: #212529;
                        }
                        .badge-info {
                            background-color: #17a2b8;
                            color: white;
                        }
                        .print-footer {
                            position: fixed;
                            bottom: 0;
                            left: 0;
                            right: 0;
                            text-align: center;
                            font-size: 10px;
                            color: #666;
                            padding: 10px;
                            border-top: 1px solid #ddd;
                        }
						  /* Hide only interactive elements, preserve table structure */
                button, .btn, .emp-dashboard-btn-action, [onclick] {
                    display: none !important;
                }
                /* Ensure table headers are visible */
                thead th {
                    display: table-cell !important;
                }
                        @page {
                            margin: 2cm;
                        }
                    </style>
                </head>
                <body>
                    <div class="print-header">
                        <h1>AJ&K Education Department District Kotli</h1>
                        <h2>Registered Employees List</h2>
                        <p>Generated on: <?php echo date('F j, Y, g:i a'); ?></p>
                    </div>
                    ${content}
                    <div class="print-footer">
                        Designed by Wajid Muzaffar (Computer Instructor) | AJ&K Education Department District Kotli | © <?php echo date('Y'); ?>
                    </div>
                </body>
                </html>
            `);
            printWindow.document.close();
            printWindow.print();
        }

        function printCompletedProfiles() {
            const content = document.getElementById('completedProfilesContent').innerHTML;
            const printWindow = window.open('', '_blank');
            printWindow.document.write(`
                <html>
                <head>
                    <title>Completed Profiles - AJ&K Education Department</title>
                    <style>
                        body {
                            font-family: Arial, sans-serif;
                            line-height: 1.6;
                            color: #333;
                            margin: 0;
                            padding: 20px;
                        }
                        .print-header {
                            text-align: center;
                            margin-bottom: 30px;
                            padding-bottom: 20px;
                            border-bottom: 2px solid #1a3e72;
                        }
                        .print-header h1 {
                            color: #1a3e72;
                            font-size: 24px;
                            margin-bottom: 5px;
                        }
                        .print-header h2 {
                            color: #666;
                            font-size: 18px;
                            margin-top: 0;
                            font-weight: normal;
                        }
                        .print-header p {
                            color: #999;
                            font-size: 12px;
                        }
                        table {
                            width: 100%;
                            border-collapse: collapse;
                            margin-top: 20px;
                        }
                        th {
                            background-color: #28a745;
                            color: white;
                            padding: 12px;
                            text-align: left;
                            font-size: 12px;
                            text-transform: uppercase;
                            letter-spacing: 0.5px;
                        }
                        td {
                            padding: 10px;
                            border-bottom: 1px solid #ddd;
                            font-size: 11px;
                        }
                        tr:nth-child(even) {
                            background-color: #f9f9f9;
                        }
                        .badge {
                            padding: 3px 8px;
                            border-radius: 3px;
                            font-size: 10px;
                            font-weight: bold;
                        }
                        .badge-info {
                            background-color: #17a2b8;
                            color: white;
                        }
                        .print-footer {
                            position: fixed;
                            bottom: 0;
                            left: 0;
                            right: 0;
                            text-align: center;
                            font-size: 10px;
                            color: #666;
                            padding: 10px;
                            border-top: 1px solid #ddd;
                        }
						/* Hide only interactive elements, preserve table structure */
                button, .btn, .emp-dashboard-btn-action, [onclick] {
                    display: none !important;
                }
                /* Ensure table headers are visible */
                thead th {
                    display: table-cell !important;
                }
                        @page {
                            margin: 2cm;
                        }
                    </style>
                </head>
                <body>
                    <div class="print-header">
                        <h1>AJ&K Education Department District Kotli</h1>
                        <h2>Completed Profiles List</h2>
                        <p>Generated on: <?php echo date('F j, Y, g:i a'); ?></p>
                    </div>
                    ${content}
                    <div class="print-footer">
                        Designed by Wajid Muzaffar (Computer Instructor) | AJ&K Education Department District Kotli | © <?php echo date('Y'); ?>
                    </div>
                </body>
                </html>
            `);
            printWindow.document.close();
            printWindow.print();
        }

        function printPendingProfiles() {
            const content = document.getElementById('pendingProfilesContent').innerHTML;
            const printWindow = window.open('', '_blank');
            printWindow.document.write(`
                <html>
                <head>
                    <title>Pending Profiles - AJ&K Education Department</title>
                    <style>
                        body {
                            font-family: Arial, sans-serif;
                            line-height: 1.6;
                            color: #333;
                            margin: 0;
                            padding: 20px;
                        }
                        .print-header {
                            text-align: center;
                            margin-bottom: 30px;
                            padding-bottom: 20px;
                            border-bottom: 2px solid #1a3e72;
                        }
                        .print-header h1 {
                            color: #1a3e72;
                            font-size: 24px;
                            margin-bottom: 5px;
                        }
                        .print-header h2 {
                            color: #666;
                            font-size: 18px;
                            margin-top: 0;
                            font-weight: normal;
                        }
                        .print-header p {
                            color: #999;
                            font-size: 12px;
                        }
                        table {
                            width: 100%;
                            border-collapse: collapse;
                            margin-top: 20px;
                        }
                        th {
                            background-color: #ffc107;
                            color: #212529;
                            padding: 12px;
                            text-align: left;
                            font-size: 12px;
                            text-transform: uppercase;
                            letter-spacing: 0.5px;
                        }
                        td {
                            padding: 10px;
                            border-bottom: 1px solid #ddd;
                            font-size: 11px;
                        }
                        tr:nth-child(even) {
                            background-color: #f9f9f9;
                        }
                        .badge {
                            padding: 3px 8px;
                            border-radius: 3px;
                            font-size: 10px;
                            font-weight: bold;
                        }
                        .badge-info {
                            background-color: #17a2b8;
                            color: white;
                        }
                        .print-footer {
                            position: fixed;
                            bottom: 0;
                            left: 0;
                            right: 0;
                            text-align: center;
                            font-size: 10px;
                            color: #666;
                            padding: 10px;
                            border-top: 1px solid #ddd;
                        }
						/* Hide only interactive elements, preserve table structure */
                button, .btn, .emp-dashboard-btn-action, [onclick] {
                    display: none !important;
                }
                /* Ensure table headers are visible */
                thead th {
                    display: table-cell !important;
                }
                        @page {
                            margin: 2cm;
                        }
                    </style>
                </head>
                <body>
                    <div class="print-header">
                        <h1>AJ&K Education Department District Kotli</h1>
                        <h2>Pending Profiles List</h2>
                        <p>Generated on: <?php echo date('F j, Y, g:i a'); ?></p>
                    </div>
                    ${content}
                    <div class="print-footer">
                        Designed by Wajid Muzaffar (Computer Instructor) | AJ&K Education Department District Kotli | © <?php echo date('Y'); ?>
                    </div>
                </body>
                </html>
            `);
            printWindow.document.close();
            printWindow.print();
        }

        <?php endif; ?>

        // ============ MODAL CLOSE LISTENERS ============
        
        document.addEventListener('DOMContentLoaded', function() {
            document.getElementById('closeRegistrationModal')?.addEventListener('click', empDashboardCloseRegistrationModal);
            document.getElementById('closePasswordResetModal')?.addEventListener('click', empDashboardClosePasswordResetModal);
            
            // Close modals when clicking outside
            const modals = ['registrationApprovalModal', 'passwordResetApprovalModal', 'registeredEmployeesModal', 'completedProfilesModal', 'pendingProfilesModal', 'exportOptionsModal'];
            modals.forEach(modalId => {
                const modal = document.getElementById(modalId);
                if (modal) {
                    modal.addEventListener('click', function(e) {
                        if (e.target === this) {
                            this.style.display = 'none';
                        }
                    });
                }
            });
            
            // Close modals with Escape key
            document.addEventListener('keydown', function(e) {
                if (e.key === 'Escape') {
                    modals.forEach(modalId => {
                        const modal = document.getElementById(modalId);
                        if (modal && modal.style.display === 'flex') {
                            modal.style.display = 'none';
                        }
                    });
                }
            });
            
            // Initialize counts
            updatePendingCounts(<?php echo $pending_count; ?>, <?php echo $password_reset_count; ?>);
        });
    </script>
</body>
</html>