 <style>

    .wcmlim-container {
        max-width: 95%;
        margin: 20px auto;
        background: #ffffff;
        padding: 32px;
        border-radius: 16px;
        box-shadow: 0 4px 24px rgba(0, 0, 0, 0.04), 0 1px 4px rgba(0, 0, 0, 0.04);
        border: 1px solid #f1f5f9;
    }
    .wcmlim-users-top-grid h2 {
      font-size: 28px;
      font-weight: 700;
      color: #000;
      margin: 0;
    }
    .wcmlim-top-bar {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 24px;
      flex-wrap: wrap;
      gap: 16px;
      padding: 16px 0;
    }
    @media (max-width: 768px) {
      .wcmlim-top-bar {
        flex-direction: column;
        align-items: stretch;
        gap: 12px;
      }
      .wcmlim-search {
        width: 100%;
      }
      .wcmlim-tabs {
        justify-content: center;
      }
    }
    .wcmlim-search {
      border: 1px solid #e5e7eb;
      border-radius: 10px;
      padding: 12px 16px;
      display: flex;
      align-items: center;
      width: 280px;
      background: #ffffff;
      transition: all 0.3s ease;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
    }
    .wcmlim-search:hover {
      border-color: #d1d5db;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    }
    .wcmlim-search:focus-within {
      border-color: #6366f1;
      box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
    }
    .wcmlim-search input {
      border: none;
      outline: none;
      width: 100%;
      font-size: 14px;
      background: transparent;
      color: #374151;
    }
    .wcmlim-search input::placeholder {
      color: #9ca3af;
    }
    .wcmlim-tabs {
      display: flex;
      gap: 20px;
    }
    .wcmlim-tabs a {
      text-decoration: none;
      color: #6b7280;
      font-size: 14px;
      font-weight: 500;
      padding: 10px 18px;
      border-radius: 8px;
      transition: all 0.2s ease;
      position: relative;
    }
    .wcmlim-tabs a:hover {
      background: #f3f4f6;
      color: #374151;
    }
    .wcmlim-tabs a.wcmlim-active {
      background: #2271b1;
      color: white;
    }
    .wcmlim-users-grid {
      display: grid;
      /* grid-template-columns: repeat(auto-fit, minmax(350px, 1fr)); */
      grid-template-columns: 1fr 1fr 1fr;
      gap: 20px;
      margin-top: 24px;
    }
    @media (max-width: 768px) {
      .wcmlim-users-grid {
        grid-template-columns: 1fr;
        gap: 16px;
      }
    }
    .wcmlim-user-card {
      display: flex;
      gap: 8px;
      padding: 15px;
      background: #ffffff;
      border: 1px solid #e8e9ea;
      border-radius: 12px;
      align-items: center;
      transition: all 0.3s cubic-bezier(0.4, 0.0, 0.2, 1);
      position: relative;
      overflow: hidden;
    }
    .wcmlim-user-card::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      height: 4px;
      background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
      transform: scaleX(0);
      transition: transform 0.3s ease;
    }
    .wcmlim-user-card:hover {
      box-shadow: 0 12px 32px rgba(0, 0, 0, 0.08), 0 4px 16px rgba(0, 0, 0, 0.04);
    }
    .wcmlim-user-card.wcmlim-highlight {
      background: #ffffff;
      box-shadow: 0 4px 16px rgba(16, 185, 129, 0.08);
    }
    .wcmlim-user-card.wcmlim-highlight::before {
      background: linear-gradient(90deg, #c3c4c7 0%, #c3c4c7 100%);
    }
    .wcmlim-user-card.wcmlim-unassigned {
      background: #ffffff;
      border: 1px solid #c3c4c7;
      box-shadow: 0 4px 16px rgba(245, 158, 11, 0.08);
    }
    .wcmlim-user-card.wcmlim-unassigned::before {
      background: linear-gradient(90deg, #c3c4c7 0%, #c3c4c7 100%);
    }
    .wcmlim-avatar {
      width: 64px;
      height: 64px;
      border-radius: 50%;
      object-fit: cover;
      border: 3px solid #f3f4f6;
      transition: all 0.3s ease;
      flex-shrink: 0;
    }
    .wcmlim-avatar {
      border-color: #e5e7eb;
      transform: scale(1.05);
    }
    .wcmlim-user-info {
      flex: 1;
      min-width: 0;
    }
    .wcmlim-user-info h4 {
      margin: 0 0 6px 0;
      font-size: 17px;
      font-weight: 600;
      color: #111827;
      line-height: 1.3;
    }
    .wcmlim-user-info p {
      margin: 0 0 12px 0;
      font-size: 14px;
      color: #6b7280;
      line-height: 1.4;
    }
    .wcmlim-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 6px;
    }
    .wcmlim-tags span {
      display: inline-flex;
      align-items: center;
      background: #f8fafc;
      border: 1px solid #e2e8f0;
      border-radius: 20px;
      padding: 4px 12px;
      font-size: 12px;
      font-weight: 500;
      color: #64748b;
      transition: all 0.2s ease;
    }
    .wcmlim-tags span:hover {
      background: #e2e8f0;
      transform: translateY(-1px);
    }
    .wcmlim-users-top-grid {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding-bottom: 20px;
      border-bottom: 1px solid #f1f5f9;
    }
    @media (max-width: 768px) {
      .wcmlim-users-top-grid {
        flex-direction: column;
        align-items: flex-start;
        gap: 16px;
      }
    }
    .wcmlim-add-user-btn {
      background: #2271b1;
      color: white;
      padding: 12px 20px;
      border: none;
      border-radius: 10px;
      cursor: pointer;
      font-size: 14px;
      font-weight: 600;
      display: inline-flex;
      align-items: center;
      gap: 8px;
    }
    .wcmlim-add-user-btn:hover {
      transform: translateY(-2px);
      box-shadow: 0 8px 24px rgba(99, 102, 241, 0.3);
      background: linear-gradient(135deg, #5b21b6 0%, #7c3aed 100%);
    }
    .wcmlim-add-user-btn::before {
      content: '+';
      font-size: 18px;
      font-weight: 700;
    }
  </style>
  <div class="wcmlim-container">
    <?php
    $isShopManager = get_option('wcmlim_assign_location_shop_manager');
    if($isShopManager) {
    ?>
    <div class="wcmlim-users-top-grid">
      <h2>Location Managers</h2><button class="wcmlim-add-user-btn">Add User</button>
    </div>
    

    <div class="wcmlim-top-bar">
    
    <div class="wcmlim-search">
    <input type="text" id="wcmlim-user-search-input" placeholder="Search users by name, email, or location..." />
    </div>
    <div class="wcmlim-tabs">
    <a href="#" class="wcmlim-tab-link wcmlim-active" data-role="location_shop_manager">Location Shop Managers</a>
    <a href="#" class="wcmlim-tab-link" data-role="location_regional_manager">Location Regional Managers</a>
    </div>
    </div>

    <div class="wcmlim-users-grid" id="wcmlim-users-container">
		<?php
		function wcmlim_render_users_by_role($role_name, $meta_key = 'wcmlim_shop_manager') {
            $isLocationsGroup = get_option('wcmlim_enable_location_group');
			$terms = get_terms(array('taxonomy' => 'locations', 'hide_empty' => false, 'parent' => 0));
			$assigned_managers = [];
			
			// Get assigned managers from location meta
			foreach($terms as $term) {
				$manager_meta = get_term_meta($term->term_id, $meta_key, true);
				
				// Handle if the meta is stored as an array or single value
				if (is_array($manager_meta)) {
					foreach ($manager_meta as $manager_id) {
						if (!empty($manager_id) && !in_array($manager_id, $assigned_managers)) {
							$assigned_managers[] = (int)$manager_id;
						}
					}
				} elseif (!empty($manager_meta)) {
					$manager_id = (int)$manager_meta;
					if (!in_array($manager_id, $assigned_managers)) {
						$assigned_managers[] = $manager_id;
					}
				}
			}
			
			// Get all users with the specified role
			$args = ['role' => $role_name];
			$all_users = get_users($args);
			
			if (!empty($all_users)) {
				foreach ((array) $all_users as $key => $user) {
					// Show ALL users with this role, regardless of location assignments
					// Get user avatar
						$avatar_url = get_avatar_url($user->ID, array('size' => 55, 'default' => 'identicon'));
						
						// Get assigned locations for this user
						$user_locations = [];
						foreach($terms as $term) {
							$manager_meta = get_term_meta($term->term_id, $meta_key, true);
							if (is_array($manager_meta)) {
								if (in_array($user->ID, $manager_meta)) {
									$user_locations[] = $term->name;
								}
							} elseif ($manager_meta == $user->ID) {
								$user_locations[] = $term->name;
							}
						}
						?>
						<?php 
						// Prepare search data
						$search_data = strtolower($user->display_name . ' ' . $user->user_email . ' ' . implode(' ', $user_locations));
						?>
					<div class="wcmlim-user-card <?php echo !empty($user_locations) ? 'wcmlim-highlight' : 'wcmlim-unassigned'; ?>" 
						 data-role="<?php echo esc_attr($role_name); ?>" 
						 data-search="<?php echo esc_attr($search_data); ?>"
						 data-user-id="<?php echo esc_attr($user->ID); ?>">							
							
							<img class="wcmlim-avatar" src="<?php echo esc_url($avatar_url); ?>" alt="<?php echo esc_attr($user->display_name); ?>" />
							<div class="wcmlim-user-info">
								<h4><?php echo esc_html($user->display_name); ?></h4>
								<p><?php echo esc_html($user->user_email); ?></p>
								<div class="wcmlim-tags"> 
									<?php 
									if (!empty($user_locations)) {
										foreach ($user_locations as $location) {
											echo '<span>' . esc_html($location) . '</span>';
										}
									} else {
										echo '<span>No locations assigned</span>';
									}
									?>
								</div>
                                <!-- Action buttons (shown on hover) -->
							<div class="wcmlim-user-actions">
								<button class="wcmlim-action-btn wcmlim-edit-btn" onclick="editUser(<?php echo $user->ID; ?>, '<?php echo esc_js($role_name); ?>')" title="Edit User">
									<span class="dashicons dashicons-edit"></span>
								</button>
								<button class="wcmlim-action-btn wcmlim-delete-btn" onclick="deleteUser(<?php echo $user->ID; ?>, '<?php echo esc_js($user->display_name); ?>', '<?php echo esc_js($role_name); ?>')" title="Delete User Assignment">
									<span class="dashicons dashicons-trash"></span>
								</button>
							</div>
							</div>

						</div>
						<?php
				}
			} else {
				$role_display = $role_name == 'location_shop_manager' ? 'Shop Managers' : 'Regional Managers';
				?>
				<div class="wcmlim-user-card wcmlim-no-users" data-role="<?php echo esc_attr($role_name); ?>">
					<div class="wcmlim-user-info">
						<h4>No <?php echo esc_html($role_display); ?> Found</h4>
						<p>No users with the <?php echo esc_html($role_display); ?> role have been created yet.</p>
					</div>
				</div>
				<?php
			}
		}
		
		// Function to render regional managers with their location groups
		function wcmlim_render_regional_managers() {
			// Check if location groups are enabled
			$isLocationsGroup = get_option('wcmlim_enable_location_group');
			if ($isLocationsGroup !== 'on') {
				?>
				<div class="wcmlim-user-card wcmlim-no-users" data-role="location_regional_manager">
					<div class="wcmlim-user-info">
						<h4>Location Groups Not Enabled</h4>
						<p>Regional managers require location groups to be enabled in settings.</p>
					</div>
				</div>
				<?php
				return;
			}

			// Get all location groups
			$location_groups = get_terms(array(
				'taxonomy' => 'location_group', 
				'hide_empty' => false, 
				'parent' => 0
			));
			
			$assigned_regional_managers = [];
			
			// Get assigned regional managers from location groups
			foreach ($location_groups as $group) {
				$regional_manager_meta = get_term_meta($group->term_id, 'wcmlim_shop_regmanager', true);
				
				if (is_array($regional_manager_meta)) {
					foreach ($regional_manager_meta as $manager_id) {
						if (!empty($manager_id) && !in_array($manager_id, $assigned_regional_managers)) {
							$assigned_regional_managers[] = (int)$manager_id;
						}
					}
				} elseif (!empty($regional_manager_meta)) {
					$manager_id = (int)$regional_manager_meta;
					if (!in_array($manager_id, $assigned_regional_managers)) {
						$assigned_regional_managers[] = $manager_id;
					}
				}
			}
			
			// Get all users with regional manager role
			$args = ['role' => 'location_regional_manager'];
			$all_users = get_users($args);
			
			if (!empty($all_users)) {
				foreach ((array) $all_users as $key => $user) {
					// Show ALL users with regional manager role, regardless of group assignments
						// Get user avatar
						$avatar_url = get_avatar_url($user->ID, array('size' => 55, 'default' => 'identicon'));
						
						// Get assigned location groups for this user
						$user_groups = [];
						$user_locations = [];
						
						foreach ($location_groups as $group) {
							$regional_manager_meta = get_term_meta($group->term_id, 'wcmlim_shop_regmanager', true);
							
							// Check if this user is assigned to this group
							$is_assigned = false;
							if (is_array($regional_manager_meta)) {
								if (in_array($user->ID, $regional_manager_meta)) {
									$is_assigned = true;
								}
							} elseif ($regional_manager_meta == $user->ID) {
								$is_assigned = true;
							}
							
							if ($is_assigned) {
								$user_groups[] = $group->name;
								
								// Get locations within this group
								$group_locations = get_term_meta($group->term_id, 'wcmlim_location', true);
								if (!empty($group_locations) && is_array($group_locations)) {
									foreach ($group_locations as $location_id) {
										$location = get_term($location_id, 'locations');
										if ($location && !is_wp_error($location)) {
											$user_locations[] = $location->name;
										}
									}
								}
							}
						}
						?>
						<?php 
						// Prepare search data for regional managers (include groups and locations)
						$search_data = strtolower($user->display_name . ' ' . $user->user_email . ' ' . implode(' ', $user_groups) . ' ' . implode(' ', $user_locations));
						?>
						<div class="wcmlim-user-card <?php echo (!empty($user_groups) || !empty($user_locations)) ? 'wcmlim-highlight' : 'wcmlim-unassigned'; ?>" 
							 data-role="location_regional_manager"
							 data-search="<?php echo esc_attr($search_data); ?>"
							 data-user-id="<?php echo esc_attr($user->ID); ?>">
							
							
							
							<img class="wcmlim-avatar" src="<?php echo esc_url($avatar_url); ?>" alt="<?php echo esc_attr($user->display_name); ?>" />
							<div class="wcmlim-user-info">
								<h4><?php echo esc_html($user->display_name); ?></h4>
								<p><?php echo esc_html($user->user_email); ?></p>
								<div class="wcmlim-tags"> 
									<?php 
									if (!empty($user_groups)) {
										foreach ($user_groups as $group) {
											echo '<span style="background: #e8f4fd; border-color: #b3d9ff; color: #0066cc;">📁 ' . esc_html($group) . '</span>';
										}
									}
									if (!empty($user_locations)) {
										foreach ($user_locations as $location) {
											echo '<span style="background: #f0f8e8; border-color: #c7e6b3; color: #006600;">📍 ' . esc_html($location) . '</span>';
										}
									}
									if (empty($user_groups) && empty($user_locations)) {
										echo '<span>No groups/locations assigned</span>';
									}
									?>
								</div>
                                <!-- Action buttons (shown on hover) -->
							<div class="wcmlim-user-actions">
								<button class="wcmlim-action-btn wcmlim-edit-btn" onclick="editUser(<?php echo $user->ID; ?>, '<?php echo esc_js('location_regional_manager'); ?>')" title="Edit User">
									<span class="dashicons dashicons-edit"></span>
								</button>
								<button class="wcmlim-action-btn wcmlim-delete-btn" onclick="deleteUser(<?php echo $user->ID; ?>, '<?php echo esc_js($user->display_name); ?>', '<?php echo esc_js('location_regional_manager'); ?>')" title="Delete User Assignment">
									<span class="dashicons dashicons-trash"></span>
								</button>
							</div>
							</div>
						</div>
						<?php
				}
			} else {
				?>
				<div class="wcmlim-user-card wcmlim-no-users" data-role="location_regional_manager">
					<div class="wcmlim-user-info">
						<h4>No Regional Managers Found</h4>
						<p>No users with the Location Regional Manager role have been created yet.</p>
					</div>
				</div>
				<?php
			}
		}
		
		// Render both role types (initially only shop managers will be visible)
		wcmlim_render_users_by_role('location_shop_manager', 'wcmlim_shop_manager');
		wcmlim_render_regional_managers();
		?>
    </div>
  </div>

<!-- Edit User Modal -->
<div id="wcmlim-editUserModal" class="wcmlim-modal">
    <div class="wcmlim-modal-content">
        <div class="wcmlim-modal-header">
            <h3 id="wcmlim-modalTitle">Edit User</h3>
            <span class="wcmlim-modal-close" onclick="closeEditModal()">&times;</span>
        </div>
        <div class="wcmlim-modal-body">
            <form id="wcmlim-editUserForm">
                <input type="hidden" id="wcmlim-editUserId" name="user_id">
                <input type="hidden" id="wcmlim-editUserRole" name="user_role">
                
                <div class="wcmlim-form-group">
                    <label for="wcmlim-editFirstName">First Name *</label>
                    <input type="text" id="wcmlim-editFirstName" name="first_name" required>
                </div>
                
                <div class="wcmlim-form-group">
                    <label for="wcmlim-editLastName">Last Name *</label>
                    <input type="text" id="wcmlim-editLastName" name="last_name" required>
                </div>
                
                <div class="wcmlim-form-group">
                    <label for="wcmlim-editUserEmail">Email Address *</label>
                    <input type="email" id="wcmlim-editUserEmail" name="user_email" required>
                    <small class="wcmlim-form-note">Email must be unique and valid</small>
                </div>
                
                <div class="wcmlim-form-group">
                    <label for="wcmlim-editUserRoleSelect">User Role *</label>
                    <select id="wcmlim-editUserRoleSelect" name="user_role_select" required>
                        <option value="location_shop_manager">Location Shop Manager</option>
                        <option value="location_regional_manager">Location Regional Manager</option>
                    </select>
                </div>
                
                <div class="wcmlim-form-group">
                    <label for="wcmlim-editDisplayName">Display Name</label>
                    <input type="text" id="wcmlim-editDisplayName" name="display_name" readonly>
                    <small class="wcmlim-form-note">Automatically generated from first name and last name</small>
                </div>
                
                <!-- Location Assignment Section -->
                <div class="wcmlim-form-group" id="wcmlim-locationAssignmentSection">
                    <label id="wcmlim-locationAssignmentLabel">Assigned Locations</label>
                    <div id="wcmlim-locationAssignmentContainer">
                        <!-- This will be populated dynamically based on user role -->
                    </div>
                    <small class="wcmlim-form-note" id="wcmlim-locationAssignmentNote">Select locations/groups to assign to this user</small>
                </div>
            </form>
        </div>
        <div class="wcmlim-modal-footer">
            <button type="button" class="btn btn-secondary" onclick="closeEditModal()">Cancel</button>
            <button type="button" class="btn btn-primary" onclick="saveUserChanges()" id="wcmlim-saveUserBtn">
                <span class="wcmlim-btn-text">Save Changes</span>
                <span class="wcmlim-btn-spinner" style="display: none;">💫 Saving...</span>
            </button>
        </div>
    </div>
</div>

<!-- Add User Modal -->
<div id="wcmlim-addUserModal" class="wcmlim-modal" style="display: none;">
    <div class="wcmlim-modal-content">
        <div class="wcmlim-modal-header">
            <h3>Add New User</h3>
            <button type="button" class="wcmlim-modal-close" onclick="closeAddUserModal()">&times;</button>
        </div>
        <div class="wcmlim-modal-body">
            <form id="wcmlim-addUserForm">
                <div class="wcmlim-form-group">
                    <label for="wcmlim-newUserRole">User Role *</label>
                    <select id="wcmlim-newUserRole" name="user_role" required onchange="updateAddUserLocationSection()">
                        <option value="">Select Role</option>
                        <option value="location_shop_manager">Location Shop Manager</option>
                        <option value="location_regional_manager">Location Regional Manager</option>
                    </select>
                </div>
                
                <div class="wcmlim-form-group">
                    <label for="wcmlim-newUsername">Username *</label>
                    <input type="text" id="wcmlim-newUsername" name="username" required>
                    <small class="wcmlim-form-note">Must be unique, lowercase letters, numbers, and underscores only</small>
                </div>
                
                <div class="wcmlim-form-group">
                    <label for="wcmlim-newUserEmail">Email Address *</label>
                    <input type="email" id="wcmlim-newUserEmail" name="user_email" required>
                    <small class="wcmlim-form-note">Must be unique and valid email address</small>
                </div>
                
                <div class="wcmlim-form-group">
                    <label for="wcmlim-newFirstName">First Name *</label>
                    <input type="text" id="wcmlim-newFirstName" name="first_name" required>
                </div>
                
                <div class="wcmlim-form-group">
                    <label for="wcmlim-newLastName">Last Name *</label>
                    <input type="text" id="wcmlim-newLastName" name="last_name" required>
                </div>
                
                <div class="wcmlim-form-group">
                    <label for="wcmlim-newUserPassword">Password *</label>
                    <input type="password" id="wcmlim-newUserPassword" name="user_password" required minlength="6">
                    <small class="wcmlim-form-note">Minimum 6 characters</small>
                </div>
                
                <div class="wcmlim-form-group">
                    <label for="wcmlim-newUserPasswordConfirm">Confirm Password *</label>
                    <input type="password" id="wcmlim-newUserPasswordConfirm" name="user_password_confirm" required>
                    <small class="wcmlim-form-note">Must match the password above</small>
                </div>
                
                <!-- Location Assignment Section for New User -->
                <div class="wcmlim-form-group" id="wcmlim-newUserLocationSection" style="display: none;">
                    <label id="wcmlim-newUserLocationLabel">Assign Locations</label>
                    <div id="wcmlim-newUserLocationContainer">
                        <!-- This will be populated dynamically based on user role -->
                    </div>
                    <small class="wcmlim-form-note" id="wcmlim-newUserLocationNote">Select locations/groups to assign to this user</small>
                </div>
            </form>
        </div>
        <div class="wcmlim-modal-footer">
            <button type="button" class="btn btn-secondary" onclick="closeAddUserModal()">Cancel</button>
            <button type="button" class="btn btn-primary" onclick="createNewUser()" id="wcmlim-createUserBtn">
                <span class="wcmlim-btn-text">Create User</span>
                <span class="wcmlim-btn-spinner" style="display: none;">💫 Creating...</span>
            </button>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const tabLinks = document.querySelectorAll('.wcmlim-tab-link');
    const userCards = document.querySelectorAll('.wcmlim-user-card');
    const searchInput = document.getElementById('wcmlim-user-search-input');
    let currentRole = 'location_shop_manager'; // Track current active role

    // Add User Button Click Handler
    const addUserBtn = document.querySelector('.wcmlim-add-user-btn');
    if (addUserBtn) {
        addUserBtn.addEventListener('click', function(e) {
            e.preventDefault();
            console.log('Add User button clicked'); // Debug log
            openAddUserModal();
        });
    } else {
        console.log('Add User button not found'); // Debug log
    }

    // Function to show users for selected role
    function showUsersForRole(selectedRole) {
        currentRole = selectedRole;
        const searchTerm = searchInput.value.toLowerCase().trim();
        
        userCards.forEach(function(card) {
            const cardRole = card.getAttribute('data-role');
            const cardSearch = card.getAttribute('data-search') || '';
            
            // Check if card matches current role
            const roleMatch = cardRole === selectedRole;
            
            // Check if card matches search term (if any)
            const searchMatch = searchTerm === '' || cardSearch.includes(searchTerm);
            
            // Show card only if both role and search match
            if (roleMatch && searchMatch) {
                card.style.display = 'flex';
            } else {
                card.style.display = 'none';
            }
        });
        
        // Show "no results" message if no cards are visible for current role
        showNoResultsMessage();
    }

    // Function to show "no results" message when search yields no results
    function showNoResultsMessage() {
        const visibleCards = Array.from(userCards).filter(function(card) {
            return card.style.display === 'flex' && card.getAttribute('data-role') === currentRole;
        });
        
        // Remove any existing no-results message
        const existingMessage = document.querySelector('.wcmlim-no-search-results');
        if (existingMessage) {
            existingMessage.remove();
        }
        
        // Add no-results message if no cards are visible and there's a search term
        if (visibleCards.length === 0 && searchInput.value.trim() !== '') {
            const roleDisplay = currentRole === 'location_shop_manager' ? 'Shop Managers' : 'Regional Managers';
            const noResultsCard = document.createElement('div');
            noResultsCard.className = 'wcmlim-user-card wcmlim-no-search-results';
            noResultsCard.style.display = 'flex';
            noResultsCard.innerHTML = `
                <div class="wcmlim-user-info">
                    <h4>No ${roleDisplay} Found</h4>
                    <p>No ${roleDisplay.toLowerCase()} match your search criteria: "${searchInput.value}"</p>
                </div>
            `;
            
            // Insert after the last user card or at the beginning of users-container
            const usersContainer = document.getElementById('wcmlim-users-container');
            usersContainer.appendChild(noResultsCard);
        }
    }

    // Add click event listeners to tab links
    tabLinks.forEach(function(link) {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            
            // Remove active class from all tabs
            tabLinks.forEach(function(tab) {
                tab.classList.remove('wcmlim-active');
            });
            
            // Add active class to clicked tab
            this.classList.add('wcmlim-active');
            
            // Get the role from data attribute
            const selectedRole = this.getAttribute('data-role');
            
            // Show users for selected role (with current search applied)
            showUsersForRole(selectedRole);
        });
    });

    // Add search functionality
    if (searchInput) {
        searchInput.addEventListener('input', function() {
            // Apply search to current active role
            showUsersForRole(currentRole);
        });

        // Add search icon styling and clear button functionality
        searchInput.addEventListener('keyup', function(e) {
            // Clear search on Escape key
            if (e.key === 'Escape') {
                this.value = '';
                showUsersForRole(currentRole);
            }
        });
    }

    // Initially show only shop managers (default active tab)
    showUsersForRole('location_shop_manager');

    // Open Add User Modal
    window.openAddUserModal = function() {
        console.log('openAddUserModal called'); // Debug log
        const modal = document.getElementById('wcmlim-addUserModal');
        if (modal) {
            console.log('Modal found, opening...'); // Debug log
            modal.style.display = 'block';
            modal.style.opacity = '1';
            document.body.style.overflow = 'hidden';
            
            // Reset form
            const form = document.getElementById('wcmlim-addUserForm');
            if (form) {
                form.reset();
            }
            
            const locationSection = document.getElementById('wcmlim-newUserLocationSection');
            if (locationSection) {
                locationSection.style.display = 'none';
            }
            
            // Focus on role selection
            const roleSelect = document.getElementById('wcmlim-newUserRole');
            if (roleSelect) {
                roleSelect.focus();
            }
        } else {
            console.error('Modal with id wcmlim-addUserModal not found'); // Debug log
        }
    };

    // Close Add User Modal
    window.closeAddUserModal = function() {
        console.log('closeAddUserModal called'); // Debug log
        const modal = document.getElementById('wcmlim-addUserModal');
        if (modal) {
            modal.style.display = 'none';
            document.body.style.overflow = '';
            
            // Reset form
            const form = document.getElementById('wcmlim-addUserForm');
            if (form) {
                form.reset();
            }
            
            const locationSection = document.getElementById('wcmlim-newUserLocationSection');
            if (locationSection) {
                locationSection.style.display = 'none';
            }
            
            // Reset button state
            const createBtn = document.getElementById('wcmlim-createUserBtn');
            if (createBtn) {
                createBtn.disabled = false;
                const btnText = createBtn.querySelector('.wcmlim-btn-text');
                const btnSpinner = createBtn.querySelector('.wcmlim-btn-spinner');
                if (btnText) btnText.style.display = 'inline';
                if (btnSpinner) btnSpinner.style.display = 'none';
            }
        }
    };

    // Update location section when role changes
    window.updateAddUserLocationSection = function() {
        console.log('updateAddUserLocationSection called'); // Debug log
        const role = document.getElementById('wcmlim-newUserRole').value;
        const locationSection = document.getElementById('wcmlim-newUserLocationSection');
        
        if (role) {
            locationSection.style.display = 'block';
            loadNewUserLocationOptions(role);
        } else {
            locationSection.style.display = 'none';
        }
    };

    // Load location options for new user
    function loadNewUserLocationOptions(role) {
        console.log('loadNewUserLocationOptions called with role:', role); // Debug log
        const container = document.getElementById('wcmlim-newUserLocationContainer');
        const label = document.getElementById('wcmlim-newUserLocationLabel');
        const note = document.getElementById('wcmlim-newUserLocationNote');
        
        // Show loading state
        container.innerHTML = '<div class="wcmlim-loading-locations">Loading locations...</div>';
        
        // Update labels based on role
        if (role === 'location_shop_manager') {
            label.textContent = 'Assign Locations';
            note.textContent = 'Select individual locations to assign to this shop manager';
        } else if (role === 'location_regional_manager') {
            label.textContent = 'Assign Location Groups';
            note.textContent = 'Select location groups to assign to this regional manager';
        }
        
        // Check if wcmlim_ajax and ajaxurl are available
        if (typeof wcmlim_ajax === 'undefined' || typeof ajaxurl === 'undefined') {
            console.error('wcmlim_ajax or ajaxurl not defined');
            container.innerHTML = '<div class="wcmlim-error-message">AJAX configuration error</div>';
            return;
        }
        
        // Make AJAX request to get locations
        fetch(ajaxurl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({
                action: 'wcmlim_get_location_assignments',
                user_id: 0, // For new user
                user_role: role
            })
        })
        .then(response => response.json())
        .then(data => {
            console.log('Location data received:', data); // Debug log
            if (data.success) {
                renderNewUserLocationOptions(data.data.available, role);
            } else {
                container.innerHTML = '<div class="wcmlim-error-message">Error loading locations: ' + (data.data || 'Unknown error') + '</div>';
            }
        })
        .catch(error => {
            console.error('Error loading locations:', error);
            container.innerHTML = '<div class="wcmlim-error-message">Network error loading locations</div>';
        });
    }

    // Render location options for new user
    function renderNewUserLocationOptions(locations, role) {
        console.log('renderNewUserLocationOptions called with locations:', locations); // Debug log
        const container = document.getElementById('wcmlim-newUserLocationContainer');
        
        if (!locations || locations.length === 0) {
            container.innerHTML = '<div class="wcmlim-no-locations">No locations available</div>';
            return;
        }
        
        let html = '<div class="wcmlim-assignment-grid">';
        
        // Add select all option
        html += '<label class="wcmlim-assignment-item wcmlim-select-all">';
        html += '<input type="checkbox" onchange="toggleAllNewUserAssignments(this.checked)">';
        html += '<span class="wcmlim-assignment-name">Select All</span>';
        html += '</label>';
        
        // Add individual locations
        locations.forEach(location => {
            html += '<label class="wcmlim-assignment-item">';
            html += `<input type="checkbox" value="${location.id}" name="new_user_locations[]">`;
            html += `<span class="wcmlim-assignment-name">${location.name}</span>`;
            html += '</label>';
        });
        
        html += '</div>';
        container.innerHTML = html;
    }

    // Toggle all assignment checkboxes for new user
    window.toggleAllNewUserAssignments = function(selectAll) {
        console.log('toggleAllNewUserAssignments called with:', selectAll); // Debug log
        const checkboxes = document.querySelectorAll('#wcmlim-newUserLocationContainer input[type="checkbox"][name="new_user_locations[]"]');
        checkboxes.forEach(checkbox => {
            checkbox.checked = selectAll;
        });
    };

    // Create new user
    window.createNewUser = function() {
        console.log('createNewUser called'); // Debug log
        const form = document.getElementById('wcmlim-addUserForm');
        const createBtn = document.getElementById('wcmlim-createUserBtn');
        
        // Validate form
        if (!form.checkValidity()) {
            form.reportValidity();
            return;
        }
        
        // Check password confirmation
        const password = document.getElementById('wcmlim-newUserPassword').value;
        const confirmPassword = document.getElementById('wcmlim-newUserPasswordConfirm').value;
        
        if (password !== confirmPassword) {
            alert('Passwords do not match');
            return;
        }
        
        // Show loading state
        createBtn.disabled = true;
        const btnText = createBtn.querySelector('.wcmlim-btn-text');
        const btnSpinner = createBtn.querySelector('.wcmlim-btn-spinner');
        if (btnText) btnText.style.display = 'none';
        if (btnSpinner) btnSpinner.style.display = 'inline';
        
        // Get form data
        const formData = new FormData(form);
        
        // Get selected locations
        const selectedLocations = getNewUserSelectedAssignments();
        
        // Check if wcmlim_ajax and ajaxurl are available
        if (typeof wcmlim_ajax === 'undefined' || typeof ajaxurl === 'undefined') {
            console.error('wcmlim_ajax or ajaxurl not defined');
            alert('AJAX configuration error. Please refresh the page and try again.');
            return;
        }
        
        // Prepare FormData for AJAX (better handling of arrays)
        const ajaxData = new FormData();
        ajaxData.append('action', 'wcmlim_create_user');
        ajaxData.append('username', formData.get('username'));
        ajaxData.append('user_email', formData.get('user_email'));
        ajaxData.append('first_name', formData.get('first_name'));
        ajaxData.append('last_name', formData.get('last_name'));
        ajaxData.append('user_password', formData.get('user_password'));
        ajaxData.append('user_role', formData.get('user_role'));
        ajaxData.append('locations', selectedLocations);
        ajaxData.append('nonce', wcmlim_ajax.nonce);
        
        
        console.log('Sending AJAX data with locations:', selectedLocations); // Debug log
        
        // Make AJAX request
        fetch(ajaxurl, {
            method: 'POST',
            body: ajaxData // Using FormData directly, don't set Content-Type header
        })
        .then(response => response.json())
        .then(data => {
            console.log('User creation response:', data); // Debug log
            if (data.success) {
                alert('User created successfully!');
                closeAddUserModal();
                location.reload(); // Refresh page to show new user
            } else {
                alert('Error creating user: ' + (data.data || 'Unknown error'));
            }
        })
        .catch(error => {
            console.error('Error creating user:', error);
            alert('Error creating user. Please try again.');
        })
        .finally(() => {
            // Reset button state
            createBtn.disabled = false;
            if (btnText) btnText.style.display = 'inline';
            if (btnSpinner) btnSpinner.style.display = 'none';
        });
    };

    // Get selected assignments for new user
    function getNewUserSelectedAssignments() {
        const checkboxes = document.querySelectorAll('#wcmlim-newUserLocationContainer input[type="checkbox"]:checked[name="new_user_locations[]"]');
        return Array.from(checkboxes).map(cb => cb.value);
    }
});

