<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Human Resource - {{ $hotelName ?? hotelName() }}</title>
    
    @hotelSettings
    <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 rel="stylesheet" href="https://cdn.jsdelivr.net/npm/fullcalendar@5.11.3/main.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
   
    <style>
        :root {
            --primary: var(--primary-green, #2A5C82);
            --primary-light: var(--secondary-green, #3A7CA5);
            --primary-dark: var(--dark-green, #1A3A5A);
            --secondary: var(--secondary-green, #5A9E7A);
            --secondary-light: var(--light-green, #7AB89A);
            --accent: var(--accent, #F9C74F);
            --success: #4CAF50;
            --warning: #FF9800;
            --danger: #F44336;
            --info: #00BCD4;
            --dark: var(--dark-green, #2C3E50);
            --light: var(--gray-100, #F8F9FA);
            --gray-100: var(--gray-100, #F8F9FA);
            --gray-200: var(--gray-200, #E9ECEF);
            --gray-300: #DEE2E6;
            --gray-400: #CED4DA;
            --gray-500: #ADB5BD;
            --gray-600: var(--gray-600, #6C757D);
            --gray-700: #495057;
            --gray-800: var(--gray-800, #343A40);
            --gray-900: #212529;
            --header-height: 70px;
            --card-shadow: 0 10px 30px rgba(0, 0, 0, 0.05);
            --card-shadow-hover: 0 15px 40px rgba(0, 0, 0, 0.1);
            --transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            --font-family: var(--font-family, 'Segoe UI', sans-serif);
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', sans-serif;
            background-color: #F5F7FA;
            color: var(--gray-800);
            line-height: 1.6;
            overflow-x: hidden;
        }

        /* Modern Scrollbar */
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }

        ::-webkit-scrollbar-track {
            background: var(--gray-100);
        }

        ::-webkit-scrollbar-thumb {
            background: var(--gray-400);
            border-radius: 4px;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: var(--gray-500);
        }

        /* Main Content */
        .main-content {
            padding: 30px 40px;
            max-width: 1400px;
            margin: 0 auto;
        }

        /* Top Bar */
        .top-bar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            background: white;
            padding: 15px 25px;
            border-radius: 15px;
            box-shadow: var(--card-shadow);
        }

        .page-title h1 {
            font-size: 1.8rem;
            font-weight: 700;
            color: var(--gray-800);
            margin: 0;
        }

        .page-title p {
            color: var(--gray-500);
            font-size: 0.9rem;
            margin: 5px 0 0;
        }

        .top-bar-actions {
            display: flex;
            gap: 15px;
            align-items: center;
        }

        .search-box {
            position: relative;
        }

        .search-box i {
            position: absolute;
            left: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--gray-500);
        }

        .search-box input {
            padding: 10px 15px 10px 45px;
            border: 1px solid var(--gray-200);
            border-radius: 25px;
            width: 300px;
            font-size: 0.9rem;
            transition: var(--transition);
        }

        .search-box input:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(42, 92, 130, 0.1);
        }

        .notification-badge {
            position: relative;
            cursor: pointer;
        }

        .notification-badge i {
            font-size: 1.3rem;
            color: var(--gray-600);
        }

        .notification-count {
            position: absolute;
            top: -5px;
            right: -5px;
            background: var(--danger);
            color: white;
            font-size: 0.7rem;
            padding: 2px 5px;
            border-radius: 10px;
        }

        .user-profile {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 5px 10px;
            border-radius: 25px;
            background: var(--gray-100);
            cursor: pointer;
            transition: var(--transition);
        }

        .user-profile:hover {
            background: var(--gray-200);
        }

        .user-avatar {
            width: 35px;
            height: 35px;
            border-radius: 50%;
            background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
        }

        .user-info {
            line-height: 1.3;
        }

        .user-info .name {
            font-weight: 600;
            font-size: 0.9rem;
            color: var(--gray-800);
        }

        .user-info .role {
            font-size: 0.8rem;
            color: var(--gray-500);
        }

        /* Navigation Bar - Styled like Management Buttons */
        .nav-bar {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            flex-wrap: wrap;
            background: white;
            padding: 15px 20px;
            border-radius: 12px;
            box-shadow: var(--card-shadow);
        }

        .nav-item {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 10px 20px;
            border-radius: 25px;
            font-size: 0.9rem;
            font-weight: 500;
            border: none;
            transition: var(--transition);
            background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
            color: white;
            text-decoration: none;
            cursor: pointer;
        }

        .nav-item i {
            font-size: 1rem;
        }

        .nav-item:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(42, 92, 130, 0.3);
        }

        .nav-item-outline {
            background: transparent;
            border: 1px solid var(--primary);
            color: var(--primary);
        }

        .nav-item-outline:hover {
            background: var(--primary);
            color: white;
        }

        .nav-item.active {
            background: linear-gradient(135deg, var(--primary-dark) 0%, var(--primary) 100%);
            box-shadow: 0 5px 15px rgba(42, 92, 130, 0.4);
        }

        .nav-divider {
            width: 1px;
            height: 30px;
            background: var(--gray-300);
            margin: auto 5px;
        }

        /* Quick Stats */
        .quick-stats {
            display: flex;
            gap: 15px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }

        .quick-stat-item {
            background: white;
            padding: 15px 20px;
            border-radius: 10px;
            box-shadow: var(--card-shadow);
            flex: 1;
            min-width: 150px;
        }

        .quick-stat-label {
            font-size: 0.85rem;
            color: var(--gray-500);
            margin-bottom: 5px;
        }

        .quick-stat-value {
            font-size: 1.5rem;
            font-weight: 700;
            color: var(--primary);
        }

        .quick-stat-sub {
            font-size: 0.8rem;
            color: var(--gray-400);
        }

        /* Stats Cards */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(6, 1fr);
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: white;
            border-radius: 15px;
            padding: 20px;
            box-shadow: var(--card-shadow);
            transition: var(--transition);
            position: relative;
            overflow: hidden;
        }

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

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

        .stat-icon {
            width: 50px;
            height: 50px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 15px;
            font-size: 1.5rem;
        }

        .stat-icon.primary { background: rgba(42, 92, 130, 0.1); color: var(--primary); }
        .stat-icon.success { background: rgba(76, 175, 80, 0.1); color: var(--success); }
        .stat-icon.warning { background: rgba(255, 152, 0, 0.1); color: var(--warning); }
        .stat-icon.info { background: rgba(0, 188, 212, 0.1); color: var(--info); }
        .stat-icon.danger { background: rgba(244, 67, 54, 0.1); color: var(--danger); }
        .stat-icon.secondary { background: rgba(90, 158, 122, 0.1); color: var(--secondary); }

        .stat-value {
            font-size: 1.8rem;
            font-weight: 700;
            color: var(--gray-800);
            margin-bottom: 5px;
        }

        .stat-label {
            color: var(--gray-500);
            font-size: 0.9rem;
            font-weight: 500;
        }

        .stat-trend {
            position: absolute;
            top: 20px;
            right: 20px;
            font-size: 0.85rem;
            padding: 3px 8px;
            border-radius: 20px;
        }

        .stat-trend.up { background: rgba(76, 175, 80, 0.1); color: var(--success); }
        .stat-trend.down { background: rgba(244, 67, 54, 0.1); color: var(--danger); }

        /* Dashboard Grid */
        .dashboard-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 25px;
            margin-bottom: 30px;
        }

        .dashboard-card {
            background: white;
            border-radius: 15px;
            box-shadow: var(--card-shadow);
            overflow: hidden;
            transition: var(--transition);
        }

        .dashboard-card:hover {
            box-shadow: var(--card-shadow-hover);
        }

        .card-header {
            padding: 20px 25px;
            border-bottom: 1px solid var(--gray-200);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .card-header h3 {
            font-size: 1.2rem;
            font-weight: 600;
            color: var(--gray-800);
            margin: 0;
        }

        .card-header h3 i {
            margin-right: 10px;
            color: var(--primary);
        }

        .card-header .badge {
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 500;
        }

        .card-body {
            padding: 20px 25px;
        }

        /* Leave Requests Table */
        .leave-table {
            width: 100%;
        }

        .leave-table tr {
            transition: var(--transition);
        }

        .leave-table td {
            padding: 15px 0;
            border-bottom: 1px solid var(--gray-200);
        }

        .leave-table tr:last-child td {
            border-bottom: none;
        }

        .staff-info {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .staff-avatar {
            width: 45px;
            height: 45px;
            border-radius: 12px;
            background: linear-gradient(135deg, var(--primary-light), var(--secondary-light));
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            font-size: 1.1rem;
            box-shadow: 0 5px 15px rgba(42, 92, 130, 0.2);
        }

        .staff-details h4 {
            font-size: 1rem;
            font-weight: 600;
            color: var(--gray-800);
            margin: 0 0 5px;
        }

        .staff-details .staff-id {
            font-size: 0.85rem;
            color: var(--gray-500);
        }

        .leave-type-badge {
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 500;
        }

        .leave-type-annual { background: rgba(42, 92, 130, 0.1); color: var(--primary); }
        .leave-type-sick { background: rgba(244, 67, 54, 0.1); color: var(--danger); }
        .leave-type-casual { background: rgba(255, 152, 0, 0.1); color: var(--warning); }
        .leave-type-maternity { background: rgba(90, 158, 122, 0.1); color: var(--secondary); }
        .leave-type-paternity { background: rgba(33, 150, 243, 0.1); color: #2196F3; }
        .leave-type-unpaid { background: rgba(108, 117, 125, 0.1); color: var(--gray-600); }

        .leave-dates {
            font-size: 0.9rem;
            color: var(--gray-600);
        }

        .leave-dates i {
            margin-right: 5px;
            color: var(--gray-400);
        }

        .status-badge {
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 500;
        }

        .status-pending { background: rgba(255, 152, 0, 0.1); color: var(--warning); }
        .status-approved { background: rgba(76, 175, 80, 0.1); color: var(--success); }
        .status-rejected { background: rgba(244, 67, 54, 0.1); color: var(--danger); }
        .status-cancelled { background: rgba(108, 117, 125, 0.1); color: var(--gray-600); }

        .btn-view {
            width: 35px;
            height: 35px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            background: var(--gray-100);
            color: var(--gray-600);
            border: none;
            transition: var(--transition);
        }

        .btn-view:hover {
            background: var(--primary);
            color: white;
        }

        /* Calendar */
        #leaveCalendarPreview {
            height: 350px;
        }

        .fc .fc-toolbar-title {
            font-size: 1rem;
            font-weight: 600;
            color: var(--gray-800);
        }

        .fc .fc-button-primary {
            background: var(--gray-100);
            border: none;
            color: var(--gray-700);
            box-shadow: none;
            transition: var(--transition);
        }

        .fc .fc-button-primary:hover {
            background: var(--primary);
            color: white;
        }

        .fc .fc-daygrid-day-number {
            color: var(--gray-700);
            font-weight: 500;
        }

        .fc-event {
            cursor: pointer;
            border-radius: 6px;
            padding: 2px 4px;
            font-size: 0.8rem;
        }

        /* Staff Table */
        .staff-table-container {
            background: white;
            border-radius: 15px;
            box-shadow: var(--card-shadow);
            overflow: hidden;
        }

        .staff-table {
            width: 100%;
            border-collapse: collapse;
        }

        .staff-table thead th {
            background: var(--gray-100);
            padding: 15px 20px;
            font-weight: 600;
            font-size: 0.9rem;
            color: var(--gray-700);
            text-align: left;
            border-bottom: 2px solid var(--gray-200);
        }

        .staff-table tbody td {
            padding: 15px 20px;
            border-bottom: 1px solid var(--gray-200);
            vertical-align: middle;
        }

        .staff-table tbody tr:hover {
            background: var(--gray-50);
        }

        .staff-table tbody tr.selected {
            background: rgba(42, 92, 130, 0.05);
        }

        .employee-id {
            font-weight: 600;
            color: var(--gray-800);
            font-size: 0.9rem;
        }

        .department-badge {
            background: rgba(90, 158, 122, 0.1);
            color: var(--secondary);
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 500;
            cursor: pointer;
            transition: var(--transition);
        }

        .department-badge:hover {
            background: var(--secondary);
            color: white;
        }

        .position-badge {
            background: rgba(42, 92, 130, 0.1);
            color: var(--primary);
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 500;
            cursor: pointer;
            transition: var(--transition);
        }

        .position-badge:hover {
            background: var(--primary);
            color: white;
        }

        .contact-info {
            font-size: 0.9rem;
        }

        .contact-info i {
            width: 20px;
            color: var(--gray-400);
            margin-right: 5px;
        }

        .shift-badge {
            background: rgba(0, 188, 212, 0.1);
            color: var(--info);
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 500;
        }

        .status-badge {
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 500;
        }

        .status-active { background: rgba(76, 175, 80, 0.1); color: var(--success); }
        .status-inactive { background: rgba(108, 117, 125, 0.1); color: var(--gray-600); }
        .status-suspended { background: rgba(255, 152, 0, 0.1); color: var(--warning); }
        .status-terminated { background: rgba(244, 67, 54, 0.1); color: var(--danger); }

        .action-buttons {
            display: flex;
            gap: 8px;
        }

        .btn-action {
            width: 35px;
            height: 35px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            border: none;
            transition: var(--transition);
        }

        .btn-view { background: rgba(42, 92, 130, 0.1); color: var(--primary); }
        .btn-edit { background: rgba(255, 152, 0, 0.1); color: var(--warning); }
        .btn-delete { background: rgba(244, 67, 54, 0.1); color: var(--danger); }
        .btn-leave { background: rgba(90, 158, 122, 0.1); color: var(--secondary); }

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

        .btn-view:hover { background: var(--primary); color: white; }
        .btn-edit:hover { background: var(--warning); color: white; }
        .btn-delete:hover { background: var(--danger); color: white; }
        .btn-leave:hover { background: var(--secondary); color: white; }

        /* Pagination */
        .pagination-container {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 20px;
            padding: 15px 20px;
            background: white;
            border-radius: 10px;
        }

        .pagination-info {
            color: var(--gray-500);
            font-size: 0.9rem;
        }

        .pagination {
            gap: 5px;
        }

        .page-link {
            border: none;
            padding: 8px 12px;
            color: var(--gray-600);
            border-radius: 6px;
            transition: var(--transition);
        }

        .page-link:hover {
            background: var(--gray-100);
            color: var(--primary);
        }

        .page-item.active .page-link {
            background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
            color: white;
        }

        /* Bulk Actions Bar */
        .bulk-actions-bar {
            position: fixed;
            bottom: 20px;
            left: 50%;
            transform: translateX(-50%);
            background: white;
            border-radius: 50px;
            padding: 10px 20px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
            display: flex;
            align-items: center;
            gap: 20px;
            z-index: 1000;
            border: 1px solid var(--gray-200);
            transition: var(--transition);
            opacity: 0;
            visibility: hidden;
        }

        .bulk-actions-bar.show {
            opacity: 1;
            visibility: visible;
        }

        .selected-count {
            font-weight: 600;
            color: var(--primary);
        }

        .bulk-actions {
            display: flex;
            gap: 10px;
        }

        .btn-bulk {
            padding: 8px 15px;
            border-radius: 25px;
            font-size: 0.9rem;
            font-weight: 500;
            border: none;
            transition: var(--transition);
        }

        .btn-bulk-delete { background: rgba(244, 67, 54, 0.1); color: var(--danger); }
        .btn-bulk-deactivate { background: rgba(255, 152, 0, 0.1); color: var(--warning); }
        .btn-bulk-export { background: rgba(42, 92, 130, 0.1); color: var(--primary); }
        .btn-bulk-clear { background: var(--gray-100); color: var(--gray-600); }

        .btn-bulk:hover {
            transform: translateY(-2px);
        }

        /* Filter Panel */
        .filter-panel {
            background: white;
            border-radius: 15px;
            margin-bottom: 30px;
            box-shadow: var(--card-shadow);
            overflow: hidden;
        }

        .filter-header {
            padding: 15px 20px;
            background: var(--gray-100);
            cursor: pointer;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .filter-header h3 {
            font-size: 1rem;
            font-weight: 600;
            color: var(--gray-700);
            margin: 0;
        }

        .filter-header i {
            transition: var(--transition);
        }

        .filter-body {
            padding: 20px;
            display: none;
        }

        .filter-body.show {
            display: block;
        }

        .filter-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
        }

        .filter-group {
            margin-bottom: 15px;
        }

        .filter-group label {
            display: block;
            font-size: 0.85rem;
            font-weight: 500;
            color: var(--gray-600);
            margin-bottom: 5px;
        }

        .filter-control {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid var(--gray-200);
            border-radius: 8px;
            font-size: 0.9rem;
            transition: var(--transition);
        }

        .filter-control:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(42, 92, 130, 0.1);
        }

        .filter-actions {
            display: flex;
            gap: 10px;
            margin-top: 20px;
            justify-content: flex-end;
        }

        /* Responsive */
        @media (max-width: 1400px) {
            .stats-grid {
                grid-template-columns: repeat(3, 1fr);
            }
        }

        @media (max-width: 1200px) {
            .main-content {
                padding: 20px;
            }
            
            .stats-grid {
                grid-template-columns: repeat(2, 1fr);
            }
            
            .dashboard-grid {
                grid-template-columns: 1fr;
            }
        }

        @media (max-width: 768px) {
            .top-bar {
                flex-direction: column;
                gap: 15px;
            }
            
            .search-box input {
                width: 100%;
            }
            
            .stats-grid {
                grid-template-columns: 1fr;
            }
            
            .staff-table {
                font-size: 0.9rem;
            }
            
            .action-buttons {
                flex-wrap: wrap;
            }
            
            .nav-bar {
                justify-content: center;
            }
        }

        /* Modal Styles */
        .department-item, .position-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 15px;
            border-bottom: 1px solid var(--gray-200);
            transition: var(--transition);
        }

        .department-item:hover, .position-item:hover {
            background: var(--gray-100);
        }

        .department-info, .position-info {
            flex: 1;
        }

        .department-name, .position-name {
            font-weight: 600;
            color: var(--gray-800);
        }

        .department-desc, .position-desc {
            font-size: 0.85rem;
            color: var(--gray-500);
        }

        .empty-list {
            text-align: center;
            padding: 30px;
            color: var(--gray-500);
        }

        .empty-list i {
            font-size: 2rem;
            margin-bottom: 10px;
            color: var(--gray-300);
        }

        .modal-header {
            background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
            color: white;
            border: none;
        }

        .modal-header .btn-close {
            filter: brightness(0) invert(1);
        }
    </style>
</head>
<body>
    <!-- Main Content -->
    <main class="main-content">
        <!-- Top Bar -->
        <div class="top-bar">
            <div class="page-title">
                <h1>Human Resource Dashboard</h1>
                <p>Manage your team members and their information</p>
            </div>
            
            <div class="top-bar-actions">
                <div class="search-box">
                    <i class="fas fa-search"></i>
                    <input type="text" id="searchInput" placeholder="Search staff..." value="{{ request('search') }}">
                </div> 
            </div>
        </div>

        <!-- Navigation Bar - Styled exactly like management buttons -->
        <div class="nav-bar">
            <a href="{{ route('dashboard') }}" class="btn btn-outline-secondary me-2">
                <i class="fas fa-tachometer-alt me-2"></i>Back to Dashboard
            </a>
            <a href="{{ route('leaves.index') }}" class="nav-item nav-item-outline">
                <i class="fas fa-calendar-alt"></i>
                Leave Management
            </a>
            <a href="{{ route('attendance.record') }}" class="nav-item nav-item-outline">
                <i class="fas fa-clock"></i>
                Attendance
            </a>
           
            <span class="nav-divider"></span>
            <a href="javascript:void(0)" class="nav-item nav-item-outline" onclick="openDepartmentsModal()">
                <i class="fas fa-building"></i>
                Manage Departments
            </a>
            <a href="javascript:void(0)" class="nav-item nav-item-outline" onclick="openPositionsModal()">
                <i class="fas fa-user-tie"></i>
                Manage Positions
            </a>
            <a href="{{ route('staff.payroll.index') }}" class="nav-item nav-item-outline">
                <i class="fas fa-money-check-alt"></i>
                Payroll
            </a>
        </div>

        <!-- Quick Stats -->
        <div class="quick-stats">
            <div class="quick-stat-item">
                <div class="quick-stat-label">Total Departments</div>
                <div class="quick-stat-value">{{ $departmentsCount ?? 0 }}</div>
                <div class="quick-stat-sub">{{ $departments->count() ?? 0 }} active</div>
            </div>
            <div class="quick-stat-item">
                <div class="quick-stat-label">Total Positions</div>
                <div class="quick-stat-value">{{ $positionsCount ?? 0 }}</div>
                <div class="quick-stat-sub">{{ $positions->count() ?? 0 }} active</div>
            </div>
        </div>

        <!-- Success/Error Messages -->
        @if(session('success'))
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <i class="fas fa-check-circle me-2"></i>
                {{ session('success') }}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        @endif
        
        @if(session('error'))
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="fas fa-exclamation-circle me-2"></i>
                {{ session('error') }}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        @endif

        <!-- Stats Cards -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-icon primary">
                    <i class="fas fa-users"></i>
                </div>
                <div class="stat-value">{{ $totalStaff ?? 0 }}</div>
                <div class="stat-label">Total Staff</div>
                <div class="stat-trend up">
                    <i class="fas fa-arrow-up"></i> +12%
                </div>
            </div>

            <div class="stat-card">
                <div class="stat-icon success">
                    <i class="fas fa-user-check"></i>
                </div>
                <div class="stat-value">{{ $activeStaff ?? 0 }}</div>
                <div class="stat-label">Active</div>
                <div class="stat-trend up">
                    <i class="fas fa-arrow-up"></i> +5%
                </div>
            </div>

            <div class="stat-card">
                <div class="stat-icon info">
                    <i class="fas fa-building"></i>
                </div>
                <div class="stat-value">{{ $departmentsCount ?? 0 }}</div>
                <div class="stat-label">Departments</div>
            </div>

            <div class="stat-card">
                <div class="stat-icon secondary">
                    <i class="fas fa-user-tie"></i>
                </div>
                <div class="stat-value">{{ $positionsCount ?? 0 }}</div>
                <div class="stat-label">Positions</div>
            </div>

            <div class="stat-card">
                <div class="stat-icon warning">
                    <i class="fas fa-calendar-exclamation"></i>
                </div>
                <div class="stat-value">{{ $pendingLeaves ?? 0 }}</div>
                <div class="stat-label">Pending Leaves</div>
                <div class="stat-trend down">
                    <i class="fas fa-arrow-down"></i> -2%
                </div>
            </div>

            <div class="stat-card">
                <div class="stat-icon success">
                    <i class="fas fa-calendar-check"></i>
                </div>
                <div class="stat-value">{{ $approvedLeaves ?? 0 }}</div>
                <div class="stat-label">Approved This Month</div>
            </div>
        </div>

        <!-- Dashboard Grid -->
        <div class="dashboard-grid">
            <!-- Recent Leave Requests -->
            <div class="dashboard-card">
                <div class="card-header">
                    <h3>
                        <i class="fas fa-calendar-exclamation"></i>
                        Recent Leave Requests
                    </h3>
                    <a href="{{ route('leaves.index') }}" class="badge" style="background: var(--primary); color: white;">View All</a>
                </div>
                <div class="card-body">
                    @php
                        $recentLeaves = \App\Models\Leave::with(['staff', 'leaveType'])
                            ->orderBy('created_at', 'desc')
                            ->limit(5)
                            ->get();
                    @endphp
                    
                    @if($recentLeaves->count() > 0)
                        <table class="leave-table">
                            @foreach($recentLeaves as $leave)
                            <tr>
                                <td>
                                    <div class="staff-info">
                                        <div class="staff-avatar">
                                            {{ substr($leave->staff->first_name ?? '', 0, 1) }}{{ substr($leave->staff->last_name ?? '', 0, 1) }}
                                        </div>
                                        <div class="staff-details">
                                            <h4>{{ $leave->staff->first_name ?? 'Unknown' }} {{ $leave->staff->last_name ?? '' }}</h4>
                                            <span class="staff-id">{{ $leave->staff->employee_id ?? 'N/A' }}</span>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <span class="leave-type-badge leave-type-{{ $leave->leave_type ?? 'annual' }}">
                                        {{ $leave->leaveType->name ?? $leave->leave_type ?? 'Annual' }}
                                    </span>
                                </td>
                                <td>
                                    <div class="leave-dates">
                                        <i class="fas fa-calendar"></i>
                                        {{ \Carbon\Carbon::parse($leave->start_date)->format('M d') }} - {{ \Carbon\Carbon::parse($leave->end_date)->format('M d') }}
                                        <br>
                                        <small style="color: var(--gray-400);">{{ $leave->duration ?? 'N/A' }} days</small>
                                    </div>
                                </td>
                                <td>
                                    <span class="status-badge status-{{ $leave->status }}">
                                        {{ ucfirst($leave->status) }}
                                    </span>
                                </td>
                                <td>
                                    <a href="{{ route('leaves.show', $leave->id) }}" class="btn-view">
                                        <i class="fas fa-eye"></i>
                                    </a>
                                </td>
                            </tr>
                            @endforeach
                        </table>
                    @else
                        <div style="text-align: center; padding: 40px 20px;">
                            <i class="fas fa-calendar-times" style="font-size: 3rem; color: var(--gray-300); margin-bottom: 15px;"></i>
                            <p style="color: var(--gray-500);">No recent leave requests</p>
                        </div>
                    @endif
                </div>
            </div>

            <!-- Fixed Calendar Preview Section -->
            <div class="dashboard-card">
                <div class="card-header">
                    <h3>
                        <i class="fas fa-calendar-alt"></i>
                        Upcoming Leave Calendar
                    </h3>
                    <div class="d-flex gap-2">
                        <button class="btn btn-sm btn-outline-primary" onclick="refreshCalendar()">
                            <i class="fas fa-sync-alt"></i>
                        </button>
                    </div>
                </div>
                <div class="card-body">
                    <div id="leaveCalendarPreview" style="height: 350px; display: none;"></div>
                    <div id="calendarLoading" class="text-center py-5">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">Loading calendar...</span>
                        </div>
                        <p class="mt-2 text-muted">Loading calendar data...</p>
                    </div>
                    <div id="calendarError" class="text-center py-5 d-none">
                        <i class="fas fa-calendar-times fa-3x text-muted mb-3"></i>
                        <p class="text-muted">Unable to load calendar. Using sample data instead.</p>
                        <button class="btn btn-sm btn-primary" onclick="loadSampleCalendarData()">
                            <i class="fas fa-redo-alt me-2"></i>Load Sample Data
                        </button>
                    </div>
                    <div id="calendarEmpty" class="text-center py-5 d-none">
                        <i class="fas fa-calendar-check fa-3x text-muted mb-3"></i>
                        <p class="text-muted">No upcoming leaves scheduled</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- Filter Panel -->
        <div class="filter-panel">
            <div class="filter-header" onclick="toggleFilters()">
                <h3>
                    <i class="fas fa-filter me-2"></i>
                    Filter Staff
                </h3>
                <i class="fas fa-chevron-down" id="filterIcon"></i>
            </div>
            <div class="filter-body" id="filterBody">
                <form action="{{ route('staff.index') }}" method="GET" id="filterForm">
                    <div class="filter-grid">
                        <div class="filter-group">
                            <label>Department</label>
                            <select class="filter-control" name="department" id="filterDepartment">
                                <option value="">All Departments</option>
                                @foreach($departments ?? [] as $department)
                                    <option value="{{ $department->id }}" {{ request('department') == $department->id ? 'selected' : '' }}>
                                        {{ $department->name }}
                                    </option>
                                @endforeach
                            </select>
                        </div>
                        
                        <div class="filter-group">
                            <label>Position</label>
                            <select class="filter-control" name="position" id="filterPosition">
                                <option value="">All Positions</option>
                                @foreach($positions ?? [] as $position)
                                    <option value="{{ $position->id }}" {{ request('position') == $position->id ? 'selected' : '' }}>
                                        {{ $position->name }}
                                    </option>
                                @endforeach
                            </select>
                        </div>
                        
                        <div class="filter-group">
                            <label>Status</label>
                            <select class="filter-control" name="status">
                                <option value="">All Statuses</option>
                                <option value="active" {{ request('status') == 'active' ? 'selected' : '' }}>Active</option>
                                <option value="inactive" {{ request('status') == 'inactive' ? 'selected' : '' }}>Inactive</option>
                                <option value="suspended" {{ request('status') == 'suspended' ? 'selected' : '' }}>Suspended</option>
                                <option value="terminated" {{ request('status') == 'terminated' ? 'selected' : '' }}>Terminated</option>
                            </select>
                        </div>
                        
                        <div class="filter-group">
                            <label>Shift</label>
                            <select class="filter-control" name="shift">
                                <option value="">All Shifts</option>
                                <option value="morning" {{ request('shift') == 'morning' ? 'selected' : '' }}>Morning</option>
                                <option value="afternoon" {{ request('shift') == 'afternoon' ? 'selected' : '' }}>Afternoon</option>
                                <option value="night" {{ request('shift') == 'night' ? 'selected' : '' }}>Night</option>
                                <option value="rotating" {{ request('shift') == 'rotating' ? 'selected' : '' }}>Rotating</option>
                            </select>
                        </div>
                        
                        <div class="filter-group">
                            <label>Hire Date From</label>
                            <input type="date" class="filter-control" name="hire_date_from" value="{{ request('hire_date_from') }}">
                        </div>
                        
                        <div class="filter-group">
                            <label>Hire Date To</label>
                            <input type="date" class="filter-control" name="hire_date_to" value="{{ request('hire_date_to') }}">
                        </div>
                    </div>
                    
                    <div class="filter-actions">
                        <button type="submit" class="btn" style="background: var(--primary); color: white; padding: 8px 20px; border-radius: 25px;">
                            <i class="fas fa-filter me-2"></i>Apply Filters
                        </button>
                        <a href="{{ route('staff.index') }}" class="btn" style="background: var(--gray-200); color: var(--gray-700); padding: 8px 20px; border-radius: 25px;">
                            <i class="fas fa-times me-2"></i>Clear
                        </a>
                    </div>
                </form>
            </div>
        </div>

        <!-- Staff Table -->
        <div class="staff-table-container">
            <div style="padding: 20px; border-bottom: 1px solid var(--gray-200); display: flex; justify-content: space-between; align-items: center;">
                <div>
                    <h3 style="font-size: 1.2rem; font-weight: 600; margin: 0;">Staff Members</h3>
                    <p style="color: var(--gray-500); font-size: 0.9rem; margin: 5px 0 0;">{{ $staff->total() ?? 0 }} total employees</p>
                </div>
                <div>
                    <a href="{{ route('staff.create') }}" class="btn" style="background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%); color: white; padding: 10px 20px; border-radius: 25px;">
                        <i class="fas fa-user-plus me-2"></i>Add Staff
                    </a>
                </div>
            </div>

            @if($staff->count() > 0)
                <div style="overflow-x: auto;">
                    <table class="staff-table">
                        <thead>
                            <tr>
                                <th width="40">
                                    <input type="checkbox" class="form-check-input" id="selectAll">
                                </th>
                                <th>Employee</th>
                                <th>ID</th>
                                <th>Department</th>
                                <th>Position</th>
                                <th>Contact</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($staff as $member)
                                <tr class="staff-row" data-staff-id="{{ $member->id }}">
                                    <td>
                                        <input type="checkbox" class="form-check-input staff-checkbox" value="{{ $member->id }}">
                                    </td>
                                    <td>
                                        <div class="staff-info">
                                            <div class="staff-avatar">
                                                @if($member->profile_picture)
                                                    <img src="{{ asset('storage/' . $member->profile_picture) }}" alt="{{ $member->first_name }}" style="width: 100%; height: 100%; object-fit: cover;">
                                                @else
                                                    {{ substr($member->first_name, 0, 1) }}{{ substr($member->last_name, 0, 1) }}
                                                @endif
                                            </div>
                                            <div class="staff-details">
                                                <h4>{{ $member->first_name }} {{ $member->last_name }}</h4>
                                                <span class="staff-id">{{ $member->email }}</span>
                                            </div>
                                        </div>
                                    </td>
                                    <td>
                                        <span class="employee-id">{{ $member->employee_id ?? 'N/A' }}</span>
                                    </td>
                                    <td>
                                        @if($member->department)
                                            <span class="department-badge" onclick="viewDepartment('{{ $member->department->id }}')">{{ $member->department->name }}</span>
                                        @else
                                            <span class="text-muted">N/A</span>
                                        @endif
                                    </td>
                                    <td>
                                        @if($member->position)
                                            <span class="position-badge" onclick="viewPosition('{{ $member->position->id }}')">{{ $member->position->name }}</span>
                                        @else
                                            <span class="text-muted">N/A</span>
                                        @endif
                                    </td>
                                    <td>
                                        <div class="contact-info">
                                            @if($member->phone)
                                                <div><i class="fas fa-phone"></i> {{ $member->phone }}</div>
                                            @endif
                                            @if($member->emergency_contact_name)
                                                <div><i class="fas fa-first-aid"></i> {{ $member->emergency_contact_name }}</div>
                                            @endif
                                        </div>
                                    </td>
                                    <td>
                                        <span class="status-badge status-{{ $member->status }}">
                                            {{ ucfirst(str_replace('_', ' ', $member->status)) }}
                                        </span>
                                    </td>
                                    <td>
                                        <div class="action-buttons">
                                            <a href="{{ route('staff.show', $member->id) }}" class="btn-action btn-view" title="View">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                            <a href="{{ route('staff.edit', $member->id) }}" class="btn-action btn-edit" title="Edit">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            <a href="{{ route('leaves.create', ['staff_id' => $member->id]) }}" class="btn-action btn-leave" title="Apply Leave">
                                                <i class="fas fa-calendar-plus"></i>
                                            </a>
                                            <button type="button" class="btn-action btn-delete" title="Delete" onclick="confirmDelete('{{ $member->id }}')">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                            <form id="deleteForm{{ $member->id }}" action="{{ route('staff.destroy', $member->id) }}" method="POST" style="display: none;">
                                                @csrf
                                                @method('DELETE')
                                            </form>
                                        </div>
                                    </td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>

                <!-- Pagination -->
                <div class="pagination-container">
                    <div class="pagination-info">
                        Showing {{ $staff->firstItem() ?? 0 }} to {{ $staff->lastItem() ?? 0 }} of {{ $staff->total() ?? 0 }} entries
                    </div>
                    <div class="pagination">
                        {{ $staff->links() }}
                    </div>
                </div>
            @else
                <div style="text-align: center; padding: 60px 20px;">
                    <i class="fas fa-users" style="font-size: 4rem; color: var(--gray-300); margin-bottom: 20px;"></i>
                    <h3 style="color: var(--gray-700); margin-bottom: 10px;">No Staff Members Found</h3>
                    <p style="color: var(--gray-500); margin-bottom: 20px;">Try adjusting your filters or add a new staff member.</p>
                    <a href="{{ route('staff.create') }}" class="btn" style="background: var(--primary); color: white; padding: 10px 25px; border-radius: 25px;">
                        <i class="fas fa-user-plus me-2"></i>Add New Staff
                    </a>
                </div>
            @endif
        </div>

        <!-- Bulk Actions Bar -->
        <div class="bulk-actions-bar" id="bulkActionsBar">
            <div>
                <span class="selected-count" id="selectedCount">0</span> staff selected
            </div>
            <div class="bulk-actions">
                <button class="btn-bulk btn-bulk-delete" id="bulkDelete">
                    <i class="fas fa-trash me-1"></i>Delete
                </button>
                <button class="btn-bulk btn-bulk-deactivate" id="bulkDeactivate">
                    <i class="fas fa-user-slash me-1"></i>Deactivate
                </button>
                <button class="btn-bulk btn-bulk-export" id="bulkExport">
                    <i class="fas fa-file-export me-1"></i>Export
                </button>
                <button class="btn-bulk btn-bulk-clear" id="clearSelection">
                    <i class="fas fa-times me-1"></i>Clear
                </button>
            </div>
        </div>
    </main>

    <!-- ==================== DEPARTMENTS MODAL (NO DELETE BUTTONS) ==================== -->
    <div class="modal fade" id="departmentsModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-building me-2"></i>Manage Departments</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <!-- Add Department Form -->
                    <form id="addDepartmentForm" class="mb-4">
                        @csrf
                        <div class="row g-3">
                            <div class="col-md-5">
                                <input type="text" class="form-control" id="departmentName" placeholder="Department Name" required>
                            </div>
                            <div class="col-md-5">
                                <input type="text" class="form-control" id="departmentDescription" placeholder="Description (optional)">
                            </div>
                            <div class="col-md-2">
                                <button type="submit" class="btn btn-success w-100">
                                    <i class="fas fa-plus me-2"></i>Add
                                </button>
                            </div>
                        </div>
                    </form>

                    <!-- Departments List - NO DELETE BUTTONS -->
                    <div id="departmentsList">
                        <!-- Departments will be loaded here via JavaScript -->
                        <div class="text-center py-4">
                            <div class="spinner-border text-primary" role="status">
                                <span class="visually-hidden">Loading...</span>
                            </div>
                            <p class="mt-2 text-muted">Loading departments...</p>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <!-- ==================== POSITIONS MODAL (NO DELETE BUTTONS) ==================== -->
    <div class="modal fade" id="positionsModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-user-tie me-2"></i>Manage Positions</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <!-- Add Position Form -->
                    <form id="addPositionForm" class="mb-4">
                        @csrf
                        <div class="row g-3">
                            <div class="col-md-4">
                                <input type="text" class="form-control" id="positionName" placeholder="Position Name" required>
                            </div>
                            <div class="col-md-3">
                                <input type="number" class="form-control" id="positionMinSalary" placeholder="Min Salary" min="0" step="1" title="Minimum salary for this role">
                            </div>
                            <div class="col-md-3">
                                <input type="number" class="form-control" id="positionMaxSalary" placeholder="Max Salary" min="0" step="1" title="Maximum salary (must be ≥ min; reversed values are auto-corrected)">
                            </div>
                            <div class="col-md-2">
                                <button type="submit" class="btn btn-success w-100">
                                    <i class="fas fa-plus me-2"></i>Add
                                </button>
                            </div>
                        </div>
                        <div class="row mt-2">
                            <div class="col-12">
                                <textarea class="form-control" id="positionDescription" placeholder="Description (optional)" rows="2"></textarea>
                            </div>
                        </div>
                    </form>

                    <!-- Positions List - NO DELETE BUTTONS -->
                    <div id="positionsList">
                        <!-- Positions will be loaded here via JavaScript -->
                        <div class="text-center py-4">
                            <div class="spinner-border text-primary" role="status">
                                <span class="visually-hidden">Loading...</span>
                            </div>
                            <p class="mt-2 text-muted">Loading positions...</p>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Delete Confirmation Modal -->
    <div class="modal fade" id="deleteModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content" style="border-radius: 15px; border: none;">
                <div class="modal-header" style="border-bottom: 1px solid var(--gray-200); padding: 20px;">
                    <h5 class="modal-title" style="font-weight: 600;">Confirm Delete</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" style="padding: 20px;">
                    <p>Are you sure you want to delete this staff member?</p>
                    <p class="text-danger" style="font-size: 0.9rem;"><i class="fas fa-exclamation-triangle me-1"></i>This action cannot be undone.</p>
                </div>
                <div class="modal-footer" style="border-top: 1px solid var(--gray-200); padding: 15px 20px;">
                    <button type="button" class="btn" style="background: var(--gray-200);" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn" style="background: var(--danger); color: white;" id="confirmDeleteBtn">Delete</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Bulk Delete Modal -->
    <div class="modal fade" id="bulkDeleteModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content" style="border-radius: 15px; border: none;">
                <div class="modal-header" style="border-bottom: 1px solid var(--gray-200); padding: 20px;">
                    <h5 class="modal-title" style="font-weight: 600;">Confirm Bulk Delete</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" style="padding: 20px;">
                    <p>Are you sure you want to delete <span id="deleteCount">0</span> selected staff members?</p>
                    <p class="text-danger" style="font-size: 0.9rem;"><i class="fas fa-exclamation-triangle me-1"></i>This action cannot be undone.</p>
                </div>
                <div class="modal-footer" style="border-top: 1px solid var(--gray-200); padding: 15px 20px;">
                    <button type="button" class="btn" style="background: var(--gray-200);" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn" style="background: var(--danger); color: white;" id="confirmBulkDelete">Delete Selected</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Scripts -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/fullcalendar@5.11.3/main.min.js"></script>
    <script src="{{ asset('js/theme-applier.js') }}"></script>
    <script>
        let deleteStaffId = null;
        let deleteModal = null;
        let bulkDeleteModal = null;
        let departmentsModal = null;
        let positionsModal = null;
        let calendar = null;

        document.addEventListener('DOMContentLoaded', function() {
            // Initialize modals
            deleteModal = new bootstrap.Modal(document.getElementById('deleteModal'));
            bulkDeleteModal = new bootstrap.Modal(document.getElementById('bulkDeleteModal'));
            departmentsModal = new bootstrap.Modal(document.getElementById('departmentsModal'));
            positionsModal = new bootstrap.Modal(document.getElementById('positionsModal'));

            // Search functionality
            const searchInput = document.getElementById('searchInput');
            if (searchInput) {
                let searchTimeout;
                searchInput.addEventListener('input', function() {
                    clearTimeout(searchTimeout);
                    searchTimeout = setTimeout(() => {
                        const url = new URL(window.location.href);
                        url.searchParams.set('search', this.value);
                        window.location.href = url.toString();
                    }, 500);
                });
            }

            // Filter toggle
            const filterBody = document.getElementById('filterBody');
            const filterIcon = document.getElementById('filterIcon');
            
            // Check if filter should be open based on URL parameters
            const urlParams = new URLSearchParams(window.location.search);
            const hasFilters = urlParams.has('department') || urlParams.has('position') || 
                              urlParams.has('status') || urlParams.has('shift') ||
                              urlParams.has('hire_date_from') || urlParams.has('hire_date_to');
            
            if (hasFilters) {
                filterBody.classList.add('show');
                filterIcon.classList.add('fa-chevron-up');
                filterIcon.classList.remove('fa-chevron-down');
            }

            // Auto-submit filters on change
            document.querySelectorAll('.filter-control').forEach(select => {
                select.addEventListener('change', function() {
                    document.getElementById('filterForm').submit();
                });
            });

            // Initialize Leave Calendar with sample data first (since API is returning 500)
            setTimeout(loadSampleCalendarData, 500);

            // Bulk Selection
            const staffCheckboxes = document.querySelectorAll('.staff-checkbox');
            const selectAllCheckbox = document.getElementById('selectAll');
            const bulkActionsBar = document.getElementById('bulkActionsBar');
            const selectedCountSpan = document.getElementById('selectedCount');

            function updateBulkActions() {
                const checked = document.querySelectorAll('.staff-checkbox:checked');
                const count = checked.length;
                
                if (count > 0) {
                    bulkActionsBar.classList.add('show');
                    selectedCountSpan.textContent = count;
                    
                    // Highlight selected rows
                    document.querySelectorAll('.staff-row').forEach(row => {
                        const checkbox = row.querySelector('.staff-checkbox');
                        if (checkbox && checkbox.checked) {
                            row.classList.add('selected');
                        } else {
                            row.classList.remove('selected');
                        }
                    });
                    
                    // Update select all checkbox
                    if (selectAllCheckbox) {
                        selectAllCheckbox.checked = count === staffCheckboxes.length;
                    }
                } else {
                    bulkActionsBar.classList.remove('show');
                    document.querySelectorAll('.staff-row').forEach(row => {
                        row.classList.remove('selected');
                    });
                }
            }

            // Select All
            if (selectAllCheckbox) {
                selectAllCheckbox.addEventListener('change', function() {
                    staffCheckboxes.forEach(checkbox => {
                        checkbox.checked = this.checked;
                    });
                    updateBulkActions();
                });
            }

            // Individual checkboxes
            staffCheckboxes.forEach(checkbox => {
                checkbox.addEventListener('change', updateBulkActions);
            });

            // Clear selection
            document.getElementById('clearSelection').addEventListener('click', function() {
                staffCheckboxes.forEach(checkbox => {
                    checkbox.checked = false;
                });
                if (selectAllCheckbox) {
                    selectAllCheckbox.checked = false;
                }
                updateBulkActions();
            });

            // Bulk Delete
            document.getElementById('bulkDelete').addEventListener('click', function() {
                const count = document.querySelectorAll('.staff-checkbox:checked').length;
                if (count > 0) {
                    document.getElementById('deleteCount').textContent = count;
                    bulkDeleteModal.show();
                }
            });

            document.getElementById('confirmBulkDelete').addEventListener('click', function() {
                const selectedIds = Array.from(document.querySelectorAll('.staff-checkbox:checked'))
                    .map(checkbox => checkbox.value);
                
                const form = document.createElement('form');
                form.method = 'POST';
                form.action = '{{ route("staff.bulk-delete") }}';
                
                const csrf = document.createElement('input');
                csrf.type = 'hidden';
                csrf.name = '_token';
                csrf.value = '{{ csrf_token() }}';
                form.appendChild(csrf);
                
                const method = document.createElement('input');
                method.type = 'hidden';
                method.name = '_method';
                method.value = 'DELETE';
                form.appendChild(method);
                
                selectedIds.forEach(id => {
                    const input = document.createElement('input');
                    input.type = 'hidden';
                    input.name = 'staff_ids[]';
                    input.value = id;
                    form.appendChild(input);
                });
                
                document.body.appendChild(form);
                form.submit();
            });

            // Bulk Deactivate
            document.getElementById('bulkDeactivate').addEventListener('click', function() {
                const selectedIds = Array.from(document.querySelectorAll('.staff-checkbox:checked'))
                    .map(checkbox => checkbox.value);
                
                if (selectedIds.length > 0 && confirm('Are you sure you want to deactivate selected staff members?')) {
                    const form = document.createElement('form');
                    form.method = 'POST';
                    form.action = '{{ route("staff.bulk-deactivate") }}';
                    
                    const csrf = document.createElement('input');
                    csrf.type = 'hidden';
                    csrf.name = '_token';
                    csrf.value = '{{ csrf_token() }}';
                    form.appendChild(csrf);
                    
                    selectedIds.forEach(id => {
                        const input = document.createElement('input');
                        input.type = 'hidden';
                        input.name = 'staff_ids[]';
                        input.value = id;
                        form.appendChild(input);
                    });
                    
                    document.body.appendChild(form);
                    form.submit();
                }
            });

            // Bulk Export
            document.getElementById('bulkExport').addEventListener('click', function() {
                const selectedIds = Array.from(document.querySelectorAll('.staff-checkbox:checked'))
                    .map(checkbox => checkbox.value);
                
                if (selectedIds.length > 0) {
                    const url = new URL('{{ route("staff.export") }}');
                    url.searchParams.set('staff_ids', selectedIds.join(','));
                    url.searchParams.set('format', 'excel');
                    window.location.href = url.toString();
                }
            });

            // Auto-dismiss alerts
            setTimeout(() => {
                document.querySelectorAll('.alert').forEach(alert => {
                    const bsAlert = new bootstrap.Alert(alert);
                    bsAlert.close();
                });
            }, 5000);
        });

        // Toggle filters
        function toggleFilters() {
            const filterBody = document.getElementById('filterBody');
            const filterIcon = document.getElementById('filterIcon');
            
            filterBody.classList.toggle('show');
            
            if (filterBody.classList.contains('show')) {
                filterIcon.classList.remove('fa-chevron-down');
                filterIcon.classList.add('fa-chevron-up');
            } else {
                filterIcon.classList.remove('fa-chevron-up');
                filterIcon.classList.add('fa-chevron-down');
            }
        }

        // Confirm delete
        function confirmDelete(staffId) {
            deleteStaffId = staffId;
            deleteModal.show();
        }

        // Handle delete confirmation
        document.getElementById('confirmDeleteBtn')?.addEventListener('click', function() {
            if (deleteStaffId) {
                document.getElementById(`deleteForm${deleteStaffId}`).submit();
            }
        });

        // Load sample calendar data (always works)
        function loadSampleCalendarData() {
            const calendarEl = document.getElementById('leaveCalendarPreview');
            const loadingEl = document.getElementById('calendarLoading');
            const errorEl = document.getElementById('calendarError');
            const emptyEl = document.getElementById('calendarEmpty');
            
            // Hide loading and error, show calendar
            loadingEl.classList.add('d-none');
            errorEl.classList.add('d-none');
            if (emptyEl) emptyEl.classList.add('d-none');
            calendarEl.style.display = 'block';
            
            // Sample data for testing
            const sampleEvents = [
                {
                    title: 'John Doe - Annual Leave',
                    start: '2024-03-15',
                    end: '2024-03-20',
                    backgroundColor: '#2A5C82',
                    borderColor: '#2A5C82',
                    textColor: '#ffffff'
                },
                {
                    title: 'Jane Smith - Sick Leave',
                    start: '2024-03-18',
                    end: '2024-03-22',
                    backgroundColor: '#DC3545',
                    borderColor: '#DC3545',
                    textColor: '#ffffff'
                },
                {
                    title: 'Mike Johnson - Casual Leave',
                    start: '2024-03-25',
                    end: '2024-03-28',
                    backgroundColor: '#FF9800',
                    borderColor: '#FF9800',
                    textColor: '#ffffff'
                },
                {
                    title: 'Sarah Wilson - Maternity Leave',
                    start: '2024-04-01',
                    end: '2024-06-01',
                    backgroundColor: '#9C27B0',
                    borderColor: '#9C27B0',
                    textColor: '#ffffff'
                },
                {
                    title: 'Robert Brown - Study Leave',
                    start: '2024-03-10',
                    end: '2024-03-15',
                    backgroundColor: '#009688',
                    borderColor: '#009688',
                    textColor: '#ffffff'
                }
            ];
            
            // Destroy existing calendar if any
            if (calendar) {
                calendar.destroy();
            }
            
            calendar = new FullCalendar.Calendar(calendarEl, {
                initialView: 'dayGridMonth',
                headerToolbar: {
                    left: 'prev,next today',
                    center: 'title',
                    right: 'dayGridMonth,dayGridWeek'
                },
                height: '100%',
                events: sampleEvents,
                eventClick: function(info) {
                    alert('Leave: ' + info.event.title);
                },
                eventDidMount: function(info) {
                    info.el.setAttribute('title', info.event.title);
                    info.el.setAttribute('data-bs-toggle', 'tooltip');
                }
            });
            
            calendar.render();
            
            // Initialize tooltips
            if (typeof bootstrap !== 'undefined') {
                setTimeout(() => {
                    const tooltips = document.querySelectorAll('[data-bs-toggle="tooltip"]');
                    tooltips.forEach(el => new bootstrap.Tooltip(el));
                }, 100);
            }
        }

        // Refresh calendar
        function refreshCalendar() {
            if (calendar) {
                calendar.refetchEvents();
            } else {
                loadSampleCalendarData();
            }
        }

        /** First validation message from Laravel JSON (HR AJAX). */
        function staffHrApiMessage(data) {
            if (!data) return 'Request failed';
            if (data.errors) {
                const parts = Object.values(data.errors).flat();
                if (parts.length) return parts[0];
            }
            return data.message || 'Request failed';
        }

        // ==================== DEPARTMENT MANAGEMENT FUNCTIONS ====================
        function openDepartmentsModal() {
            departmentsModal.show();
            loadDepartments();
        }

        function loadDepartments() {
            const departmentsList = document.getElementById('departmentsList');
            
            // Show loading
            departmentsList.innerHTML = `
                <div class="text-center py-4">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <p class="mt-2 text-muted">Loading departments...</p>
                </div>
            `;
            
            // Fetch departments via AJAX
            fetch('/api/staff/departments/list', {
                credentials: 'same-origin',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'Accept': 'application/json'
                }
            })
            .then(async response => {
                const data = await response.json().catch(() => null);
                if (!response.ok) {
                    throw new Error(staffHrApiMessage(data) || `HTTP ${response.status}`);
                }
                return data;
            })
            .then(data => {
                if (Array.isArray(data) && data.length > 0) {
                    let html = '<div class="list-group">';
                    data.forEach(dept => {
                        html += `
                            <div class="department-item" data-id="${dept.id}">
                                <div class="department-info">
                                    <div class="department-name">${dept.name}</div>
                                    <div class="department-desc">${dept.description || 'No description'}</div>
                                </div>
                            </div>
                        `;
                    });
                    html += '</div>';
                    departmentsList.innerHTML = html;
                } else {
                    departmentsList.innerHTML = `
                        <div class="empty-list">
                            <i class="fas fa-building"></i>
                            <p>No departments found. Create your first department above.</p>
                        </div>
                    `;
                }
            })
            .catch(error => {
                console.error('Error loading departments:', error);
                departmentsList.innerHTML = `
                    <div class="empty-list text-danger">
                        <i class="fas fa-exclamation-triangle"></i>
                        <p>Error loading departments. Please try again.</p>
                        <small class="text-muted">${error.message}</small>
                    </div>
                `;
            });
        }

        // Add Department Form Submit
        document.getElementById('addDepartmentForm')?.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const name = document.getElementById('departmentName').value;
            const description = document.getElementById('departmentDescription').value;
            
            // Show loading state
            const submitBtn = this.querySelector('button[type="submit"]');
            const originalText = submitBtn.innerHTML;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Adding...';
            submitBtn.disabled = true;
            
            fetch('/api/staff/departments', {
                method: 'POST',
                credentials: 'same-origin',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': '{{ csrf_token() }}',
                    'Accept': 'application/json'
                },
                body: JSON.stringify({ name, description })
            })
            .then(async response => {
                const data = await response.json().catch(() => ({}));
                if (!response.ok) {
                    showNotification(staffHrApiMessage(data), 'error');
                    return;
                }
                if (data.success) {
                    // Clear form
                    document.getElementById('departmentName').value = '';
                    document.getElementById('departmentDescription').value = '';
                    
                    // Show success message
                    showNotification('Department added successfully!', 'success');
                    
                    // Reload departments list
                    loadDepartments();
                    
                    // Refresh filter dropdown
                    refreshFilterDropdowns();
                } else {
                    showNotification(staffHrApiMessage(data), 'error');
                }
            })
            .catch(error => {
                console.error('Error adding department:', error);
                showNotification('Error adding department: ' + error.message, 'error');
            })
            .finally(() => {
                // Restore button state
                submitBtn.innerHTML = originalText;
                submitBtn.disabled = false;
            });
        });

        // ==================== POSITION MANAGEMENT FUNCTIONS ====================
        function openPositionsModal() {
            positionsModal.show();
            loadPositions();
        }

        function loadPositions() {
            const positionsList = document.getElementById('positionsList');
            
            // Show loading
            positionsList.innerHTML = `
                <div class="text-center py-4">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <p class="mt-2 text-muted">Loading positions...</p>
                </div>
            `;
            
            // Fetch positions via AJAX
            fetch('/api/staff/positions/list', {
                credentials: 'same-origin',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'Accept': 'application/json'
                }
            })
            .then(async response => {
                const data = await response.json().catch(() => null);
                if (!response.ok) {
                    throw new Error(staffHrApiMessage(data) || `HTTP ${response.status}`);
                }
                return data;
            })
            .then(data => {
                if (Array.isArray(data) && data.length > 0) {
                    let html = '<div class="list-group">';
                    data.forEach(pos => {
                        html += `
                            <div class="position-item" data-id="${pos.id}">
                                <div class="position-info">
                                    <div class="position-name">${pos.name}</div>
                                    <div class="position-desc">${pos.description || 'No description'}</div>
                                    ${pos.salary_range_min || pos.salary_range_max ? 
                                        `<small class="text-muted">Salary: UGX ${pos.salary_range_min?.toLocaleString() || 'N/A'} - ${pos.salary_range_max?.toLocaleString() || 'N/A'}</small>` : ''}
                                </div>
                            </div>
                        `;
                    });
                    html += '</div>';
                    positionsList.innerHTML = html;
                } else {
                    positionsList.innerHTML = `
                        <div class="empty-list">
                            <i class="fas fa-user-tie"></i>
                            <p>No positions found. Create your first position above.</p>
                        </div>
                    `;
                }
            })
            .catch(error => {
                console.error('Error loading positions:', error);
                positionsList.innerHTML = `
                    <div class="empty-list text-danger">
                        <i class="fas fa-exclamation-triangle"></i>
                        <p>Error loading positions. Please try again.</p>
                        <small class="text-muted">${error.message}</small>
                    </div>
                `;
            });
        }

        // Add Position Form Submit
        document.getElementById('addPositionForm')?.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const name = document.getElementById('positionName').value.trim();
            const description = document.getElementById('positionDescription').value;
            let minSalary = document.getElementById('positionMinSalary').value;
            let maxSalary = document.getElementById('positionMaxSalary').value;
            if (minSalary !== '' && maxSalary !== '') {
                const a = parseFloat(minSalary);
                const b = parseFloat(maxSalary);
                if (!isNaN(a) && !isNaN(b) && a > b) {
                    minSalary = String(b);
                    maxSalary = String(a);
                }
            }
            
            // Show loading state
            const submitBtn = this.querySelector('button[type="submit"]');
            const originalText = submitBtn.innerHTML;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Adding...';
            submitBtn.disabled = true;
            
            fetch('/api/staff/positions', {
                method: 'POST',
                credentials: 'same-origin',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': '{{ csrf_token() }}',
                    'Accept': 'application/json'
                },
                body: JSON.stringify({ 
                    name, 
                    description,
                    salary_range_min: minSalary || null,
                    salary_range_max: maxSalary || null
                })
            })
            .then(async response => {
                const data = await response.json().catch(() => ({}));
                if (!response.ok) {
                    showNotification(staffHrApiMessage(data), 'error');
                    return;
                }
                if (data.success) {
                    // Clear form
                    document.getElementById('positionName').value = '';
                    document.getElementById('positionDescription').value = '';
                    document.getElementById('positionMinSalary').value = '';
                    document.getElementById('positionMaxSalary').value = '';
                    
                    // Show success message
                    showNotification('Position added successfully!', 'success');
                    
                    // Reload positions list
                    loadPositions();
                    
                    // Refresh filter dropdown
                    refreshFilterDropdowns();
                } else {
                    showNotification(staffHrApiMessage(data), 'error');
                }
            })
            .catch(error => {
                console.error('Error adding position:', error);
                showNotification('Error adding position: ' + error.message, 'error');
            })
            .finally(() => {
                // Restore button state
                submitBtn.innerHTML = originalText;
                submitBtn.disabled = false;
            });
        });

        // Refresh filter dropdowns after changes
        function refreshFilterDropdowns() {
            // Reload departments dropdown
            fetch('/api/staff/departments/list', { credentials: 'same-origin', headers: { 'Accept': 'application/json' } })
                .then(response => response.json())
                .then(data => {
                    const deptSelect = document.getElementById('filterDepartment');
                    if (deptSelect) {
                        const currentValue = deptSelect.value;
                        deptSelect.innerHTML = '<option value="">All Departments</option>';
                        data.forEach(dept => {
                            deptSelect.innerHTML += `<option value="${dept.id}" ${currentValue == dept.id ? 'selected' : ''}>${dept.name}</option>`;
                        });
                    }
                })
                .catch(error => console.error('Error refreshing departments:', error));
            
            // Reload positions dropdown
            fetch('/api/staff/positions/list', { credentials: 'same-origin', headers: { 'Accept': 'application/json' } })
                .then(response => response.json())
                .then(data => {
                    const posSelect = document.getElementById('filterPosition');
                    if (posSelect) {
                        const currentValue = posSelect.value;
                        posSelect.innerHTML = '<option value="">All Positions</option>';
                        data.forEach(pos => {
                            posSelect.innerHTML += `<option value="${pos.id}" ${currentValue == pos.id ? 'selected' : ''}>${pos.name}</option>`;
                        });
                    }
                })
                .catch(error => console.error('Error refreshing positions:', error));
        }

        // View department details
        function viewDepartment(id) {
            showNotification('Department ID: ' + id, 'info');
        }

        // View position details
        function viewPosition(id) {
            showNotification('Position ID: ' + id, 'info');
        }

        // Show notification
        function showNotification(message, type) {
            // Create toast notification
            const toastContainer = document.createElement('div');
            toastContainer.style.position = 'fixed';
            toastContainer.style.top = '20px';
            toastContainer.style.right = '20px';
            toastContainer.style.zIndex = '9999';
            
            const toast = document.createElement('div');
            toast.className = `alert alert-${type} alert-dismissible fade show`;
            toast.innerHTML = `
                <i class="fas ${type === 'success' ? 'fa-check-circle' : type === 'error' ? 'fa-exclamation-circle' : 'fa-info-circle'} me-2"></i>
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;
            
            toastContainer.appendChild(toast);
            document.body.appendChild(toastContainer);
            
            setTimeout(() => {
                toastContainer.remove();
            }, 5000);
        }
    </script>
</body>
</html>
