<main class="main-content" id="mainContent">
    <header class="main-header">
        <div>
            <h1><?php echo strtoupper($page_title); ?></h1>
            <p class="welcome-text">Manage system users and their permissions</p>
        </div>
        <div class="header-actions">
            <?php if ($is_admin): ?>
            <button class="btn btn-primary" onclick="openCreateUserModal()">
                <i class="fas fa-plus"></i> Add New User
            </button>
            <?php endif; ?>
        </div>
    </header>

    <!-- User Statistics -->
    <section class="metrics-cards modern">
        <div class="metric-card">
            <div class="metric-icon">
                <i class="fas fa-users"></i>
            </div>
            <div class="metric-content">
                <div class="metric-value"><?php echo number_format($user_stats['total_users']); ?></div>
                <div class="metric-label">Total Users</div>
            </div>
        </div>

        <div class="metric-card">
            <div class="metric-icon active">
                <i class="fas fa-user-check"></i>
            </div>
            <div class="metric-content">
                <div class="metric-value"><?php echo number_format($user_stats['active_users']); ?></div>
                <div class="metric-label">Active Users</div>
            </div>
        </div>

        <div class="metric-card">
            <div class="metric-icon admin">
                <i class="fas fa-crown"></i>
            </div>
            <div class="metric-content">
                <div class="metric-value"><?php echo number_format($user_stats['admin_users']); ?></div>
                <div class="metric-label">Admin Users</div>
            </div>
        </div>

        <div class="metric-card">
            <div class="metric-icon user">
                <i class="fas fa-user"></i>
            </div>
            <div class="metric-content">
                <div class="metric-value"><?php echo number_format($user_stats['regular_users']); ?></div>
                <div class="metric-label">Regular Users</div>
            </div>
        </div>
    </section>

    <!-- Search and Filters -->
    <section class="search-filters-section">
        <div class="search-container">
            <div class="search-input-wrapper">
                <i class="fas fa-search"></i>
                <input type="text" id="userSearch" placeholder="Search users by name, username, or role..." class="search-input">
                <button class="search-clear" onclick="clearUserSearch()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        </div>

        <div class="filters-container">
            <div class="filter-group">
                <label class="filter-label">Role</label>
                <select id="roleFilter" onchange="applyUserFilters()" class="modern-select">
                    <option value="">All Roles</option>
                    <option value="admin">Admin</option>
                    <option value="user">User</option>
                </select>
            </div>

            <div class="filter-group">
                <label class="filter-label">Status</label>
                <select id="statusFilter" onchange="applyUserFilters()" class="modern-select">
                    <option value="">All Status</option>
                    <option value="active">Active</option>
                    <option value="inactive">Inactive</option>
                </select>
            </div>

            <div class="filter-group">
                <label class="filter-label">Sort By</label>
                <select id="sortFilter" onchange="applyUserFilters()" class="modern-select">
                    <option value="newest">Newest First</option>
                    <option value="oldest">Oldest First</option>
                    <option value="name_asc">Name A-Z</option>
                    <option value="name_desc">Name Z-A</option>
                    <option value="login_desc">Most Active</option>
                </select>
            </div>
        </div>
    </section>

    <!-- Users Grid -->
    <section class="content-area modern">
        <div class="section-header">
            <h2>All Users</h2>
            <div class="results-info">
                <span id="usersCount" class="results-count"><?php echo count($users); ?> users</span>
            </div>
        </div>
        
        <?php if (empty($users)): ?>
            <div class="empty-state">
                <div class="empty-icon">
                    <i class="fas fa-users"></i>
                </div>
                <h3>No Users Found</h3>
                <p>Get started by creating your first user account.</p>
                <?php if ($is_admin): ?>
                <button class="btn btn-primary" onclick="openCreateUserModal()">
                    <i class="fas fa-plus"></i> Create First User
                </button>
                <?php endif; ?>
            </div>
        <?php else: ?>
            <div class="users-grid modern">
                <?php foreach ($users as $user): 
                    // Format last login in IST
                    if ($user->last_login) {
                        $last_login = new DateTime($user->last_login, new DateTimeZone('UTC'));
                        $last_login->setTimezone(new DateTimeZone('Asia/Kolkata'));
                        $last_login_display = $last_login->format('M j, Y g:i A');
                        $is_active = true;
                    } else {
                        $last_login_display = 'Never';
                        $is_active = false;
                    }
                    
                    // Format created at in IST
                    $created_at = new DateTime($user->created_at, new DateTimeZone('UTC'));
                    $created_at->setTimezone(new DateTimeZone('Asia/Kolkata'));
                    $created_at_display = $created_at->format('M j, Y');
                    
                    $is_current_user = $user->id == $this->session->userdata('user_id');
                ?>
                    <div class="user-card-modern" data-user-id="<?php echo $user->id; ?>">
                        <div class="user-card-header">
                            <div class="user-avatar-section">
                                <div class="user-avatar-modern <?php echo $user->role === 'admin' ? 'admin' : 'user'; ?>">
                                    <?php echo strtoupper(substr($user->full_name ?: $user->username, 0, 1)); ?>
                                    <?php if ($user->role === 'admin'): ?>
                                        <div class="admin-crown">👑</div>
                                    <?php endif; ?>
                                </div>
                                <div class="user-status <?php echo $is_active ? 'online' : 'offline'; ?>"></div>
                            </div>
                            
                            <div class="user-actions-menu">
                                <button class="btn-icon menu-trigger">
                                    <i class="fas fa-ellipsis-v"></i>
                                </button>
                                <div class="dropdown-menu">
                                    <button class="menu-item" onclick="viewUserDetails(<?php echo $user->id; ?>)">
                                        <i class="fas fa-eye"></i> View Details
                                    </button>
                                    <?php if ($is_admin || $is_current_user): ?>
                                    <button class="menu-item" onclick="openEditUserModal(<?php echo $user->id; ?>)">
                                        <i class="fas fa-edit"></i> Edit User
                                    </button>
                                    <?php endif; ?>
                                    <?php if ($is_admin && !$is_current_user): ?>
                                    <button class="menu-item danger" onclick="deleteUser(<?php echo $user->id; ?>, '<?php echo htmlspecialchars($user->username); ?>')">
                                        <i class="fas fa-trash"></i> Delete User
                                    </button>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                        
                        <div class="user-card-body">
                            <div class="user-info">
                                <h3 class="user-name"><?php echo htmlspecialchars($user->full_name); ?></h3>
                                <p class="user-username">@<?php echo htmlspecialchars($user->username); ?></p>
                                <div class="user-role <?php echo $user->role; ?>">
                                    <?php echo ucfirst($user->role); ?>
                                    <?php if ($user->role === 'admin'): ?>👑<?php endif; ?>
                                </div>
                            </div>
                            
                            <div class="user-stats">
                                <div class="stat">
                                    <i class="fas fa-sign-in-alt"></i>
                                    <span><?php echo $user->login_count ?? 0; ?> logins</span>
                                </div>
                                <div class="stat">
                                    <i class="fas fa-clock"></i>
                                    <span><?php echo $last_login_display; ?></span>
                                </div>
                            </div>
                            
                            <div class="user-meta">
                                <div class="meta-item">
                                    <i class="fas fa-calendar"></i>
                                    <span>Joined <?php echo $created_at_display; ?></span>
                                </div>
                                <?php if ($is_current_user): ?>
                                <div class="current-user-badge">
                                    <i class="fas fa-user-check"></i>
                                    <span>Current User</span>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </section>
