<?php
/**
 * HR Management Page for AJ&K Education Department
 * File: hr_management.php
 */

// Start session and check authentication
require_once 'session_config_emp.php';

// Check for logout first
if (isset($_GET['logout'])) {
    session_destroy();
    setcookie('remember_employee', '', time() - 3600, "/");
    header("Location: login_emp.php");
    exit();
}

// Check if user is logged in
if (!isset($_SESSION['employee_id']) && !isset($_SESSION['cnic'])) {
    header("Location: login_emp.php");
    exit();
}

// Database connection
include_once 'connect.php';

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Get user role and permissions
$user_role = $_SESSION['employee_data']['role_id'] ?? 6;
$is_secretary = ($user_role == 1);
$is_deo = ($user_role == 2);
$is_mis_admin = ($user_role == 7);
$has_hr_access = ($is_secretary || $is_deo || $is_mis_admin);

// Redirect if no HR access
if (!$has_hr_access) {
    header("Location: employee_dashboard.php?error=access_denied");
    exit();
}

// Function to get table columns
function getTableColumns($conn, $table) {
    $columns = [];
    $result = $conn->query("SHOW COLUMNS FROM $table");
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $columns[] = $row['Field'];
        }
    }
    return $columns;
}

// Get employees table columns
$emp_columns = getTableColumns($conn, 'employees');

// Check if designations table exists
$designations_exist = $conn->query("SHOW TABLES LIKE 'designations'")->num_rows > 0;
$designation_columns = $designations_exist ? getTableColumns($conn, 'designations') : [];

// Check if school_emis table exists
$schools_exist = $conn->query("SHOW TABLES LIKE 'school_emis'")->num_rows > 0;
$school_columns = $schools_exist ? getTableColumns($conn, 'school_emis') : [];

// Determine the designation column in employees table
$emp_designation_col = null;
$possible_desig_cols = ['current_designation_id', 'designation_id', 'des_id', 'designationid', 'designation'];
foreach ($possible_desig_cols as $col) {
    if (in_array($col, $emp_columns)) {
        $emp_designation_col = $col;
        break;
    }
}

// Determine the school column in employees table
$emp_school_col = null;
$possible_school_cols = ['current_school_emis', 'school_emis', 'school_code', 'emis_code', 'school_id', 'school'];
foreach ($possible_school_cols as $col) {
    if (in_array($col, $emp_columns)) {
        $emp_school_col = $col;
        break;
    }
}

// Determine the mobile/contact column in employees table
$emp_mobile_col = null;
$possible_mobile_cols = ['mobile_no', 'contact_no', 'phone_no', 'phone', 'contact', 'mobile'];
foreach ($possible_mobile_cols as $col) {
    if (in_array($col, $emp_columns)) {
        $emp_mobile_col = $col;
        break;
    }
}

// Determine designation table columns
$desig_id_col = 'id';
$desig_name_col = 'name';
if ($designations_exist) {
    if (in_array('des_id', $designation_columns)) $desig_id_col = 'des_id';
    elseif (in_array('designation_id', $designation_columns)) $desig_id_col = 'designation_id';
    elseif (in_array('id', $designation_columns)) $desig_id_col = 'id';
    
    if (in_array('designation_name', $designation_columns)) $desig_name_col = 'designation_name';
    elseif (in_array('des_name', $designation_columns)) $desig_name_col = 'des_name';
    elseif (in_array('name', $designation_columns)) $desig_name_col = 'name';
    elseif (in_array('title', $designation_columns)) $desig_name_col = 'title';
}

// Determine school table columns
$school_id_col = 'id';
$school_name_col = 'name';
if ($schools_exist) {
    if (in_array('emis_code', $school_columns)) $school_id_col = 'emis_code';
    elseif (in_array('school_code', $school_columns)) $school_id_col = 'school_code';
    elseif (in_array('code', $school_columns)) $school_id_col = 'code';
    elseif (in_array('id', $school_columns)) $school_id_col = 'id';
    
    if (in_array('school_name', $school_columns)) $school_name_col = 'school_name';
    elseif (in_array('name', $school_columns)) $school_name_col = 'name';
    elseif (in_array('school', $school_columns)) $school_name_col = 'school';
}