// Functions for handling user actions
function editUser(userId, userRole) {
    // Prevent card click event from triggering
    event.stopPropagation();
    
    // Show loading state
    showNotification('Loading user data...', 'info');
    
    // Fetch user data via AJAX
    const formData = new FormData();
    formData.append('action', 'wcmlim_get_user_data');
    formData.append('user_id', userId);
    formData.append('security', '<?php echo wp_create_nonce('wcmlim_user_management_nonce'); ?>');
    
    fetch('<?php echo admin_url('admin-ajax.php'); ?>', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        // Remove loading notification
        const notification = document.querySelector('.wcmlim-notification');
        if (notification) notification.remove();
        
        if (data.success) {
            showEditUserModal(data.data, userRole);
        } else {
            showNotification('Error loading user data: ' + (data.data?.message || 'Unknown error'), 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showNotification('Network error: Failed to load user data.', 'error');
    });
}

function deleteUser(userId, userName, userRole) {
    // Prevent card click event from triggering
    event.stopPropagation();
    
    const roleDisplay = userRole === 'location_shop_manager' ? 'Shop Manager' : 'Regional Manager';
    const confirmMessage = `Are you sure you want to remove "${userName}" from all location assignments?\n\nThis will:\n- Remove their ${roleDisplay} role\n- Unassign them from all locations/groups\n- This action cannot be undone`;
    
    if (confirm(confirmMessage)) {
        // Show loading state
        const userCard = document.querySelector(`[data-user-id="${userId}"]`);
        if (userCard) {
            userCard.style.opacity = '0.5';
            userCard.style.pointerEvents = 'none';
        }
        
        // Perform AJAX request to remove user assignments
        removeUserAssignments(userId, userName, userRole);
    }
}

function removeUserAssignments(userId, userName, userRole) {
    // Create AJAX request
    const formData = new FormData();
    formData.append('action', 'wcmlim_remove_user_assignments');
    formData.append('user_id', userId);
    formData.append('user_role', userRole);
    formData.append('security', '<?php echo wp_create_nonce('wcmlim_user_management_nonce'); ?>');
    
    fetch('<?php echo admin_url('admin-ajax.php'); ?>', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Remove the user card with animation
            const userCard = document.querySelector(`[data-user-id="${userId}"]`);
            if (userCard) {
                userCard.style.transform = 'scale(0)';
                userCard.style.opacity = '0';
                setTimeout(() => {
                    userCard.remove();
                    // Show success message
                    showNotification(`${userName} has been successfully removed from all location assignments.`, 'success');
                }, 300);
            }
        } else {
            // Show error message
            showNotification(`Error: ${data.data.message || 'Failed to remove user assignments.'}`, 'error');
            
            // Restore user card
            const userCard = document.querySelector(`[data-user-id="${userId}"]`);
            if (userCard) {
                userCard.style.opacity = '1';
                userCard.style.pointerEvents = 'auto';
            }
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showNotification('Network error: Failed to remove user assignments.', 'error');
        
        // Restore user card
        const userCard = document.querySelector(`[data-user-id="${userId}"]`);
        if (userCard) {
            userCard.style.opacity = '1';
            userCard.style.pointerEvents = 'auto';
        }
    });
}