</main>

<!-- Create User Modal -->
<div id="createUserModal" class="modal modern">
    <div class="modal-backdrop" onclick="closeCreateUserModal()"></div>
    <div class="modal-container">
        <div class="modal-header">
            <h3>Create New User</h3>
            <button class="btn-close" onclick="closeCreateUserModal()">
                <i class="fas fa-times"></i>
            </button>
        </div>
        
        <div class="modal-body">
            <form id="createUserForm" class="modern-form">
                <div class="form-group">
                    <label class="form-label">Full Name *</label>
                    <input type="text" name="full_name" required class="form-input" placeholder="Enter full name">
                    <div class="error-message"></div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Username *</label>
                    <input type="text" name="username" required class="form-input" placeholder="Enter username">
                    <div class="error-message"></div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Password *</label>
                    <div class="password-input-wrapper">
                        <input type="password" name="password" required class="form-input" placeholder="Enter password" id="createPassword">
                        <button type="button" class="password-toggle" onclick="togglePassword('createPassword')">
                            <i class="fas fa-eye"></i>
                        </button>
                    </div>
                    <div class="error-message"></div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Confirm Password *</label>
                    <div class="password-input-wrapper">
                        <input type="password" name="confirm_password" required class="form-input" placeholder="Confirm password" id="createConfirmPassword">
                        <button type="button" class="password-toggle" onclick="togglePassword('createConfirmPassword')">
                            <i class="fas fa-eye"></i>
                        </button>
                    </div>
                    <div class="error-message"></div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Role *</label>
                    <select name="role" required class="form-select">
                        <option value="user">User</option>
                        <option value="admin">Admin</option>
                    </select>
                    <div class="error-message"></div>
                </div>
            </form>
        </div>
        
        <div class="modal-footer">
            <button class="btn btn-secondary" onclick="closeCreateUserModal()">Cancel</button>
            <button class="btn btn-primary" onclick="submitCreateUserForm()">Create User</button>
        </div>
    </div>
</div>