// Handle AJAX requests
if (isset($_GET['ajax_action'])) {
    header('Content-Type: application/json');
    $response = ['success' => false, 'message' => '', 'data' => null];
    
    try {
        if ($_GET['ajax_action'] == 'get_designation_stats') {
            // Get designation-wise employee counts
            $stats = [];
            
            if ($designations_exist && $emp_designation_col) {
                $query = "SELECT d.$desig_name_col as designation, COUNT(e.employee_id) as count 
                         FROM employees e 
                         LEFT JOIN designations d ON e.$emp_designation_col = d.$desig_id_col 
                         GROUP BY d.$desig_name_col 
                         ORDER BY count DESC";
                
                $result = $conn->query($query);
                if ($result) {
                    while ($row = $result->fetch_assoc()) {
                        $stats[] = [
                            'designation' => $row['designation'] ?? 'Not Assigned',
                            'count' => (int)$row['count']
                        ];
                    }
                }
            } else {
                // Fallback if no designation table
                $stats[] = ['designation' => 'No Designation Data', 'count' => 1];
            }
            
            $response['success'] = true;
            $response['data'] = $stats;
        }
        
        elseif ($_GET['ajax_action'] == 'search_employees') {
            $search = $_GET['search'] ?? '';
            $search_param = "%$search%";
            
            // Build query with proper joins
            $query = "SELECT e.employee_id, e.full_name, e.personal_no, e.cnic";
            
            // Add designation name
            if ($designations_exist && $emp_designation_col) {
                $query .= ", d.$desig_name_col as designation_name";
            } else {
                $query .= ", NULL as designation_name";
            }
            
            // Add school name
            if ($schools_exist && $emp_school_col) {
                $query .= ", sch.$school_name_col as school_name";
            } else {
                $query .= ", NULL as school_name";
            }
            
            // Add mobile if exists
            if ($emp_mobile_col) {
                $query .= ", e.$emp_mobile_col as mobile_no";
            } else {
                $query .= ", NULL as mobile_no";
            }
            
            $query .= " FROM employees e";
            
            // Add joins
            if ($designations_exist && $emp_designation_col) {
                $query .= " LEFT JOIN designations d ON e.$emp_designation_col = d.$desig_id_col";
            }
            
            if ($schools_exist && $emp_school_col) {
                $query .= " LEFT JOIN school_emis sch ON e.$emp_school_col = sch.$school_id_col";
            }
            
            // Add search conditions
            $where = [];
            $params = [];
            $types = "";
            
            if (!empty($search)) {
                $where[] = "e.full_name LIKE ?";
                $params[] = $search_param;
                $types .= "s";
                
                $where[] = "e.personal_no LIKE ?";
                $params[] = $search_param;
                $types .= "s";
                
                $where[] = "e.cnic LIKE ?";
                $params[] = $search_param;
                $types .= "s";
                
                if ($schools_exist && $school_name_col) {
                    $where[] = "sch.$school_name_col LIKE ?";
                    $params[] = $search_param;
                    $types .= "s";
                }
                
                // Search by designation name
                if ($designations_exist && $desig_name_col) {
                    $where[] = "d.$desig_name_col LIKE ?";
                    $params[] = $search_param;
                    $types .= "s";
                }
            }
            
            if (!empty($where)) {
                $query .= " WHERE " . implode(" OR ", $where);
            }
            
            $query .= " ORDER BY e.full_name LIMIT 50";
            
            $stmt = $conn->prepare($query);
            if ($stmt) {
                if (!empty($params)) {
                    $stmt->bind_param($types, ...$params);
                }
                $stmt->execute();
                $result = $stmt->get_result();
                
                $employees = [];
                while ($row = $result->fetch_assoc()) {
                    $employees[] = $row;
                }
                
                $response['success'] = true;
                $response['data'] = $employees;
                $response['message'] = count($employees) . ' employees found';
                $stmt->close();
            } else {
                $response['message'] = 'Query preparation failed: ' . $conn->error;
            }
        }
        
        elseif ($_GET['ajax_action'] == 'get_stats') {
            $stats = [];
            
            // Total employees
            $result = $conn->query("SELECT COUNT(*) as total FROM employees");
            $stats['total_employees'] = $result->fetch_assoc()['total'];
            
            // Gender distribution
            if (in_array('gender', $emp_columns)) {
                $result = $conn->query("SELECT gender, COUNT(*) as count FROM employees WHERE gender IS NOT NULL GROUP BY gender");
                $stats['gender'] = ['Male' => 0, 'Female' => 0];
                while ($row = $result->fetch_assoc()) {
                    $stats['gender'][$row['gender']] = $row['count'];
                }
            } else {
                $stats['gender'] = ['Male' => 0, 'Female' => 0];
            }
            
            // New hires
            if (in_array('created_at', $emp_columns)) {
                $result = $conn->query("SELECT COUNT(*) as count FROM employees WHERE MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE())");
                $stats['new_hires_month'] = $result->fetch_assoc()['count'];
                
                $result = $conn->query("SELECT COUNT(*) as count FROM employees WHERE YEAR(created_at) = YEAR(CURDATE())");
                $stats['new_hires_year'] = $result->fetch_assoc()['count'];
            } else {
                $stats['new_hires_month'] = 0;
                $stats['new_hires_year'] = 0;
            }
            
            // Schools with staff
            if ($emp_school_col && $schools_exist) {
                $result = $conn->query("SELECT COUNT(DISTINCT $emp_school_col) as count FROM employees WHERE $emp_school_col IS NOT NULL");
                $stats['school_count'] = $result->fetch_assoc()['count'] ?? 0;
            } else {
                $stats['school_count'] = 0;
            }
            
            $response['success'] = true;
            $response['data'] = $stats;
        }
        
        elseif ($_GET['ajax_action'] == 'get_employee' && isset($_GET['id'])) {
            $id = intval($_GET['id']);
            
            $query = "SELECT e.*";
            
            if ($designations_exist && $emp_designation_col) {
                $query .= ", d.$desig_name_col as designation_name";
            }
            
            if ($schools_exist && $emp_school_col) {
                $query .= ", sch.$school_name_col as school_name";
            }
            
            if (in_array('date_of_birth', $emp_columns)) {
                $query .= ", TIMESTAMPDIFF(YEAR, e.date_of_birth, CURDATE()) as age";
            }
            
            $query .= " FROM employees e";
            
            if ($designations_exist && $emp_designation_col) {
                $query .= " LEFT JOIN designations d ON e.$emp_designation_col = d.$desig_id_col";
            }
            
            if ($schools_exist && $emp_school_col) {
                $query .= " LEFT JOIN school_emis sch ON e.$emp_school_col = sch.$school_id_col";
            }
            
            $query .= " WHERE e.employee_id = ?";
            
            $stmt = $conn->prepare($query);
            if ($stmt) {
                $stmt->bind_param("i", $id);
                $stmt->execute();
                $result = $stmt->get_result();
                
                if ($row = $result->fetch_assoc()) {
                    $response['success'] = true;
                    $response['data'] = $row;
                } else {
                    $response['message'] = 'Employee not found';
                }
                $stmt->close();
            } else {
                $response['message'] = 'Query preparation failed: ' . $conn->error;
            }
        }
        
    } catch (Exception $e) {
        $response['message'] = 'Error: ' . $e->getMessage();
    }
    
    echo json_encode($response);
    exit();
}