function showNotification(message, type = 'info') {
    // Remove any existing notifications
    const existingNotification = document.querySelector('.wcmlim-notification');
    if (existingNotification) {
        existingNotification.remove();
    }
    
    // Create notification element
    const notification = document.createElement('div');
    notification.className = `wcmlim-notification ${type}`;
    notification.innerHTML = `
        <span>${message}</span>
        <button onclick="this.parentElement.remove()" style="background:none;border:none;color:inherit;margin-left:10px;cursor:pointer;">&times;</button>
    `;
    
    // Add styles
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 15px 20px;
        border-radius: 4px;
        color: white;
        font-weight: 500;
        z-index: 9999;
        max-width: 400px;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        animation: slideInRight 0.3s ease;
        background: ${type === 'success' ? '#4caf50' : type === 'error' ? '#f44336' : '#2196f3'};
    `;
    
    // Add animation styles
    if (!document.querySelector('#notification-styles')) {
        const style = document.createElement('style');
        style.id = 'notification-styles';
        style.textContent = `
            @keyframes slideInRight {
                from { transform: translateX(100%); opacity: 0; }
                to { transform: translateX(0); opacity: 1; }
            }
        `;
        document.head.appendChild(style);
    }
    
    document.body.appendChild(notification);
    
    // Auto-remove after 5 seconds
    setTimeout(() => {
        if (notification.parentElement) {
            notification.remove();
        }
    }, 5000);
}

// Modal functions
function showEditUserModal(userData, userRole) {
    const modal = document.getElementById('wcmlim-editUserModal');
    const roleDisplay = userRole === 'location_shop_manager' ? 'Shop Manager' : 'Regional Manager';
    
    // Set modal title
    document.getElementById('wcmlim-modalTitle').textContent = `Edit ${roleDisplay}`;
    
    // Populate form fields
    document.getElementById('wcmlim-editUserId').value = userData.ID;
    document.getElementById('wcmlim-editUserRole').value = userRole;
    document.getElementById('wcmlim-editFirstName').value = userData.first_name || '';
    document.getElementById('wcmlim-editLastName').value = userData.last_name || '';
    document.getElementById('wcmlim-editUserEmail').value = userData.user_email || '';
    document.getElementById('wcmlim-editUserRoleSelect').value = userRole;
    
    // Generate and set display name from first and last name
    const firstName = userData.first_name || '';
    const lastName = userData.last_name || '';
    document.getElementById('wcmlim-editDisplayName').value = (firstName + ' ' + lastName).trim();
    
    // Add event listeners to auto-update display name when first/last name changes
    const firstNameInput = document.getElementById('wcmlim-editFirstName');
    const lastNameInput = document.getElementById('wcmlim-editLastName');
    const displayNameInput = document.getElementById('wcmlim-editDisplayName');
    
    function updateDisplayName() {
        const firstName = firstNameInput.value.trim();
        const lastName = lastNameInput.value.trim();
        displayNameInput.value = (firstName + ' ' + lastName).trim();
    }
    
    // Remove existing event listeners to avoid duplicates
    firstNameInput.removeEventListener('input', updateDisplayName);
    lastNameInput.removeEventListener('input', updateDisplayName);
    
    // Add new event listeners
    firstNameInput.addEventListener('input', updateDisplayName);
    lastNameInput.addEventListener('input', updateDisplayName);
    
    // Load location assignments based on user role
    loadLocationAssignments(userData.ID, userRole);
    
    // Show modal
    modal.style.display = 'block';
    setTimeout(() => modal.classList.add('wcmlim-show'), 10);
    
    // Focus on first input
    document.getElementById('wcmlim-editFirstName').focus();
}

function closeEditModal() {
    const modal = document.getElementById('wcmlim-editUserModal');
    modal.classList.remove('wcmlim-show');
    setTimeout(() => {
        modal.style.display = 'none';
        // Reset form
        document.getElementById('wcmlim-editUserForm').reset();
    }, 300);
}

function saveUserChanges() {
    const form = document.getElementById('wcmlim-editUserForm');
    const saveBtn = document.getElementById('wcmlim-saveUserBtn');
    const btnText = saveBtn.querySelector('.wcmlim-btn-text');
    const btnSpinner = saveBtn.querySelector('.wcmlim-btn-spinner');
    
    // Validate form
    if (!form.checkValidity()) {
        form.reportValidity();
        return;
    }
    
    // Show loading state
    saveBtn.disabled = true;
    btnText.style.display = 'none';
    btnSpinner.style.display = 'inline';
    
    // Prepare form data
    const formData = new FormData();
    formData.append('action', 'wcmlim_update_user_data');
    formData.append('user_id', document.getElementById('wcmlim-editUserId').value);
    formData.append('first_name', document.getElementById('wcmlim-editFirstName').value);
    formData.append('last_name', document.getElementById('wcmlim-editLastName').value);
    formData.append('user_email', document.getElementById('wcmlim-editUserEmail').value);
    formData.append('display_name', document.getElementById('wcmlim-editDisplayName').value);
    formData.append('user_role_select', document.getElementById('wcmlim-editUserRoleSelect').value);
    formData.append('old_role', document.getElementById('wcmlim-editUserRole').value);
    
    // Add location assignments
    const selectedAssignments = getSelectedAssignments();
    formData.append('location_assignments', JSON.stringify(selectedAssignments));
    
    formData.append('security', '<?php echo wp_create_nonce('wcmlim_user_management_nonce'); ?>');
    
    // Send AJAX request
    fetch('<?php echo admin_url('admin-ajax.php'); ?>', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        // Reset button state
        saveBtn.disabled = false;
        btnText.style.display = 'inline';
        btnSpinner.style.display = 'none';
        
        if (data.success) {
            // Close modal
            closeEditModal();
            
            // Show success message
            showNotification(data.data.message || 'User updated successfully!', 'success');
            
            // Refresh the user list to show updated data
            setTimeout(() => {
                location.reload();
            }, 1500);
        } else {
            // Show error message
            showNotification('Error: ' + (data.data?.message || 'Failed to update user'), 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        
        // Reset button state
        saveBtn.disabled = false;
        btnText.style.display = 'inline';
        btnSpinner.style.display = 'none';
        
        showNotification('Network error: Failed to update user.', 'error');
    });
}

// Close modal when clicking outside
window.onclick = function(event) {
    const modal = document.getElementById('wcmlim-editUserModal');
    if (event.target === modal) {
        closeEditModal();
    }
}

// Handle ESC key to close modal
document.addEventListener('keydown', function(event) {
    if (event.key === 'Escape') {
        const modal = document.getElementById('wcmlim-editUserModal');
        if (modal.style.display === 'block') {
            closeEditModal();
        }
    }
});

// Load location assignments based on user role
function loadLocationAssignments(userId, userRole) {
    const container = document.getElementById('wcmlim-locationAssignmentContainer');
    const label = document.getElementById('wcmlim-locationAssignmentLabel');
    const note = document.getElementById('wcmlim-locationAssignmentNote');
    
    // Show loading state
    container.innerHTML = '<div class="wcmlim-loading-spinner">Loading...</div>';
    
    // Update labels based on role
    if (userRole === 'location_shop_manager') {
        label.textContent = 'Assigned Locations';
        note.textContent = 'Select individual locations to assign to this shop manager';
    } else if (userRole === 'location_regional_manager') {
        label.textContent = 'Assigned Location Groups';
        note.textContent = 'Select location groups to assign to this regional manager';
    }
    
    // Fetch available locations/groups and current assignments
    const formData = new FormData();
    formData.append('action', 'wcmlim_get_location_assignments');
    formData.append('user_id', userId);
    formData.append('user_role', userRole);
    formData.append('security', '<?php echo wp_create_nonce('wcmlim_user_management_nonce'); ?>');
    
    fetch('<?php echo admin_url('admin-ajax.php'); ?>', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            renderLocationAssignments(data.data, userRole);
        } else {
            container.innerHTML = '<div class="wcmlim-error-message">Error loading locations: ' + (data.data?.message || 'Unknown error') + '</div>';
        }
    })
    .catch(error => {
        console.error('Error:', error);
        container.innerHTML = '<div class="wcmlim-error-message">Network error: Failed to load locations.</div>';
    });
}

// Render location assignment checkboxes
function renderLocationAssignments(data, userRole) {
    const container = document.getElementById('wcmlim-locationAssignmentContainer');
    const { available, assigned } = data;
    
    if (!available || available.length === 0) {
        const itemType = userRole === 'location_shop_manager' ? 'locations' : 'location groups';
        container.innerHTML = `<div class="wcmlim-no-items-message">No ${itemType} available for assignment.</div>`;
        return;
    }
    
    let html = '<div class="wcmlim-location-assignments-grid">';
    
    available.forEach(item => {
        const isAssigned = assigned.includes(item.id.toString());
        const itemType = userRole === 'location_shop_manager' ? 'location' : 'group';
        
        html += `
            <div class="wcmlim-assignment-item">
                <label class="wcmlim-assignment-checkbox">
                    <input type="checkbox" 
                           name="assigned_${itemType}s[]" 
                           value="${item.id}" 
                           ${isAssigned ? 'checked' : ''}
                           data-name="${item.name}">
                    <span class="wcmlim-checkmark"></span>
                    <span class="wcmlim-assignment-name">${item.name}</span>
                </label>
            </div>
        `;
    });
    
    html += '</div>';
    
    // Add select all / deselect all buttons
    html += `
        <div class="wcmlim-assignment-actions">
            <button type="button" class="wcmlim-btn-link" onclick="toggleAllAssignments(true)">Select All</button>
            <button type="button" class="wcmlim-btn-link" onclick="toggleAllAssignments(false)">Deselect All</button>
        </div>
    `;
    
    container.innerHTML = html;
}

// Toggle all assignment checkboxes
function toggleAllAssignments(selectAll) {
    const checkboxes = document.querySelectorAll('#wcmlim-locationAssignmentContainer input[type="checkbox"]');
    checkboxes.forEach(checkbox => {
        checkbox.checked = selectAll;
    });
}

// Get selected assignments
function getSelectedAssignments() {
    const checkboxes = document.querySelectorAll('#wcmlim-locationAssignmentContainer input[type="checkbox"]:checked');
    return Array.from(checkboxes).map(cb => cb.value);
}

// Modal functions are now defined inside DOMContentLoaded event above

// Update location section when role changes
function updateAddUserLocationSection() {
    const role = document.getElementById('wcmlim-newUserRole').value;
    const locationSection = document.getElementById('wcmlim-newUserLocationSection');
    
    if (role) {
        locationSection.style.display = 'block';
        loadNewUserLocationOptions(role);
    } else {
        locationSection.style.display = 'none';
    }
}

// Load location options for new user
function loadNewUserLocationOptions(role) {
    const container = document.getElementById('wcmlim-newUserLocationContainer');
    const label = document.getElementById('wcmlim-newUserLocationLabel');
    const note = document.getElementById('wcmlim-newUserLocationNote');
    
    // Show loading state
    container.innerHTML = '<div class="wcmlim-loading-locations">Loading locations...</div>';
    
    // Update labels based on role
    if (role === 'location_shop_manager') {
        label.textContent = 'Assign Locations';
        note.textContent = 'Select individual locations to assign to this shop manager';
    } else if (role === 'location_regional_manager') {
        label.textContent = 'Assign Location Groups';
        note.textContent = 'Select location groups to assign to this regional manager';
    }
    
    // Make AJAX request to get locations
    fetch(ajaxurl, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: new URLSearchParams({
            action: 'wcmlim_get_location_assignments',
            user_id: 0, // New user, no existing assignments
            user_role: role
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            renderNewUserLocationOptions(data.data.available, role);
        } else {
            container.innerHTML = '<div class="wcmlim-error-message">Error loading locations</div>';
        }
    })
    .catch(error => {
        console.error('Error loading locations:', error);
        container.innerHTML = '<div class="wcmlim-error-message">Error loading locations</div>';
    });
}

// Render location options for new user
function renderNewUserLocationOptions(locations, role) {
    const container = document.getElementById('wcmlim-newUserLocationContainer');
    
    if (!locations || locations.length === 0) {
        container.innerHTML = '<div class="wcmlim-no-locations">No locations available</div>';
        return;
    }
    
    let html = '<div class="wcmlim-assignment-grid">';
    
    // Add select all option
    html += '<label class="wcmlim-assignment-item wcmlim-select-all">';
    html += '<input type="checkbox" onchange="toggleAllNewUserAssignments(this.checked)">';
    html += '<span class="wcmlim-assignment-name">Select All</span>';
    html += '</label>';
    
    // Add individual locations
    locations.forEach(location => {
        html += '<label class="wcmlim-assignment-item">';
        html += `<input type="checkbox" value="${location.id}" name="new_user_locations[]">`;
        html += `<span class="wcmlim-assignment-name">${location.name}</span>`;
        html += '</label>';
    });
    
    html += '</div>';
    container.innerHTML = html;
}

// Toggle all assignment checkboxes for new user
function toggleAllNewUserAssignments(selectAll) {
    const checkboxes = document.querySelectorAll('#wcmlim-newUserLocationContainer input[type="checkbox"][name="new_user_locations[]"]');
    checkboxes.forEach(checkbox => {
        checkbox.checked = selectAll;
    });
}

// Create new user
function createNewUser() {
    const form = document.getElementById('wcmlim-addUserForm');
    const createBtn = document.getElementById('wcmlim-createUserBtn');
    
    // Validate form
    if (!form.checkValidity()) {
        form.reportValidity();
        return;
    }
    
    // Check password confirmation
    const password = document.getElementById('wcmlim-newUserPassword').value;
    const confirmPassword = document.getElementById('wcmlim-newUserPasswordConfirm').value;
    
    if (password !== confirmPassword) {
        alert('Passwords do not match');
        return;
    }
    
    // Show loading state
    createBtn.disabled = true;
    createBtn.querySelector('.wcmlim-btn-text').style.display = 'none';
    createBtn.querySelector('.wcmlim-btn-spinner').style.display = 'inline';
    
    // Get form data
    const formData = new FormData(form);
    
    // Get selected locations
    const selectedLocations = getNewUserSelectedAssignments();
    
    // Prepare data for AJAX
    const data = {
        action: 'wcmlim_create_user',
        username: formData.get('username'),
        user_email: formData.get('user_email'),
        first_name: formData.get('first_name'),
        last_name: formData.get('last_name'),
        user_password: formData.get('user_password'),
        user_role: formData.get('user_role'),
        locations: selectedLocations
    };
    
    // Make AJAX request
    fetch(ajaxurl, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: new URLSearchParams(data)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('User created successfully!');
            closeAddUserModal();
            location.reload(); // Refresh page to show new user
        } else {
            alert('Error creating user: ' + (data.data || 'Unknown error'));
        }
    })
    .catch(error => {
        console.error('Error creating user:', error);
        alert('Error creating user. Please try again.');
    })
    .finally(() => {
        // Reset button state
        createBtn.disabled = false;
        createBtn.querySelector('.wcmlim-btn-text').style.display = 'inline';
        createBtn.querySelector('.wcmlim-btn-spinner').style.display = 'none';
    });
}

// Get selected assignments for new user
function getNewUserSelectedAssignments() {
    const checkboxes = document.querySelectorAll('#wcmlim-newUserLocationContainer input[type="checkbox"]:checked[name="new_user_locations[]"]');
    return Array.from(checkboxes).map(cb => cb.value);
}
</script>

<style>
.wcmlim-user-card {
    display: none; /* Initially hide all cards, JavaScript will show appropriate ones */
}

/* Search functionality styles */
.wcmlim-search {
    position: relative;
}

.wcmlim-search input {
    transition: border-color 0.2s ease;
}

.wcmlim-search input:focus {
    border-color: transparent;
    box-shadow: 0 0 0 0 rgba(108, 139, 255, 0.2);
    outline: none;
}

/* Highlight matching text in search results */
.wcmlim-user-card.wcmlim-search-highlight {
    animation: highlightPulse 0.3s ease-in-out;
}

@keyframes highlightPulse {
    0% { transform: scale(1); }
    50% { transform: scale(1.02); }
    100% { transform: scale(1); }
}

/* No results message styling */
.wcmlim-no-search-results {
    grid-column: 1 / -1; /* Span all columns */
    justify-content: center;
    text-align: center;
    padding: 40px 20px;
    background: #f9f9f9;
    border: 2px dashed #ddd;
    color: #666;
}

.wcmlim-no-search-results h4 {
    color: #666;
    margin-bottom: 8px;
}

.wcmlim-no-search-results p {
    color: #888;
    font-style: italic;
}

/* Search input placeholder styling */
.wcmlim-search input::placeholder {
    color: #999;
    font-style: italic;
}

/* User card hover effects and action buttons */
.wcmlim-user-card {
    position: relative;
    cursor: pointer;
    opacity: 0;
    animation: fadeInUp 0.5s ease forwards;
}

@keyframes fadeInUp {
    from {
        opacity: 0;
        transform: translateY(20px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.wcmlim-user-card:nth-child(1) { animation-delay: 0.1s; }
.wcmlim-user-card:nth-child(2) { animation-delay: 0.2s; }
.wcmlim-user-card:nth-child(3) { animation-delay: 0.3s; }
.wcmlim-user-card:nth-child(4) { animation-delay: 0.4s; }
.wcmlim-user-card:nth-child(5) { animation-delay: 0.5s; }
.wcmlim-user-card:nth-child(6) { animation-delay: 0.6s; }

.wcmlim-user-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}


/* Individual action buttons */
.wcmlim-action-btn {
    width: 36px;
    height: 36px;
    border-radius: 8px;
    border: none;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
}

.wcmlim-edit-btn {
    color: #000;
}

.wcmlim-delete-btn {
    color: #000;
}

.wcmlim-action-btn .dashicons {
    font-size: 16px;
    width: 16px;
    height: 16px;
    line-height: 16px;
}

.wcmlim-user-actions {
    display: flex;
    gap: 5px;
    margin-top: 10px;
}
/* Hover effect for entire card */
.wcmlim-user-card:hover {
    background: #fafafa;
    border-color: #c3c4c7;
}


/* Edit User Modal Styles */
.wcmlim-modal {
    display: none;
    position: fixed;
    z-index: 10000;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    opacity: 0;
    padding-top: 0;
    transition: opacity 0.3s ease;
}

.wcmlim-modal.wcmlim-show {
    opacity: 1;
}

.wcmlim-modal-content {
    background-color: #fff;
    padding: 0;
    border-radius: 8px;
    width: 90%;
    max-width: 500px;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
    transform: translateY(-50px);
    transition: transform 0.3s ease;
    position: relative;
    top: 15%;
    left: 0;
}

.wcmlim-modal.wcmlim-show .wcmlim-modal-content {
    transform: translateY(0);
}

.wcmlim-modal-header {
    padding: 20px 25px;
    background: #c3c4c7;
    color: white;
    border-radius: 8px 8px 0 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.wcmlim-modal-header h3 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
}

.wcmlim-modal-close {
    font-size: 24px;
    font-weight: bold;
    cursor: pointer;
    padding: 0;
    background: none;
    border: none;
    color: white;
    width: 30px;
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    transition: background-color 0.2s ease;
}

.wcmlim-modal-close:hover {
    background-color: rgba(255, 255, 255, 0.2);
}

.wcmlim-modal-body {
    padding: 25px;
    max-height: 60vh;
    overflow-y: auto;
}

.wcmlim-modal-footer {
    padding: 20px 25px;
    border-top: 1px solid #eee;
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    border-radius: 0 0 8px 8px;
}

/* Form Styles */
.wcmlim-form-group {
    margin-bottom: 20px;
}

.wcmlim-form-group label {
    display: block;
    margin-bottom: 8px;
    font-weight: 600;
    color: #333;
    font-size: 14px;
}

.wcmlim-form-group input[type="checkbox"] {
    width: auto;
}

.wcmlim-form-group input,
.wcmlim-form-group select {
    width: 100%;
    padding: 12px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 14px;
    transition: border-color 0.2s ease, box-shadow 0.2s ease;
    box-sizing: border-box;
}

.wcmlim-form-group input:focus,
.wcmlim-form-group select:focus {
    outline: none;
    border-color: #c3c4c7;
    box-shadow: 0 0 0 3px rgba(108, 139, 255, 0.1);
}

/* Readonly input styling */
.wcmlim-form-group input[readonly] {
    background-color: #f8f9fa;
    color: #6c757d;
    cursor: not-allowed;
    border-color: #e9ecef;
}

.wcmlim-form-group input[readonly]:focus {
    box-shadow: none;
    border-color: #e9ecef;
}

/* Location Assignment Styles */
.wcmlim-location-assignments-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 10px;
    max-height: 200px;
    overflow-y: auto;
    border: 1px solid #e9ecef;
    border-radius: 4px;
    padding: 15px;
    background: #fafafa;
}

.wcmlim-assignment-item {
    display: flex;
    align-items: center;
}

.wcmlim-assignment-checkbox {
    display: flex;
    align-items: center;
    cursor: pointer;
    font-size: 14px;
    position: relative;
    user-select: none;
}

.wcmlim-assignment-checkbox input[type="checkbox"] {
    width: 18px;
    height: 18px;
    margin-right: 8px;
    cursor: pointer;
}

.wcmlim-assignment-checkbox .wcmlim-assignment-name {
    color: #333;
    font-weight: 500;
}

.wcmlim-assignment-actions {
    margin-top: 10px;
    display: flex;
    gap: 15px;
    justify-content: flex-start;
}

.wcmlim-btn-link {
    background: none;
    border: none;
    color: #c3c4c7;
    cursor: pointer;
    font-size: 13px;
    text-decoration: underline;
    padding: 0;
}

.wcmlim-btn-link:hover {
    color: #5a77e6;
    text-decoration: none;
}

.wcmlim-loading-spinner {
    text-align: center;
    padding: 20px;
    color: #666;
    font-style: italic;
}

.wcmlim-error-message {
    background: #fff2f2;
    border: 1px solid #ffcdd2;
    border-radius: 4px;
    padding: 15px;
    color: #d32f2f;
    text-align: center;
    font-size: 14px;
}

.wcmlim-no-items-message {
    background: #f0f8e8;
    border: 1px solid #c7e6b3;
    border-radius: 4px;
    padding: 15px;
    color: #2e7d32;
    text-align: center;
    font-size: 14px;
    font-style: italic;
}

.wcmlim-form-note {
    display: block;
    margin-top: 5px;
    color: #666;
    font-size: 12px;
    font-style: italic;
}

/* Button Styles */
.wcmlim-btn {
    padding: 12px 20px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
    font-weight: 600;
    transition: all 0.2s ease;
    display: inline-flex;
    align-items: center;
    gap: 8px;
}

/* Responsive Design */
@media (max-width: 600px) {
    .wcmlim-modal-content {
        width: 95%;
        margin: 2% auto;
    }
    
    .wcmlim-modal-header,
    .wcmlim-modal-body,
    .wcmlim-modal-footer {
        padding: 15px 20px;
    }
    
    .wcmlim-modal-footer {
        flex-direction: column;
    }
    
    .wcmlim-btn {
        width: 100%;
        justify-content: center;
    }
}
</style>

<script>
// Debug: Test if modal opens
document.addEventListener('DOMContentLoaded', function() {
    const btn = document.querySelector('.wcmlim-add-user-btn');
    const modal = document.getElementById('wcmlim-addUserModal');
    
    // Simple test function
    window.testModal = function() {
        const modal = document.getElementById('wcmlim-addUserModal');
        if (modal) {
            modal.style.display = 'block';
        }
    };
});
</script>

<?php
    }
    ?>