<!-- Edit User Modal -->
<div id="editUserModal" class="modal modern">
    <div class="modal-backdrop" onclick="closeEditUserModal()"></div>
    <div class="modal-container">
        <div class="modal-header">
            <h3>Edit User</h3>
            <button class="btn-close" onclick="closeEditUserModal()">
                <i class="fas fa-times"></i>
            </button>
        </div>
        
        <div class="modal-body">
            <form id="editUserForm" class="modern-form">
                <input type="hidden" name="user_id" id="edit_user_id">
                
                <div class="form-group">
                    <label class="form-label">Full Name *</label>
                    <input type="text" name="full_name" id="edit_full_name" required class="form-input">
                    <div class="error-message"></div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Username *</label>
                    <input type="text" name="username" id="edit_username" required class="form-input">
                    <div class="error-message"></div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Password (leave blank to keep current)</label>
                    <div class="password-input-wrapper">
                        <input type="password" name="password" id="edit_password" class="form-input" placeholder="Enter new password">
                        <button type="button" class="password-toggle" onclick="togglePassword('edit_password')">
                            <i class="fas fa-eye"></i>
                        </button>
                    </div>
                    <div class="error-message"></div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Confirm Password</label>
                    <div class="password-input-wrapper">
                        <input type="password" name="confirm_password" id="edit_confirm_password" class="form-input" placeholder="Confirm new password">
                        <button type="button" class="password-toggle" onclick="togglePassword('edit_confirm_password')">
                            <i class="fas fa-eye"></i>
                        </button>
                    </div>
                    <div class="error-message"></div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Role *</label>
                    <?php if ($is_admin): ?>
                        <select name="role" id="edit_role" required class="form-select">
                            <option value="user">User</option>
                            <option value="admin">Admin</option>
                        </select>
                    <?php else: ?>
                        <input type="text" id="edit_role_display" readonly class="form-input" style="background-color: var(--border-color);">
                        <input type="hidden" name="role" id="edit_role">
                    <?php endif; ?>
                    <div class="error-message"></div>
                </div>
            </form>
        </div>
        
        <div class="modal-footer">
            <button class="btn btn-secondary" onclick="closeEditUserModal()">Cancel</button>
            <button class="btn btn-primary" onclick="submitEditUserForm()">Update User</button>
        </div>
    </div>
</div>

<!-- User Details Modal -->
<div id="userDetailsModal" class="modal modern">
    <div class="modal-backdrop" onclick="closeUserDetailsModal()"></div>
    <div class="modal-container wide">
        <!-- Will be populated via JavaScript -->
    </div>
</div>

<style>
/* Modern Metrics Cards */
.metrics-cards.modern {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
    gap: 20px;
    margin-bottom: 30px;
}

.metric-card {
    background: var(--card-bg);
    border: 1px solid var(--border-color);
    border-radius: 16px;
    padding: 24px;
    display: flex;
    align-items: center;
    gap: 16px;
    transition: all 0.3s ease;
}

.metric-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 30px rgba(0,0,0,0.12);
}

.metric-icon {
    width: 60px;
    height: 60px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
    color: white;
}