// Get total employees count
$total_employees = 0;
$result = $conn->query("SELECT COUNT(*) as total FROM employees");
if ($result) {
    $total_employees = $result->fetch_assoc()['total'];
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HR Management - AJ&K Education Department</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">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <!-- Chart.js for pie chart -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        :root {
            --primary: #059669;
            --primary-dark: #047857;
            --primary-light: #10b981;
            --primary-soft: #d1fae5;
            --secondary: #0284c7;
            --secondary-light: #38bdf8;
            --secondary-soft: #e0f2fe;
            --success: #059669;
            --success-soft: #d1fae5;
            --danger: #dc2626;
            --danger-soft: #fee2e2;
            --warning: #d97706;
            --warning-soft: #fef3c7;
            --info: #0284c7;
            --info-soft: #e0f2fe;
            --gray-50: #f9fafb;
            --gray-100: #f3f4f6;
            --gray-200: #e5e7eb;
            --gray-300: #d1d5db;
            --gray-400: #9ca3af;
            --gray-500: #6b7280;
            --gray-600: #4b5563;
            --gray-700: #374151;
            --gray-800: #1f2937;
            --gray-900: #111827;
            --white: #ffffff;
            --shadow-sm: 0 1px 2px 0 rgb(0 0 0 / 0.05);
            --shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1);
            --shadow-md: 0 10px 15px -3px rgb(0 0 0 / 0.1);
            --shadow-lg: 0 20px 25px -5px rgb(0 0 0 / 0.1);
            --shadow-xl: 0 25px 50px -12px rgb(0 0 0 / 0.25);
            
            /* Chart colors */
            --chart-1: #059669;
            --chart-2: #0284c7;
            --chart-3: #8b5cf6;
            --chart-4: #f59e0b;
            --chart-5: #ef4444;
            --chart-6: #ec4899;
            --chart-7: #14b8a6;
            --chart-8: #f97316;
        }

        body {
            background: linear-gradient(135deg, #f0fdf4 0%, #f0f9ff 100%);
            font-family: 'Inter', sans-serif;
            min-height: 100vh;
            color: var(--gray-800);
        }

        /* Navigation */
        .navbar-fresh {
            background: var(--white);
            box-shadow: var(--shadow-sm);
            padding: 0.75rem 2rem;
            position: sticky;
            top: 0;
            z-index: 1000;
            border-bottom: 3px solid var(--primary);
        }

        .navbar-brand-fresh {
            color: var(--primary-dark);
            font-weight: 600;
            font-size: 0.95rem;
            padding: 0.5rem 1rem;
            background: var(--primary-soft);
            border-radius: 40px;
            transition: all 0.3s;
            text-decoration: none;
        }

        .navbar-brand-fresh:hover {
            background: var(--primary);
            color: var(--white);
            transform: translateX(-3px);
        }

        .navbar-brand-fresh i {
            margin-right: 0.5rem;
        }

        .user-menu-fresh .dropdown-toggle {
            color: var(--gray-700);
            padding: 0.5rem 1.25rem;
            border-radius: 40px;
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 0.75rem;
            background: var(--gray-50);
            border: 1px solid var(--gray-200);
            transition: all 0.3s;
            text-decoration: none;
        }

        .user-menu-fresh .dropdown-toggle:hover {
            background: var(--primary-soft);
            border-color: var(--primary);
        }

        .user-menu-fresh .dropdown-toggle i {
            color: var(--primary);
            font-size: 1.1rem;
        }

        .user-menu-fresh .dropdown-menu {
            background: var(--white);
            border: 1px solid var(--gray-200);
            border-radius: 16px;
            padding: 0.5rem;
            margin-top: 0.5rem;
            box-shadow: var(--shadow-lg);
        }

        .user-menu-fresh .dropdown-item {
            border-radius: 12px;
            padding: 0.6rem 1rem;
            font-weight: 500;
            transition: all 0.2s;
            color: var(--gray-700);
        }

        .user-menu-fresh .dropdown-item:hover {
            background: var(--primary-soft);
            color: var(--primary-dark);
            transform: translateX(3px);
        }

        /* Main Container */
        .main-container {
            max-width: 1600px;
            margin: 2rem auto;
            padding: 0 2rem;
        }

        /* Page Header */
        .page-header-fresh {
            background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
            color: var(--white);
            padding: 2rem 2.5rem;
            border-radius: 24px;
            margin-bottom: 2rem;
            box-shadow: var(--shadow-lg);
            display: flex;
            align-items: center;
            justify-content: space-between;
            position: relative;
            overflow: hidden;
        }

        .page-header-fresh::before {
            content: '';
            position: absolute;
            top: -30%;
            right: -10%;
            width: 300px;
            height: 300px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 50%;
        }

        .page-header-fresh::after {
            content: '';
            position: absolute;
            bottom: -30%;
            left: -10%;
            width: 300px;
            height: 300px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 50%;
        }

        .page-header-fresh h2 {
            font-size: 1.75rem;
            font-weight: 700;
            margin: 0;
            display: flex;
            align-items: center;
            gap: 1rem;
            position: relative;
            z-index: 1;
        }

        .page-header-fresh h2 i {
            font-size: 2rem;
            background: rgba(255, 255, 255, 0.2);
            padding: 0.75rem;
            border-radius: 18px;
        }

        .header-badge-fresh {
            background: rgba(255, 255, 255, 0.2);
            padding: 0.75rem 1.5rem;
            border-radius: 50px;
            font-weight: 500;
            border: 1px solid rgba(255, 255, 255, 0.3);
            position: relative;
            z-index: 1;
            backdrop-filter: blur(4px);
        }

        .header-badge-fresh i {
            margin-right: 0.5rem;
        }

        /* Stats Grid */
        .stats-grid-fresh {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 1.5rem;
            margin-bottom: 2rem;
        }

        .stat-card-fresh {
            background: var(--white);
            border-radius: 20px;
            padding: 1.5rem;
            box-shadow: var(--shadow);
            transition: all 0.3s;
            border: 1px solid var(--gray-200);
            position: relative;
            overflow: hidden;
        }

        .stat-card-fresh::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: linear-gradient(90deg, var(--primary), var(--secondary));
        }

        .stat-card-fresh:hover {
            transform: translateY(-5px);
            box-shadow: var(--shadow-lg);
            border-color: var(--primary-light);
        }

        .stat-header-fresh {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 1rem;
        }

        .stat-icon-fresh {
            width: 56px;
            height: 56px;
            background: linear-gradient(135deg, var(--primary-soft), var(--secondary-soft));
            border-radius: 16px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: var(--primary-dark);
            font-size: 1.8rem;
            transition: all 0.3s;
        }

        .stat-card-fresh:hover .stat-icon-fresh {
            transform: scale(1.1) rotate(5deg);
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            color: var(--white);
        }

        .stat-badge-fresh {
            background: var(--gray-100);
            color: var(--gray-600);
            font-size: 0.7rem;
            font-weight: 600;
            padding: 0.35rem 1rem;
            border-radius: 30px;
            letter-spacing: 0.5px;
        }

        .stat-value-fresh {
            font-size: 2.5rem;
            font-weight: 800;
            color: var(--gray-900);
            line-height: 1;
            margin-bottom: 0.25rem;
        }

        .stat-label-fresh {
            color: var(--gray-600);
            font-size: 0.85rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .stat-footer-fresh {
            margin-top: 1rem;
            padding-top: 1rem;
            border-top: 1px solid var(--gray-200);
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-size: 0.8rem;
            color: var(--gray-500);
        }

        .stat-footer-fresh i {
            color: var(--primary);
        }

        /* Action Bar - Updated */
        .action-bar-fresh {
            display: flex;
            gap: 1rem;
            margin-bottom: 2rem;
            flex-wrap: wrap;
        }

        .action-btn-fresh {
            background: var(--white);
            border: 1px solid var(--gray-200);
            border-radius: 50px;
            padding: 0.75rem 1.5rem;
            display: flex;
            align-items: center;
            gap: 0.75rem;
            cursor: pointer;
            transition: all 0.3s;
            box-shadow: var(--shadow-sm);
            font-weight: 600;
            color: var(--gray-700);
            text-decoration: none;
        }

        .action-btn-fresh:hover {
            background: linear-gradient(135deg, var(--primary-soft), var(--secondary-soft));
            border-color: var(--primary);
            transform: translateY(-3px);
            box-shadow: var(--shadow-md);
            color: var(--primary-dark);
        }

        .action-btn-fresh i {
            font-size: 1.2rem;
            color: var(--primary);
            transition: all 0.3s;
        }

        .action-btn-fresh:hover i {
            transform: scale(1.1);
        }

        /* Chart Container */
        .chart-container-fresh {
            background: var(--white);
            border-radius: 24px;
            padding: 2rem;
            box-shadow: var(--shadow-lg);
            border: 1px solid var(--gray-200);
            margin-bottom: 2rem;
        }

        .chart-header-fresh {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 2rem;
            flex-wrap: wrap;
            gap: 1rem;
        }

        .chart-title-fresh {
            font-size: 1.25rem;
            font-weight: 700;
            color: var(--gray-900);
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }

        .chart-title-fresh i {
            color: var(--primary);
            font-size: 1.4rem;
        }

        .chart-legend-fresh {
            display: flex;
            gap: 1rem;
            flex-wrap: wrap;
        }

        .legend-item-fresh {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-size: 0.85rem;
            color: var(--gray-600);
            cursor: pointer;
            transition: all 0.2s;
        }

        .legend-item-fresh:hover {
            transform: translateY(-2px);
            color: var(--primary);
        }

        .legend-color-fresh {
            width: 12px;
            height: 12px;
            border-radius: 4px;
        }

        .chart-wrapper {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 2rem;
            align-items: center;
        }

        .pie-chart-container {
            position: relative;
            height: 350px;
            width: 100%;
        }

        .designation-stats {
            background: var(--gray-50);
            border-radius: 20px;
            padding: 1.5rem;
            border: 1px solid var(--gray-200);
        }

        .stats-list-fresh {
            max-height: 300px;
            overflow-y: auto;
            padding-right: 0.5rem;
        }

        .stats-list-fresh::-webkit-scrollbar {
            width: 6px;
        }

        .stats-list-fresh::-webkit-scrollbar-track {
            background: var(--gray-200);
            border-radius: 10px;
        }

        .stats-list-fresh::-webkit-scrollbar-thumb {
            background: var(--primary);
            border-radius: 10px;
        }

        .stat-item-fresh {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0.75rem 1rem;
            border-bottom: 1px solid var(--gray-200);
            transition: all 0.3s;
            cursor: pointer;
        }

        .stat-item-fresh:hover {
            background: var(--white);
            border-radius: 12px;
            transform: translateX(5px);
            box-shadow: var(--shadow-sm);
        }

        .stat-item-fresh:last-child {
            border-bottom: none;
        }

        .stat-item-name {
            font-weight: 500;
            color: var(--gray-700);
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .stat-item-count {
            background: linear-gradient(135deg, var(--primary-soft), var(--secondary-soft));
            padding: 0.25rem 1rem;
            border-radius: 30px;
            font-weight: 600;
            color: var(--primary-dark);
        }

        /* Search Info Bar */
        .search-info-fresh {
            background: linear-gradient(135deg, var(--primary-soft), var(--secondary-soft));
            border-radius: 16px;
            padding: 1rem 1.5rem;
            margin-bottom: 1.5rem;
            display: flex;
            align-items: center;
            gap: 1rem;
            color: var(--gray-700);
            border: 1px solid var(--gray-200);
            flex-wrap: wrap;
        }

        .search-info-fresh i {
            font-size: 1.2rem;
            color: var(--primary);
        }

        .search-tags-fresh {
            display: flex;
            gap: 0.5rem;
            flex-wrap: wrap;
        }

        .search-tag-fresh {
            background: var(--white);
            padding: 0.25rem 1rem;
            border-radius: 30px;
            font-size: 0.8rem;
            font-weight: 500;
            color: var(--primary-dark);
            border: 1px solid var(--gray-200);
        }

        /* Search Results Container */
        .search-container-fresh {
            background: var(--white);
            border-radius: 24px;
            padding: 2rem;
            box-shadow: var(--shadow-lg);
            border: 1px solid var(--gray-200);
        }

        .search-header-fresh {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1.5rem;
            flex-wrap: wrap;
            gap: 1rem;
        }

        .search-title-fresh {
            font-size: 1.25rem;
            font-weight: 700;
            color: var(--gray-900);
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }

        .search-title-fresh i {
            color: var(--primary);
            font-size: 1.4rem;
        }

        .search-box-fresh {
            position: relative;
            min-width: 400px;
        }

        .search-box-fresh i {
            position: absolute;
            left: 1.25rem;
            top: 50%;
            transform: translateY(-50%);
            color: var(--gray-400);
            font-size: 1rem;
            transition: all 0.3s;
        }

        .search-box-fresh input {
            width: 100%;
            padding: 0.85rem 1rem 0.85rem 3rem;
            border: 2px solid var(--gray-200);
            border-radius: 50px;
            font-size: 0.95rem;
            background: var(--gray-50);
            transition: all 0.3s;
            font-weight: 500;
        }

        .search-box-fresh input:focus {
            outline: none;
            border-color: var(--primary);
            background: var(--white);
            box-shadow: 0 0 0 4px var(--primary-soft);
        }

        .search-box-fresh input:focus + i {
            color: var(--primary);
        }

        .search-hint-fresh {
            position: absolute;
            right: 1rem;
            top: 50%;
            transform: translateY(-50%);
            font-size: 0.7rem;
            color: var(--gray-400);
            background: var(--gray-100);
            padding: 0.2rem 0.5rem;
            border-radius: 30px;
        }

        .search-results-fresh {
            min-height: 200px;
        }

        .result-item-fresh {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 1rem;
            border-bottom: 1px solid var(--gray-200);
            transition: all 0.3s;
            cursor: pointer;
        }

        .result-item-fresh:hover {
            background: var(--gray-50);
            border-radius: 12px;
            transform: translateX(5px);
            box-shadow: var(--shadow-sm);
        }

        .result-info-fresh {
            display: flex;
            align-items: center;
            gap: 1rem;
            flex: 1;
        }

        .result-avatar-fresh {
            width: 48px;
            height: 48px;
            background: linear-gradient(135deg, var(--primary-soft), var(--secondary-soft));
            border-radius: 14px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: var(--primary-dark);
            font-weight: 700;
            font-size: 1.2rem;
            flex-shrink: 0;
        }

        .result-details-fresh {
            flex: 1;
        }

        .result-details-fresh h6 {
            font-weight: 700;
            color: var(--gray-900);
            margin-bottom: 0.25rem;
            font-size: 1rem;
        }

        .result-meta-fresh {
            display: flex;
            flex-wrap: wrap;
            gap: 1rem;
            font-size: 0.8rem;
            color: var(--gray-500);
        }

        .result-meta-fresh span {
            display: flex;
            align-items: center;
            gap: 0.25rem;
        }

        .result-meta-fresh i {
            width: 14px;
            color: var(--primary);
        }

        .result-badge-fresh {
            background: var(--primary-soft);
            color: var(--primary-dark);
            padding: 0.35rem 1rem;
            border-radius: 30px;
            font-size: 0.75rem;
            font-weight: 600;
            white-space: nowrap;
            margin-left: 1rem;
        }

        .empty-results-fresh {
            text-align: center;
            padding: 3rem;
        }

        .empty-results-fresh i {
            font-size: 4rem;
            color: var(--gray-300);
            margin-bottom: 1rem;
        }

        .empty-results-fresh h5 {
            color: var(--gray-600);
            margin-bottom: 0.5rem;
        }

        .empty-results-fresh p {
            color: var(--gray-400);
        }

        /* Modal Styles - Updated (removed footer) */
        .modal-fresh .modal-content {
            background: var(--white);
            border: none;
            border-radius: 24px;
            overflow: hidden;
        }

        .modal-fresh .modal-header {
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            color: var(--white);
            padding: 1.5rem 2rem;
            border: none;
        }

        .modal-fresh .modal-header .btn-close {
            background: var(--white);
            opacity: 0.9;
        }

        .modal-fresh .modal-body {
            padding: 2rem;
        }

        .profile-avatar-fresh {
            width: 100px;
            height: 100px;
            background: linear-gradient(135deg, var(--primary-soft), var(--secondary-soft));
            border-radius: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: var(--primary-dark);
            font-size: 2.5rem;
            font-weight: 700;
            margin: 0 auto 1.5rem;
            border: 4px solid var(--white);
            box-shadow: var(--shadow-md);
        }

        .info-grid-fresh {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 1rem;
        }

        .info-item-fresh {
            background: var(--gray-50);
            border-radius: 16px;
            padding: 1.25rem;
            border: 1px solid var(--gray-200);
            transition: all 0.3s;
        }

        .info-item-fresh:hover {
            background: var(--white);
            border-color: var(--primary);
            transform: translateY(-2px);
            box-shadow: var(--shadow-sm);
        }

        .info-label-fresh {
            color: var(--gray-500);
            font-size: 0.7rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            font-weight: 600;
            margin-bottom: 0.5rem;
            display: flex;
            align-items: center;
            gap: 0.25rem;
        }

        .info-value-fresh {
            font-weight: 700;
            color: var(--gray-900);
            font-size: 1.1rem;
        }

        /* Loading Spinner */
        .loading-fresh {
            text-align: center;
            padding: 3rem;
        }

        .spinner-fresh {
            width: 50px;
            height: 50px;
            border: 4px solid var(--gray-200);
            border-top-color: var(--primary);
            border-right-color: var(--secondary);
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto 1rem;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        /* Toast */
        .toast-fresh {
            background: var(--white);
            border-left: 4px solid var(--primary);
            border-radius: 12px;
            box-shadow: var(--shadow-lg);
        }

        /* Animations */
        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .animate-slideIn {
            animation: slideIn 0.5s ease-out forwards;
        }

        /* Responsive */
        @media (max-width: 1200px) {
            .stats-grid-fresh {
                grid-template-columns: repeat(2, 1fr);
            }
            
            .chart-wrapper {
                grid-template-columns: 1fr;
            }
            
            .pie-chart-container {
                height: 300px;
            }
        }

        @media (max-width: 768px) {
            .main-container {
                padding: 0 1rem;
            }
            
            .stats-grid-fresh {
                grid-template-columns: 1fr;
            }
            
            .chart-header-fresh {
                flex-direction: column;
                align-items: flex-start;
            }
            
            .search-header-fresh {
                flex-direction: column;
            }
            
            .search-box-fresh {
                width: 100%;
                min-width: auto;
            }
            
            .result-item-fresh {
                flex-direction: column;
                align-items: flex-start;
                gap: 0.5rem;
            }
            
            .result-badge-fresh {
                margin-left: 0;
                align-self: flex-start;
            }
            
            .action-bar-fresh {
                justify-content: center;
            }
            
            .result-meta-fresh {
                flex-direction: column;
                gap: 0.25rem;
            }
        }
    </style>
</head>
<body>
    <!-- Fresh Navigation -->
    <nav class="navbar-fresh">
        <div class="container-fluid px-0 d-flex justify-content-between align-items-center">
            <a class="navbar-brand-fresh" href="employee_dashboard.php">
                <i class="fas fa-arrow-left"></i>
                <span>Dashboard</span>
            </a>
            <div class="dropdown user-menu-fresh">
                <a class="dropdown-toggle" href="#" data-bs-toggle="dropdown">
                    <i class="fas fa-user-circle"></i>
                    <span><?php echo htmlspecialchars($_SESSION['employee_data']['full_name'] ?? 'User'); ?></span>
                    <i class="fas fa-chevron-down ms-2" style="font-size: 0.8rem;"></i>
                </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>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>
                    <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>
            </div>
        </div>
    </nav>

    <!-- Main Container -->
    <div class="main-container">
        <!-- Fresh Page Header -->
        <div class="page-header-fresh animate-slideIn">
            <h2>
                <i class="fas fa-users-cog"></i>
                Human Resource Management
            </h2>
            <div class="header-badge-fresh">
                <i class="far fa-calendar-alt"></i>
                <?php echo date('F j, Y'); ?>
            </div>
        </div>

        <!-- Fresh Statistics Cards -->
        <div class="stats-grid-fresh" id="statsContainer">
            <div class="stat-card-fresh animate-slideIn" style="animation-delay: 0.1s">
                <div class="stat-header-fresh">
                    <div class="stat-icon-fresh"><i class="fas fa-users"></i></div>
                    <span class="stat-badge-fresh">TOTAL</span>
                </div>
                <div class="stat-value-fresh" id="totalEmployees">0</div>
                <div class="stat-label-fresh">Active Employees</div>
                <div class="stat-footer-fresh">
                    <i class="fas fa-arrow-up text-success"></i>
                    <span>+12% from last month</span>
                </div>
            </div>

            <div class="stat-card-fresh animate-slideIn" style="animation-delay: 0.2s">
                <div class="stat-header-fresh">
                    <div class="stat-icon-fresh"><i class="fas fa-venus-mars"></i></div>
                    <span class="stat-badge-fresh">GENDER</span>
                </div>
                <div class="stat-value-fresh" id="maleCount">0</div>
                <div class="stat-label-fresh">Male</div>
                <div class="stat-footer-fresh">
                    <i class="fas fa-female" style="color: var(--primary);"></i>
                    <span>Female: <span id="femaleCount">0</span></span>
                </div>
            </div>

            <div class="stat-card-fresh animate-slideIn" style="animation-delay: 0.3s">
                <div class="stat-header-fresh">
                    <div class="stat-icon-fresh"><i class="fas fa-user-plus"></i></div>
                    <span class="stat-badge-fresh">HIRING</span>
                </div>
                <div class="stat-value-fresh" id="newHiresMonth">0</div>
                <div class="stat-label-fresh">New This Month</div>
                <div class="stat-footer-fresh">
                    <i class="fas fa-calendar-check"></i>
                    <span>Year: <span id="newHiresYear">0</span></span>
                </div>
            </div>

            <div class="stat-card-fresh animate-slideIn" style="animation-delay: 0.4s">
                <div class="stat-header-fresh">
                    <div class="stat-icon-fresh"><i class="fas fa-school"></i></div>
                    <span class="stat-badge-fresh">SCHOOLS</span>
                </div>
                <div class="stat-value-fresh" id="schoolCount">0</div>
                <div class="stat-label-fresh">With Staff</div>
                <div class="stat-footer-fresh">
                    <i class="fas fa-map-marker-alt"></i>
                    <span>85% coverage</span>
                </div>
            </div>
        </div>

        <!-- Fresh Action Bar - Updated (removed Add Employee) -->
        <div class="action-bar-fresh">
            <a href="employee_transfer.php" class="action-btn-fresh">
                <i class="fas fa-exchange-alt"></i>
                <span>Transfer</span>
            </a>
            <a href="employee_promotion.php" class="action-btn-fresh">
                <i class="fas fa-arrow-up"></i>
                <span>Promotion</span>
            </a>
            <a href="employee_timescale.php" class="action-btn-fresh">
                <i class="fas fa-clock"></i>
                <span>Time Scale</span>
            </a>
            <a href="#" onclick="exportEmployeeData()" class="action-btn-fresh">
                <i class="fas fa-file-export"></i>
                <span>Export</span>
            </a>
        </div>

        <!-- Fresh Chart Container - Pie Chart for Designation Distribution -->
        <div class="chart-container-fresh animate-slideIn">
            <div class="chart-header-fresh">
                <h5 class="chart-title-fresh">
                    <i class="fas fa-chart-pie"></i>
                    Employee Distribution by Designation
                </h5>
                <div class="chart-legend-fresh" id="chartLegend">
                    <!-- Dynamic legend will be added here -->
                </div>
            </div>
            <div class="chart-wrapper">
                <div class="pie-chart-container">
                    <canvas id="designationPieChart"></canvas>
                </div>
                <div class="designation-stats">
                    <h6 class="mb-3 d-flex align-items-center gap-2">
                        <i class="fas fa-list"></i>
                        Designation-wise Count
                        <span class="badge bg-soft-primary ms-2" id="totalDesignations">0</span>
                    </h6>
                    <div class="stats-list-fresh" id="designationStatsList">
                        <!-- Dynamic stats list will be added here -->
                        <div class="loading-fresh">
                            <div class="spinner-fresh"></div>
                            <p class="text-muted">Loading chart data...</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Search Info Bar -->
        <div class="search-info-fresh animate-slideIn">
            <i class="fas fa-info-circle"></i>
            <span>Search by: </span>
            <div class="search-tags-fresh">
                <span class="search-tag-fresh"><i class="fas fa-user me-1"></i>Name</span>
                <span class="search-tag-fresh"><i class="fas fa-id-card me-1"></i>CNIC</span>
                <span class="search-tag-fresh"><i class="fas fa-hashtag me-1"></i>Employee No</span>
                <span class="search-tag-fresh"><i class="fas fa-school me-1"></i>School Name</span>
                <span class="search-tag-fresh"><i class="fas fa-briefcase me-1"></i>Designation</span>
            </div>
        </div>

        <!-- Fresh Search Results Container -->
        <div class="search-container-fresh animate-slideIn">
            <div class="search-header-fresh">
                <h5 class="search-title-fresh">
                    <i class="fas fa-search"></i>
                    Employee Search
                </h5>
                <div class="search-box-fresh">
                    <i class="fas fa-search"></i>
                    <input type="text" id="employeeSearch" placeholder="Search by name, CNIC, employee no, school, or designation...">
                    <span class="search-hint-fresh">Press Enter</span>
                </div>
            </div>
            <div class="search-results-fresh" id="searchResults">
                <div class="empty-results-fresh">
                    <i class="fas fa-search"></i>
                    <h5>Start Searching</h5>
                    <p class="text-muted">Type in the search box to find employees<br>You can search by name, CNIC, employee number, school name, or designation</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Fresh Employee Quick View Modal - Updated (removed footer) -->
    <div class="modal fade modal-fresh" id="employeeQuickViewModal" tabindex="-1">
        <div class="modal-dialog modal-md">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-user-circle me-2"></i>Employee Details
                    </h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>

                <div class="modal-body" id="employeeQuickViewContent">
                    <!-- Content will be loaded dynamically -->
                </div>
            </div>
        </div>
    </div>

    <!-- Fresh Change Password Modal -->
    <div class="modal fade modal-fresh" id="changePasswordModal" tabindex="-1">
        <div class="modal-dialog modal-sm">
            <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 btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form method="POST" action="change_password_emp.php">
                        <div class="mb-3">
                            <label class="form-label small fw-bold">Current Password</label>
                            <input type="password" class="form-control" name="current_password" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label small fw-bold">New Password</label>
                            <input type="password" class="form-control" name="new_password" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label small fw-bold">Confirm Password</label>
                            <input type="password" class="form-control" name="confirm_password" required>
                        </div>
                        <button type="submit" class="btn btn-primary w-100">Update Password</button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Toast Container -->
    <div class="toast-container position-fixed top-0 end-0 p-3" id="toastContainer"></div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        // Chart instance
        let pieChart = null;
        
        // Store current search results
        let currentSearchResults = [];
        
        // Toast notification
        function showToast(message, type = 'success') {
            const toastContainer = document.getElementById('toastContainer');
            const toast = document.createElement('div');
            toast.className = `toast toast-fresh align-items-center text-white bg-${type} border-0 show`;
            toast.setAttribute('role', 'alert');
            toast.innerHTML = `
                <div class="d-flex">
                    <div class="toast-body">
                        <i class="fas ${type === 'success' ? 'fa-check-circle' : type === 'danger' ? 'fa-exclamation-circle' : 'fa-info-circle'} me-2"></i>
                        ${message}
                    </div>
                    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
                </div>
            `;
            toastContainer.appendChild(toast);
            setTimeout(() => toast.remove(), 5000);
        }

        // Load designation stats and create pie chart
        async function loadDesignationStats() {
            try {
                const response = await fetch(`hr_management.php?ajax_action=get_designation_stats&t=${Date.now()}`);
                const data = await response.json();
                
                if (data.success && data.data.length > 0) {
                    createPieChart(data.data);
                    displayDesignationStatsList(data.data);
                    document.getElementById('totalDesignations').textContent = data.data.length;
                } else {
                    document.getElementById('designationStatsList').innerHTML = `
                        <div class="empty-results-fresh">
                            <i class="fas fa-chart-pie"></i>
                            <h5>No Data Available</h5>
                            <p class="text-muted">Designation data not found</p>
                        </div>
                    `;
                }
            } catch (error) {
                console.error('Error loading designation stats:', error);
                showToast('Error loading chart data', 'danger');
            }
        }

        // Create pie chart
        function createPieChart(data) {
            const ctx = document.getElementById('designationPieChart').getContext('2d');
            
            // Chart colors
            const colors = [
                '#059669', '#0284c7', '#8b5cf6', '#f59e0b', '#ef4444', 
                '#ec4899', '#14b8a6', '#f97316', '#6366f1', '#a855f7'
            ];
            
            const labels = data.map(item => item.designation);
            const values = data.map(item => item.count);
            const backgroundColors = data.map((_, index) => colors[index % colors.length]);
            
            // Create legend
            createLegend(data, backgroundColors);
            
            // Destroy existing chart if it exists
            if (pieChart) {
                pieChart.destroy();
            }
            
            // Create new chart
            pieChart = new Chart(ctx, {
                type: 'pie',
                data: {
                    labels: labels,
                    datasets: [{
                        data: values,
                        backgroundColor: backgroundColors,
                        borderWidth: 0,
                        hoverOffset: 10
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        },
                        tooltip: {
                            backgroundColor: 'white',
                            titleColor: '#1f2937',
                            bodyColor: '#4b5563',
                            borderColor: '#e5e7eb',
                            borderWidth: 1,
                            padding: 12,
                            callbacks: {
                                label: function(context) {
                                    const label = context.label || '';
                                    const value = context.raw || 0;
                                    const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                    const percentage = ((value / total) * 100).toFixed(1);
                                    return `${label}: ${value} (${percentage}%)`;
                                }
                            }
                        }
                    },
                    layout: {
                        padding: 20
                    },
                    onClick: (event, items) => {
                        if (items.length > 0) {
                            const index = items[0].index;
                            const designation = data[index].designation;
                            document.getElementById('employeeSearch').value = designation;
                            searchEmployees(designation);
                        }
                    }
                }
            });
        }

        // Create custom legend
        function createLegend(data, colors) {
            const legendContainer = document.getElementById('chartLegend');
            let legendHtml = '';
            
            // Show only first 5 items in legend to avoid clutter
            const displayData = data.slice(0, 5);
            const remainingCount = data.length - 5;
            
            displayData.forEach((item, index) => {
                legendHtml += `
                    <div class="legend-item-fresh" onclick="searchByDesignation('${item.designation}')">
                        <span class="legend-color-fresh" style="background: ${colors[index]}"></span>
                        <span>${item.designation.length > 15 ? item.designation.substring(0, 15) + '...' : item.designation}</span>
                    </div>
                `;
            });
            
            if (remainingCount > 0) {
                legendHtml += `
                    <div class="legend-item-fresh">
                        <span class="legend-color-fresh" style="background: #94a3b8"></span>
                        <span>+${remainingCount} more</span>
                    </div>
                `;
            }
            
            legendContainer.innerHTML = legendHtml;
        }

        // Search by designation when clicking on legend
        function searchByDesignation(designation) {
            document.getElementById('employeeSearch').value = designation;
            searchEmployees(designation);
        }

        // Display designation stats list
        function displayDesignationStatsList(data) {
            const statsList = document.getElementById('designationStatsList');
            let total = data.reduce((sum, item) => sum + item.count, 0);
            
            let html = '';
            data.forEach(item => {
                const percentage = ((item.count / total) * 100).toFixed(1);
                html += `
                    <div class="stat-item-fresh" onclick="searchByDesignation('${item.designation}')">
                        <span class="stat-item-name">
                            <i class="fas fa-tag" style="color: var(--primary);"></i>
                            ${item.designation}
                        </span>
                        <span class="stat-item-count">
                            ${item.count} (${percentage}%)
                        </span>
                    </div>
                `;
            });
            
            statsList.innerHTML = html;
        }

        // Search employees
        async function searchEmployees(searchTerm) {
            const resultsContainer = document.getElementById('searchResults');
            
            if (searchTerm.length < 2) {
                resultsContainer.innerHTML = `
                    <div class="empty-results-fresh">
                        <i class="fas fa-search"></i>
                        <h5>Start Searching</h5>
                        <p class="text-muted">Type at least 2 characters to search<br>You can search by name, CNIC, employee number, school name, or designation</p>
                    </div>
                `;
                return;
            }
            
            resultsContainer.innerHTML = `
                <div class="loading-fresh">
                    <div class="spinner-fresh"></div>
                    <p class="text-muted">Searching for "${searchTerm}"...</p>
                </div>
            `;
            
            try {
                const response = await fetch(`hr_management.php?ajax_action=search_employees&search=${encodeURIComponent(searchTerm)}&t=${Date.now()}`);
                const data = await response.json();
                
                if (data.success) {
                    currentSearchResults = data.data || [];
                    displaySearchResults(currentSearchResults, searchTerm);
                } else {
                    throw new Error(data.message || 'Search failed');
                }
            } catch (error) {
                console.error('Search error:', error);
                resultsContainer.innerHTML = `
                    <div class="empty-results-fresh">
                        <i class="fas fa-exclamation-circle text-danger"></i>
                        <h5 class="text-danger">Error</h5>
                        <p class="text-muted">${error.message}</p>
                    </div>
                `;
            }
        }

        // Display search results
        function displaySearchResults(results, searchTerm) {
            const resultsContainer = document.getElementById('searchResults');
            
            if (results.length === 0) {
                resultsContainer.innerHTML = `
                    <div class="empty-results-fresh">
                        <i class="fas fa-user-slash"></i>
                        <h5>No Results Found</h5>
                        <p class="text-muted">No employees match "${searchTerm}"</p>
                        <p class="text-muted small">Try searching with different keywords</p>
                    </div>
                `;
                return;
            }
            
            let html = `<div class="mb-3 text-muted small">Found ${results.length} employee(s) matching "${searchTerm}"</div>`;
            
            results.forEach((emp, index) => {
                const initials = emp.full_name ? emp.full_name.split(' ').map(n => n[0]).join('').substring(0,2).toUpperCase() : '?';
                const mobileNo = emp.mobile_no || 'N/A';
                
                html += `
                    <div class="result-item-fresh animate-slideIn" style="animation-delay: ${index * 0.03}s" onclick="quickViewEmployee(${emp.employee_id})">
                        <div class="result-info-fresh">
                            <div class="result-avatar-fresh">${initials}</div>
                            <div class="result-details-fresh">
                                <h6>${emp.full_name || 'N/A'}</h6>
                                <div class="result-meta-fresh">
                                    <span><i class="fas fa-id-card"></i> ${emp.personal_no || 'N/A'}</span>
                                    <span><i class="fas fa-id-card"></i> ${emp.cnic || 'N/A'}</span>
                                    <span><i class="fas fa-school"></i> ${emp.school_name || 'Not Assigned'}</span>
                                    <span><i class="fas fa-phone"></i> ${mobileNo}</span>
                                </div>
                            </div>
                        </div>
                        <span class="result-badge-fresh">${emp.designation_name || 'No Designation'}</span>
                    </div>
                `;
            });
            
            resultsContainer.innerHTML = html;
        }

        // Load statistics with animation
        async function loadStats() {
            try {
                const response = await fetch('hr_management.php?ajax_action=get_stats&t=' + Date.now());
                const data = await response.json();
                
                if (data.success) {
                    const stats = data.data;
                    
                    // Animate number counting
                    animateValue('totalEmployees', 0, stats.total_employees || 0, 1000);
                    animateValue('maleCount', 0, stats.gender?.Male || 0, 1000);
                    animateValue('femaleCount', 0, stats.gender?.Female || 0, 1000);
                    animateValue('newHiresMonth', 0, stats.new_hires_month || 0, 1000);
                    animateValue('newHiresYear', 0, stats.new_hires_year || 0, 1000);
                    animateValue('schoolCount', 0, stats.school_count || 0, 1000);
                }
            } catch (error) {
                console.error('Stats error:', error);
            }
        }

        // Animate number counting
        function animateValue(elementId, start, end, duration) {
            const element = document.getElementById(elementId);
            if (!element) return;
            
            const range = end - start;
            const increment = range / (duration / 10);
            let current = start;
            
            const timer = setInterval(() => {
                current += increment;
                if (current >= end) {
                    current = end;
                    clearInterval(timer);
                }
                element.textContent = Math.round(current);
            }, 10);
        }

        // Quick view employee - Updated (removed full profile link)
        async function quickViewEmployee(id) {
            try {
                const response = await fetch(`hr_management.php?ajax_action=get_employee&id=${id}`);
                const data = await response.json();
                
                if (data.success) {
                    const emp = data.data;
                    const modalBody = document.getElementById('employeeQuickViewContent');
                    
                    const mobileNo = emp.mobile_no || emp.contact_no || emp.phone_no || 'Not provided';
                    const initials = emp.full_name ? emp.full_name.split(' ').map(n => n[0]).join('').substring(0,2).toUpperCase() : '?';
                    
                    modalBody.innerHTML = `
                        <div class="text-center mb-4">
                            <div class="profile-avatar-fresh">
                                ${initials}
                            </div>
                            <h4 class="fw-bold mb-1">${emp.full_name || 'N/A'}</h4>
                            <p class="text-primary mb-2">${emp.designation_name || 'No Designation'}</p>
                            <span class="badge bg-soft-primary">${emp.personal_no || 'N/A'}</span>
                        </div>
                        
                        <div class="info-grid-fresh">
                            <div class="info-item-fresh">
                                <div class="info-label-fresh">
                                    <i class="fas fa-id-card me-1"></i>CNIC
                                </div>
                                <div class="info-value-fresh">${emp.cnic || 'N/A'}</div>
                            </div>
                            
                            <div class="info-item-fresh">
                                <div class="info-label-fresh">
                                    <i class="fas fa-venus-mars me-1"></i>Gender
                                </div>
                                <div class="info-value-fresh">${emp.gender || 'N/A'}</div>
                            </div>
                            
                            <div class="info-item-fresh">
                                <div class="info-label-fresh">
                                    <i class="fas fa-birthday-cake me-1"></i>Date of Birth
                                </div>
                                <div class="info-value-fresh">${emp.date_of_birth || 'N/A'}</div>
                            </div>
                            
                            <div class="info-item-fresh">
                                <div class="info-label-fresh">
                                    <i class="fas fa-briefcase me-1"></i>BPS
                                </div>
                                <div class="info-value-fresh">${emp.bps || 'N/A'}</div>
                            </div>
                            
                            <div class="info-item-fresh">
                                <div class="info-label-fresh">
                                    <i class="fas fa-calendar-plus me-1"></i>Date of Joining
                                </div>
                                <div class="info-value-fresh">${emp.date_of_joining || 'N/A'}</div>
                            </div>
                            
                            <div class="info-item-fresh">
                                <div class="info-label-fresh">
                                    <i class="fas fa-phone me-1"></i>Contact
                                </div>
                                <div class="info-value-fresh">${mobileNo}</div>
                            </div>
                        </div>
                        
                        <div class="info-item-fresh mt-3">
                            <div class="info-label-fresh">
                                <i class="fas fa-school me-1"></i>Current School
                            </div>
                            <div class="info-value-fresh">${emp.school_name || 'Not Assigned'}</div>
                        </div>
                    `;
                    
                    const modal = new bootstrap.Modal(document.getElementById('employeeQuickViewModal'));
                    modal.show();
                }
            } catch (error) {
                showToast('Error loading employee details', 'danger');
            }
        }

        // Export data (for action bar)
        function exportEmployeeData() {
            if (!currentSearchResults || currentSearchResults.length === 0) {
                showToast('No data to export. Try searching first.', 'warning');
                return;
            }
            
            const headers = ['Name', 'Personal No', 'CNIC', 'Designation', 'School', 'Contact'];
            const csvRows = [];
            
            csvRows.push(headers.join(','));
            
            currentSearchResults.forEach(emp => {
                const row = [
                    `"${emp.full_name || ''}"`,
                    emp.personal_no || '',
                    emp.cnic || '',
                    emp.designation_name || '',
                    emp.school_name || '',
                    emp.mobile_no || ''
                ];
                csvRows.push(row.join(','));
            });
            
            const csvContent = csvRows.join('\n');
            const blob = new Blob([csvContent], { type: 'text/csv' });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `search_results_${new Date().toISOString().split('T')[0]}.csv`;
            a.click();
            window.URL.revokeObjectURL(url);
            
            showToast('Search results exported successfully', 'success');
        }

        // Search with debounce and Enter key support
        let searchTimeout;
        const searchInput = document.getElementById('employeeSearch');
        
        searchInput.addEventListener('input', function(e) {
            clearTimeout(searchTimeout);
            const searchTerm = e.target.value.trim();
            
            searchTimeout = setTimeout(() => {
                if (searchTerm.length >= 2) {
                    searchEmployees(searchTerm);
                } else if (searchTerm.length === 0) {
                    // Clear results when search is empty
                    document.getElementById('searchResults').innerHTML = `
                        <div class="empty-results-fresh">
                            <i class="fas fa-search"></i>
                            <h5>Start Searching</h5>
                            <p class="text-muted">Type in the search box to find employees<br>You can search by name, CNIC, employee number, school name, or designation</p>
                        </div>
                    `;
                }
            }, 500);
        });

        // Support Enter key for immediate search
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                clearTimeout(searchTimeout);
                const searchTerm = e.target.value.trim();
                if (searchTerm.length >= 2) {
                    searchEmployees(searchTerm);
                }
            }
        });

        // Initialize
        document.addEventListener('DOMContentLoaded', function() {
            loadStats();
            loadDesignationStats();
        });

        // Handle session messages
        <?php if (isset($_SESSION['hr_message'])): ?>
        showToast('<?php echo addslashes($_SESSION['hr_message']); ?>', '<?php echo $_SESSION['hr_message_type']; ?>');
        <?php 
        unset($_SESSION['hr_message']);
        unset($_SESSION['hr_message_type']);
        endif; 
        ?>
    </script>
</body>
</html>