.metric-icon { background: var(--black); }
.metric-icon.active { background: #28a745; }
.metric-icon.admin { background: #ffc107; }
.metric-icon.user { background: #6c757d; }

.metric-content {
    flex: 1;
}

.metric-value {
    font-size: 2rem;
    font-weight: 800;
    color: var(--text-color);
    line-height: 1;
    margin-bottom: 4px;
}

.metric-label {
    font-size: 0.9rem;
    color: var(--light-text);
    font-weight: 500;
}

/* Search and Filters */
.search-filters-section {
    background: var(--card-bg);
    border: 1px solid var(--border-color);
    border-radius: 16px;
    padding: 24px;
    margin-bottom: 30px;
}

.search-container {
    margin-bottom: 20px;
}

.search-input-wrapper {
    position: relative;
    display: flex;
    align-items: center;
    background: var(--card-bg);
    border: 2px solid var(--border-color);
    border-radius: 12px;
    padding: 0 16px;
    transition: all 0.3s ease;
}

.search-input-wrapper:focus-within {
    border-color: var(--black);
    box-shadow: 0 4px 20px rgba(0,0,0,0.1);
}

.search-input-wrapper .fas.fa-search {
    color: var(--light-text);
    margin-right: 12px;
}

.search-input {
    flex: 1;
    padding: 14px 0;
    border: none;
    background: none;
    font-size: 16px;
    color: var(--text-color);
    outline: none;
}

.search-input::placeholder {
    color: var(--light-text);
}

.search-clear {
    display: none;
    background: none;
    border: none;
    color: var(--light-text);
    cursor: pointer;
    padding: 6px;
    border-radius: 50%;
    transition: all 0.3s ease;
}

.search-clear:hover {
    background: var(--border-color);
    color: var(--text-color);
}

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

.filter-group {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.filter-label {
    font-weight: 600;
    color: var(--text-color);
    font-size: 0.9rem;
}

.modern-select {
    padding: 10px 12px;
    border: 1px solid var(--border-color);
    border-radius: 8px;
    background: var(--card-bg);
    color: var(--text-color);
    font-size: 14px;
    transition: border-color 0.3s ease;
}

.modern-select:focus {
    outline: none;
    border-color: var(--black);
}

/* Modern Users Grid */
.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
}

.section-header h2 {
    margin: 0;
    color: var(--text-color);
    font-weight: 700;
}

.results-info {
    display: flex;
    align-items: center;
    gap: 12px;
}

.results-count {
    color: var(--light-text);
    font-size: 0.9rem;
}

.users-grid.modern {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
    gap: 24px;
}

.user-card-modern {
    background: var(--card-bg);
    border: 1px solid var(--border-color);
    border-radius: 16px;
    overflow: hidden;
    transition: all 0.3s ease;
    position: relative;
}

.user-card-modern:hover {
    transform: translateY(-4px);
    box-shadow: 0 12px 40px rgba(0,0,0,0.15);
    border-color: var(--black);
}

.user-card-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    padding: 24px 24px 0 24px;
}

.user-avatar-section {
    position: relative;
}

.user-avatar-modern {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 28px;
    font-weight: bold;
    position: relative;
}

.user-avatar-modern.admin {
    background: linear-gradient(135deg, #000000ff, #040302ff);
}

.user-avatar-modern.user {
    background: linear-gradient(135deg, #6c757d, #0a141fff);
}

.admin-crown {
    position: absolute;
    top: -5px;
    right: -5px;
    background: gold;
    border-radius: 50%;
    width: 24px;
    height: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    border: 2px solid var(--card-bg);
}

.user-status {
    position: absolute;
    bottom: 5px;
    right: 5px;
    width: 16px;
    height: 16px;
    border-radius: 50%;
    border: 2px solid var(--card-bg);
}

.user-status.online { background: #28a745; }
.user-status.offline { background: #6c757d; }

.user-actions-menu {
    position: relative;
}

.menu-trigger {
    background: none;
    border: 1px solid var(--border-color);
    border-radius: 8px;
    padding: 8px;
    color: var(--light-text);
    cursor: pointer;
    transition: all 0.3s ease;
}

.menu-trigger:hover {
    background: var(--border-color);
    color: var(--text-color);
}

.dropdown-menu {
    position: absolute;
    top: 100%;
    right: 0;
    background: var(--card-bg);
    border: 1px solid var(--border-color);
    border-radius: 8px;
    box-shadow: 0 8px 30px rgba(0,0,0,0.15);
    padding: 8px;
    min-width: 160px;
    z-index: 100;
    display: none;
}

.user-actions-menu:hover .dropdown-menu {
    display: block;
}

.menu-item {
    display: flex;
    align-items: center;
    gap: 8px;
    width: 100%;
    padding: 8px 12px;
    border: none;
    background: none;
    
    cursor: pointer;
    border-radius: 6px;
    transition: all 0.3s ease;
    font-size: 14px;
}

.menu-item:hover {
    background: var(--border-color);
}

.menu-item.danger {
    color: #dc3545;
}

.menu-item.danger:hover {
    background: #ffebee;
}

.user-card-body {
    padding: 20px 24px 24px 24px;
}

.user-info {
    margin-bottom: 20px;
}

.user-name {
    font-size: 1.25rem;
    font-weight: 700;
    color: var(--text-color);
    margin: 0 0 4px 0;
}

.user-username {
    color: var(--light-text);
    margin: 0 0 12px 0;
    font-size: 0.9rem;
}

.user-role {
    display: inline-block;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 0.8rem;
    font-weight: 600;
    text-transform: uppercase;
}

.user-role.admin {
    background: #fff3cd;
    color: #856404;
}

.user-role.user {
    background: #e2e3e5;
    color: #383d41;
}

.user-stats {
    display: flex;
    gap: 16px;
    margin-bottom: 16px;
    padding: 16px 0;
    border-top: 1px solid var(--border-color);
    border-bottom: 1px solid var(--border-color);
}

.stat {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 0.85rem;
    color: var(--light-text);
}

.stat i {
    width: 14px;
    color: var(--text-color);
}

.user-meta {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.meta-item {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 0.85rem;
    color: var(--light-text);
}

.meta-item i {
    width: 14px;
    color: var(--text-color);
}

.current-user-badge {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px 12px;
    background: #e8f5e8;
    border: 1px solid #4caf50;
    border-radius: 8px;
    color: #2e7d32;
    font-size: 0.85rem;
    font-weight: 500;
}

/* Modern Modals */
.modal.modern {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 1000;
}

.modal-backdrop {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.5);
    backdrop-filter: blur(4px);
}

.modal-container {
    position: relative;
    background: var(--card-bg);
    margin: 5% auto;
    border-radius: 16px;
    box-shadow: 0 20px 60px rgba(0,0,0,0.3);
    max-width: 500px;
    max-height: 90vh;
    overflow-y: auto;
    animation: modalSlideIn 0.3s ease;
}

.modal-container.wide {
    max-width: 600px;
}

.modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 24px;
    border-bottom: 1px solid var(--border-color);
}

.modal-header h3 {
    margin: 0;
    color: var(--text-color);
    font-weight: 700;
}

.btn-close {
    background: none;
    border: none;
    color: var(--light-text);
    cursor: pointer;
    padding: 8px;
    border-radius: 6px;
    transition: all 0.3s ease;
}

.btn-close:hover {
    background: var(--border-color);
    color: var(--text-color);
}

.modal-body {
    padding: 24px;
}

.modal-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    padding: 20px 24px;
    border-top: 1px solid var(--border-color);
}

/* Modern Forms */
.modern-form {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.form-group {
    display: flex;
    flex-direction: column;
    gap: 6px;
}

.form-label {
    font-weight: 600;
    color: var(--text-color);
    font-size: 0.9rem;
}

.form-input,
.form-select {
    padding: 12px;
    border: 1px solid var(--border-color);
    border-radius: 8px;
    background: var(--card-bg);
    color: var(--text-color);
    font-size: 14px;
    transition: all 0.3s ease;
}

.form-input:focus,
.form-select:focus {
    outline: none;
    border-color: var(--black);
    box-shadow: 0 0 0 3px rgba(0,0,0,0.1);
}

.password-input-wrapper {
    position: relative;
    display: flex;
    align-items: center;
}

.password-input-wrapper .form-input {
    flex: 1;
    padding-right: 40px;
}

.password-toggle {
    position: absolute;
    right: 12px;
    background: none;
    border: none;
    color: var(--light-text);
    cursor: pointer;
    padding: 4px;
    border-radius: 4px;
    transition: all 0.3s ease;
}

.password-toggle:hover {
    color: var(--text-color);
    background: var(--border-color);
}

.error-message {
    color: #dc3545;
    font-size: 0.8rem;
    margin-top: 4px;
    min-height: 16px;
}

/* Empty State */
.empty-state {
    text-align: center;
    padding: 80px 40px;
    color: var(--light-text);
}

.empty-icon {
    font-size: 64px;
    margin-bottom: 20px;
    opacity: 0.3;
}

.empty-state h3 {
    margin: 0 0 12px 0;
    color: var(--text-color);
    font-weight: 600;
}

.empty-state p {
    margin: 0 0 24px 0;
    font-size: 1rem;
}

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

/* Responsive Design */
@media (max-width: 768px) {
    .metrics-cards.modern {
        grid-template-columns: repeat(2, 1fr);
        gap: 16px;
    }
    
    .metric-card {
        padding: 20px;
    }
    
    .metric-icon {
        width: 50px;
        height: 50px;
        font-size: 20px;
    }
    
    .metric-value {
        font-size: 1.5rem;
    }
    
    .users-grid.modern {
        grid-template-columns: 1fr;
    }
    
    .filters-container {
        grid-template-columns: 1fr;
    }
    
    .modal-container {
        margin: 10% 5%;
        width: auto;
    }
    
    .section-header {
        flex-direction: column;
        gap: 12px;
        align-items: flex-start;
    }
}

@media (max-width: 480px) {
    .metrics-cards.modern {
        grid-template-columns: 1fr;
    }
    
    .user-card-header {
        flex-direction: column;
        gap: 16px;
        align-items: flex-start;
    }
    
    .user-actions-menu {
        align-self: flex-end;
    }
    
    .modal-footer {
        flex-direction: column;
    }
    
    .modal-footer .btn {
        width: 100%;
    }
}
</style>

<script>
// Fixed Range Slider Functionality
function initializeRangeSlider() {
    const rangeMin = document.getElementById('modelCountMin');
    const rangeMax = document.getElementById('modelCountMax');
    const minValue = document.getElementById('modelMinValue');
    const maxValue = document.getElementById('modelMaxValue');
    
    if (!rangeMin || !rangeMax) return;
    
    function updateRangeValues() {
        const min = parseInt(rangeMin.value);
        const max = parseInt(rangeMax.value);
        
        // Ensure min doesn't exceed max
        if (min > max) {
            rangeMin.value = max;
            updateRangeValues();
            return;
        }
        
        // Update display values
        minValue.textContent = min;
        maxValue.textContent = max === 50 ? '50+' : max;
        
        // Update slider track
        const minPercent = (min / 50) * 100;
        const maxPercent = (max / 50) * 100;
        
        const slider = document.querySelector('.range-slider');
        if (slider) {
            slider.style.setProperty('--min-percent', minPercent + '%');
            slider.style.setProperty('--max-percent', maxPercent + '%');
        }
        
        // Update filters
        currentFilters.modelMin = min;
        currentFilters.modelMax = max;
        applyFilters();
    }
    
    rangeMin.addEventListener('input', updateRangeValues);
    rangeMax.addEventListener('input', updateRangeValues);
    
    // Initialize
    updateRangeValues();
}

// User Management Functions
let userSearchTimeout;

function initializeUserSearch() {
    const searchInput = document.getElementById('userSearch');
    if (!searchInput) return;
    
    searchInput.addEventListener('input', function(e) {
        const searchTerm = e.target.value.trim();
        
        // Show/hide clear button
        const clearBtn = document.querySelector('.search-clear');
        if (clearBtn) {
            clearBtn.style.display = searchTerm ? 'flex' : 'none';
        }
        
        // Debounce search
        clearTimeout(userSearchTimeout);
        userSearchTimeout = setTimeout(() => {
            applyUserFilters();
        }, 300);
    });
}

function clearUserSearch() {
    const searchInput = document.getElementById('userSearch');
    if (searchInput) {
        searchInput.value = '';
        document.querySelector('.search-clear').style.display = 'none';
        applyUserFilters();
    }
}

function applyUserFilters() {
    const searchTerm = document.getElementById('userSearch')?.value.toLowerCase() || '';
    const roleFilter = document.getElementById('roleFilter')?.value || '';
    const statusFilter = document.getElementById('statusFilter')?.value || '';
    const sortFilter = document.getElementById('sortFilter')?.value || 'newest';
    
    const userCards = document.querySelectorAll('.user-card-modern');
    let visibleCount = 0;
    
    userCards.forEach(card => {
        const userName = card.querySelector('.user-name')?.textContent.toLowerCase() || '';
        const username = card.querySelector('.user-username')?.textContent.toLowerCase() || '';
        const userRole = card.querySelector('.user-role')?.textContent.toLowerCase() || '';
        const lastLogin = card.querySelector('.stat:nth-child(2) span')?.textContent || '';
        
        let matchesSearch = !searchTerm || 
            userName.includes(searchTerm) || 
            username.includes(searchTerm);
        
        let matchesRole = !roleFilter || userRole.includes(roleFilter);
        
        let matchesStatus = !statusFilter || 
            (statusFilter === 'active' && lastLogin !== 'Never') ||
            (statusFilter === 'inactive' && lastLogin === 'Never');
        
        if (matchesSearch && matchesRole && matchesStatus) {
            card.style.display = 'block';
            visibleCount++;
        } else {
            card.style.display = 'none';
        }
    });
    
    // Update results count
    const resultsCount = document.getElementById('usersCount');
    if (resultsCount) {
        resultsCount.textContent = `${visibleCount} users`;
    }
}

function togglePassword(inputId) {
    const input = document.getElementById(inputId);
    const icon = input.parentNode.querySelector('i');
    
    if (input.type === 'password') {
        input.type = 'text';
        icon.className = 'fas fa-eye-slash';
    } else {
        input.type = 'password';
        icon.className = 'fas fa-eye';
    }
}

// Modal functions (updated for modern modals)
function openCreateUserModal() {
    document.getElementById('createUserModal').style.display = 'block';
    document.getElementById('createUserForm').reset();
    clearErrors();
}

function closeCreateUserModal() {
    document.getElementById('createUserModal').style.display = 'none';
}

function openEditUserModal(userId) {
    fetch('<?php echo base_url('admin/get_user_edit_data/'); ?>' + userId)
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            const user = data.user;
            document.getElementById('edit_user_id').value = user.id;
            document.getElementById('edit_full_name').value = user.full_name;
            document.getElementById('edit_username').value = user.username;
            
            <?php if ($is_admin): ?>
                document.getElementById('edit_role').value = user.role;
            <?php else: ?>
                document.getElementById('edit_role_display').value = user.role.charAt(0).toUpperCase() + user.role.slice(1);
                document.getElementById('edit_role').value = user.role;
            <?php endif; ?>
            
            document.getElementById('edit_password').value = '';
            document.getElementById('edit_confirm_password').value = '';
            
            document.getElementById('editUserModal').style.display = 'block';
            clearErrors();
        } else {
            showNotification('Failed to load user data: ' + data.message, 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showNotification('An error occurred while loading user data.', 'error');
    });
}

function closeEditUserModal() {
    document.getElementById('editUserModal').style.display = 'none';
}

function clearErrors() {
    const errorMessages = document.querySelectorAll('.error-message');
    errorMessages.forEach(el => el.textContent = '');
    
    const inputs = document.querySelectorAll('.form-input, .form-select');
    inputs.forEach(input => input.style.borderColor = 'var(--border-color)');
}

function submitCreateUserForm() {
    const form = document.getElementById('createUserForm');
    const formData = new FormData(form);
    
    fetch('<?php echo base_url('admin/create_user'); ?>', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification('User created successfully!', 'success');
            closeCreateUserModal();
            setTimeout(() => location.reload(), 1000);
        } else {
            clearErrors();
            for (const field in data.errors) {
                const input = form.querySelector(`[name="${field}"]`);
                const errorDiv = input.parentNode.querySelector('.error-message');
                if (input && errorDiv) {
                    input.style.borderColor = '#dc3545';
                    errorDiv.textContent = data.errors[field];
                }
            }
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showNotification('An error occurred. Please try again.', 'error');
    });
}

function submitEditUserForm() {
    const form = document.getElementById('editUserForm');
    const formData = new FormData(form);
    const userId = document.getElementById('edit_user_id').value;
    
    fetch('<?php echo base_url('admin/update_user/'); ?>' + userId, {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification('User updated successfully!', 'success');
            closeEditUserModal();
            setTimeout(() => location.reload(), 1000);
        } else {
            clearErrors();
            for (const field in data.errors) {
                const input = form.querySelector(`[name="${field}"]`);
                const errorDiv = input.parentNode.querySelector('.error-message');
                if (input && errorDiv) {
                    input.style.borderColor = '#dc3545';
                    errorDiv.textContent = data.errors[field];
                }
            }
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showNotification('An error occurred. Please try again.', 'error');
    });
}

function viewUserDetails(userId) {
    fetch('<?php echo base_url('admin/get_user_details/'); ?>' + userId)
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            const user = data.user;
            
            // Format dates in IST
            const createdDate = new Date(user.created_at + ' UTC').toLocaleString('en-IN', {
                timeZone: 'Asia/Kolkata',
                year: 'numeric',
                month: 'short',
                day: 'numeric'
            });
            
            let lastLogin = 'Never';
            if (user.last_login) {
                lastLogin = new Date(user.last_login + ' UTC').toLocaleString('en-IN', {
                    timeZone: 'Asia/Kolkata',
                    year: 'numeric',
                    month: 'short',
                    day: 'numeric',
                    hour: '2-digit',
                    minute: '2-digit',
                    hour12: true
                }) + ' IST';
            }
            
            const isCurrentUser = user.id == <?php echo $this->session->userdata('user_id'); ?>;
            
            const modalContent = `
                <div class="modal-header">
                    <div style="display: flex; align-items: center; gap: 16px;">
                        <div class="user-avatar-modern ${user.role === 'admin' ? 'admin' : 'user'}">
                            ${(user.full_name || user.username).charAt(0).toUpperCase()}
                            ${user.role === 'admin' ? '<div class="admin-crown">👑</div>' : ''}
                        </div>
                        <div>
                            <h3 style="margin: 0 0 4px 0;">${user.full_name}</h3>
                            <p style="margin: 0; color: var(--light-text);">@${user.username}</p>
                        </div>
                    </div>
                    <button class="btn-close" onclick="closeUserDetailsModal()">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                
                <div class="modal-body">
                    <div class="user-details-grid">
                        <div class="detail-card">
                            <h4>User Information</h4>
                            <div class="detail-list">
                                <div class="detail-item">
                                    <i class="fas fa-shield-alt"></i>
                                    <div>
                                        <strong>Role</strong>
                                        <span class="user-role ${user.role}">${user.role.charAt(0).toUpperCase() + user.role.slice(1)} ${user.role === 'admin' ? '👑' : ''}</span>
                                    </div>
                                </div>
                                <div class="detail-item">
                                    <i class="fas fa-calendar"></i>
                                    <div>
                                        <strong>Member Since</strong>
                                        <span>${createdDate}</span>
                                    </div>
                                </div>
                                <div class="detail-item">
                                    <i class="fas fa-clock"></i>
                                    <div>
                                        <strong>Last Login</strong>
                                        <span>${lastLogin}</span>
                                    </div>
                                </div>
                                <div class="detail-item">
                                    <i class="fas fa-sign-in-alt"></i>
                                    <div>
                                        <strong>Total Logins</strong>
                                        <span>${user.login_count || 0}</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        ${data.login_history && data.login_history.length > 0 ? `
                        <div class="detail-card">
                            <h4>Recent Login History</h4>
                            <div class="login-history">
                                ${data.login_history.slice(0, 5).map(login => {
                                    const loginTime = new Date(login.login_time + ' UTC').toLocaleString('en-IN', {
                                        timeZone: 'Asia/Kolkata',
                                        year: 'numeric',
                                        month: 'short',
                                        day: 'numeric',
                                        hour: '2-digit',
                                        minute: '2-digit',
                                        hour12: true
                                    }) + ' IST';
                                    return `
                                    <div class="login-item">
                                        <i class="fas fa-sign-in-alt"></i>
                                        <div>
                                            <span>${loginTime}</span>
                                            <small>IP: ${login.ip_address}</small>
                                        </div>
                                    </div>
                                `}).join('')}
                            </div>
                        </div>
                        ` : ''}
                    </div>
                    
                    ${isCurrentUser ? `
                    <div class="current-user-notice">
                        <i class="fas fa-user-check"></i>
                        <span>This is your account</span>
                    </div>
                    ` : ''}
                </div>
                
                <div class="modal-footer">
                    <button class="btn btn-primary" onclick="closeUserDetailsModal()">Close</button>
                </div>
            `;
            
            const modal = document.getElementById('userDetailsModal');
            const container = modal.querySelector('.modal-container');
            container.innerHTML = modalContent;
            modal.style.display = 'block';
        } else {
            showNotification('Failed to load user details: ' + data.message, 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showNotification('An error occurred while loading user details.', 'error');
    });
}

function closeUserDetailsModal() {
    document.getElementById('userDetailsModal').style.display = 'none';
}

function deleteUser(userId, username) {
    if (confirm(`Are you sure you want to delete user "${username}"? This action cannot be undone.`)) {
        fetch('<?php echo base_url('admin/delete_user/'); ?>' + userId, {
            method: 'DELETE'
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showNotification('User deleted successfully!', 'success');
                setTimeout(() => location.reload(), 1000);
            } else {
                showNotification('Failed to delete user: ' + data.message, 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showNotification('An error occurred while deleting the user.', 'error');
        });
    }
}

function showNotification(message, type) {
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    notification.innerHTML = `
        <div class="notification-content">
            <i class="fas fa-${type === 'success' ? 'check' : 'exclamation-triangle'}"></i>
            <span>${message}</span>
        </div>
    `;
    
    document.body.appendChild(notification);
    
    setTimeout(() => {
        notification.style.animation = 'slideOutRight 0.3s ease';
        setTimeout(() => notification.remove(), 300);
    }, 3000);
}

// Initialize when page loads
document.addEventListener('DOMContentLoaded', function() {
    initializeRangeSlider();
    initializeUserSearch();
    
    // Close dropdowns when clicking outside
    document.addEventListener('click', function(e) {
        if (!e.target.closest('.user-actions-menu')) {
            document.querySelectorAll('.dropdown-menu').forEach(menu => {
                menu.style.display = 'none';
            });
        }
    });
    
    // Close modals when clicking outside
    document.addEventListener('click', function(e) {
        if (e.target.classList.contains('modal-backdrop')) {
            document.querySelectorAll('.modal.modern').forEach(modal => {
                modal.style.display = 'none';
            });
        }
    });
});
</script>
<style>
    /* User Details Grid */
.user-details-grid {
    display: grid;
    gap: 20px;
}

.detail-card {
    background: var(--card-bg);
    border: 1px solid var(--border-color);
    border-radius: 12px;
    padding: 20px;
}

.detail-card h4 {
    margin: 0 0 16px 0;
    color: var(--text-color);
    font-weight: 600;
}

.detail-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.detail-item {
    display: flex;
    align-items: flex-start;
    gap: 12px;
    padding: 8px 0;
}

.detail-item i {
    color: var(--light-text);
    margin-top: 2px;
    flex-shrink: 0;
}

.detail-item div {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 2px;
}

.detail-item strong {
    color: var(--text-color);
    font-size: 0.9rem;
}

.detail-item span {
    color: var(--light-text);
    font-size: 0.85rem;
}

/* Login History */
.login-history {
    display: flex;
    flex-direction: column;
    gap: 8px;
    max-height: 200px;
    overflow-y: auto;
}

.login-item {
    display: flex;
    align-items: flex-start;
    gap: 12px;
    padding: 8px 0;
    border-bottom: 1px solid var(--border-color);
}

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

.login-item i {
    color: var(--light-text);
    margin-top: 2px;
    flex-shrink: 0;
}

.login-item div {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 2px;
}

.login-item span {
    color: var(--text-color);
    font-size: 0.85rem;
}

.login-item small {
    color: var(--light-text);
    font-size: 0.75rem;
}

/* Current User Notice */
.current-user-notice {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 12px 16px;
    background: #e8f5e8;
    border: 1px solid #4caf50;
    border-radius: 8px;
    color: #2e7d32;
    font-weight: 500;
}

/* Notifications */
.notification {
    position: fixed;
    top: 20px;
    right: 20px;
    background: var(--card-bg);
    border: 1px solid var(--border-color);
    border-radius: 8px;
    padding: 16px 20px;
    box-shadow: 0 10px 30px rgba(0,0,0,0.2);
    z-index: 10000;
    animation: slideInRight 0.3s ease;
    max-width: 300px;
}

.notification-content {
    display: flex;
    align-items: center;
    gap: 10px;
}

.notification-success {
    border-left: 4px solid #28a745;
}

.notification-error {
    border-left: 4px solid #dc3545;
}

.notification-success i { color: #28a745; }
.notification-error i { color: #dc3545; }

@keyframes slideInRight {
    from {
        transform: translateX(100%);
        opacity: 0;
    }
    to {
        transform: translateX(0);
        opacity: 1;
    }
}

@keyframes slideOutRight {
    from {
        transform: translateX(0);
        opacity: 1;
    }
    to {
        transform: translateX(100%);
        opacity: 0;
    }
}
    </style>