<?php
session_start();
require_once __DIR__ . '/includes/auth_check.php';
require_once __DIR__ . '/includes/db_connect.php';

// Handle user actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'delete':
                if (isset($_POST['user_id'])) {
                    $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
                    $stmt->execute([$_POST['user_id']]);
                    $_SESSION['message'] = 'User deleted successfully';
                    $_SESSION['message_type'] = 'success';
                }
                break;
            case 'update_status':
                if (isset($_POST['user_id']) && isset($_POST['status'])) {
                    $stmt = $pdo->prepare("UPDATE users SET status = ? WHERE id = ?");
                    $stmt->execute([$_POST['status'], $_POST['user_id']]);
                    $_SESSION['message'] = 'User status updated';
                    $_SESSION['message_type'] = 'success';
                }
                break;
        }
        header('Location: users.php');
        exit();
    }
}

// Pagination
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = 20;
$offset = ($page - 1) * $perPage;

// Search and filter
$search = $_GET['search'] ?? '';
$status = $_GET['status'] ?? '';

// Base query
$query = "SELECT u.*, 
                 IFNULL(s.points, 0) AS points, 
                 IFNULL(s.consecutive_days, 0) AS streaks, 
                 s.last_participation,
                 (SELECT COUNT(*) FROM recordings WHERE user_id = u.id) AS recordings_count
          FROM users u 
          LEFT JOIN user_stats s ON s.user_id = u.id 
          WHERE 1=1";
$params = [];

// Add search condition
if (!empty($search)) {
    $query .= " AND (u.full_name LIKE ? OR u.phone LIKE ? OR u.email LIKE ?)";
    $searchTerm = "%$search%";
    $params = array_merge($params, [$searchTerm, $searchTerm, $searchTerm]);
}

// Add status filter
if (!empty($status) && in_array($status, ['active', 'inactive', 'banned'])) {
    $query .= " AND u.status = ?";
    $params[] = $status;
}

// Count total records
$countStmt = $pdo->prepare("SELECT COUNT(*) as total FROM (" . str_replace('u.*', 'u.id', $query) . ") as count_query");
$countStmt->execute($params);
$totalUsers = $countStmt->fetch()['total'];
$totalPages = ceil($totalUsers / $perPage);

// Add sorting and pagination
$query .= " ORDER BY u.created_at DESC LIMIT " . (int)$perPage . " OFFSET " . (int)$offset;

// Get users
$stmt = $pdo->prepare($query);
$stmt->execute($params);
$users = $stmt->fetchAll();
?>
<!doctype html>
<html>
<head>
  <meta charset="utf-8"/>
  <meta name="viewport" content="width=device-width,initial-scale=1"/>
  <title>Users - Admin Panel</title>
  <link rel="stylesheet" href="assets/theme.css">
</head>
<body class="dashboard-page">
<?php include 'includes/sidebar.php'; ?>
<main class="main">
  <header class="topbar">
    <div class="topbar-left">Users</div>
    <div class="topbar-right">
      Welcome, <?= htmlspecialchars($_SESSION['username'] ?? 'Admin') ?>
    </div>
  </header>
  <section class="content">
  <?php if (isset($_SESSION['message'])): ?>
    <div class="alert alert-<?= $_SESSION['message_type'] ?> mb-4">
      <?= $_SESSION['message'] ?>
      <?php unset($_SESSION['message'], $_SESSION['message_type']); ?>
    </div>
  <?php endif; ?>

  <div class="card">
    <div class="card-header">
      <div class="d-flex justify-content-between align-items-center">
        <h3>User Management</h3>
        <div>
          <a href="user_edit.php" class="btn btn-primary">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <line x1="12" y1="5" x2="12" y2="19"></line>
              <line x1="5" y1="12" x2="19" y2="12"></line>
            </svg>
            Add New User
          </a>
        </div>
      </div>
      
      <div class="row mt-3">
        <div class="col-md-6">
          <form method="get" class="d-flex">
            <input type="text" name="search" class="form-control me-2" placeholder="Search users..." value="<?= htmlspecialchars($search) ?>">
            <select name="status" class="form-select me-2" style="width: 120px;">
              <option value="">All Status</option>
              <option value="active" <?= $status === 'active' ? 'selected' : '' ?>>Active</option>
              <option value="inactive" <?= $status === 'inactive' ? 'selected' : '' ?>>Inactive</option>
              <option value="banned" <?= $status === 'banned' ? 'selected' : '' ?>>Banned</option>
            </select>
            <button type="submit" class="btn btn-outline-primary">Filter</button>
            <?php if (!empty($search) || !empty($status)): ?>
              <a href="users.php" class="btn btn-link">Clear</a>
            <?php endif; ?>
          </form>
        </div>
      </div>
    </div>
    
    <div class="table-container">
    <table class="table">
      <thead>
        <tr>
          <th>User</th>
          <th>Contact</th>
          <th>Activity</th>
          <th>Status</th>
          <th>Actions</th>
        </tr>
      </thead>
      <tbody>
        <?php if (count($users) > 0): ?>
          <?php foreach($users as $user): 
            $status = $user['status'] ?? 'active';
            $statusClass = 'status-' . $status;
          ?>
            <tr>
              <td>
                <div class="d-flex align-items-center">
                  <div class="avatar me-3">
                    <?= strtoupper(substr($user['full_name'] ?? 'U', 0, 1)) ?>
                  </div>
                  <div>
                    <div class="fw-bold"><?= htmlspecialchars($user['full_name'] ?? 'Unknown User') ?></div>
                    <div class="text-muted small">ID: <?= $user['id'] ?></div>
                  </div>
                </div>
              </td>
              <td>
                <div class="d-flex flex-column">
                  <?php if (!empty($user['phone'])): ?>
                    <div class="d-flex align-items-center mb-1">
                      <i class="fas fa-phone-alt me-2 text-muted" style="width: 16px;"></i>
                      <span><?= htmlspecialchars($user['phone']) ?></span>
                    </div>
                  <?php endif; ?>
                  <?php if (!empty($user['email'])): ?>
                    <div class="d-flex align-items-center">
                      <i class="fas fa-envelope me-2 text-muted" style="width: 16px;"></i>
                      <span class="text-truncate" style="max-width: 200px;" title="<?= htmlspecialchars($user['email']) ?>">
                        <?= htmlspecialchars($user['email']) ?>
                      </span>
                    </div>
                  <?php endif; ?>
                </div>
              </td>
              <td>
                <div class="d-flex flex-column">
                  <div class="mb-1">
                    <span class="text-muted">Points:</span>
                    <span class="ms-1 fw-medium"><?= number_format((int)($user['points'] ?? 0)) ?></span>
                  </div>
                  <div class="mb-1">
                    <span class="text-muted">Recordings:</span>
                    <span class="ms-1 fw-medium"><?= number_format((int)($user['recordings_count'] ?? 0)) ?></span>
                  </div>
                  <?php if (!empty($user['last_participation'])): ?>
                    <div>
                      <span class="text-muted">Last Active:</span>
                      <span class="ms-1"><?= date('M j, Y', strtotime($user['last_participation'])) ?></span>
                    </div>
                  <?php endif; ?>
                </div>
              </td>
              <td>
                <div class="d-flex align-items-center">
                  <span class="status-badge <?= $statusClass ?>">
                    <?= ucfirst($status) ?>
                  </span>
                  <div class="dropdown">
                    <button class="btn btn-link p-0 ms-2" 
                            type="button" 
                            onclick="toggleDropdown('statusDropdown<?= $user['id'] ?>')"
                            style="line-height: 1; text-decoration: none; border: none; background: none; cursor: pointer; color: #fff;">
                      <i class="fas fa-ellipsis-v"></i>
                    </button>
                    <div class="dropdown-menu dropdown-menu-end" 
                         id="statusDropdown<?= $user['id'] ?>"
                         style="display: none; position: absolute; z-index: 1000; min-width: 180px; padding: 8px 0; margin: 2px 0 0; background: #2d3748; border: 1px solid #4a5568; border-radius: 6px; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);">
                      <a class="dropdown-item" href="#" onclick="return updateStatus(<?= $user['id'] ?>, 'active');" style="color: #e2e8f0; padding: 8px 16px; display: flex; align-items: center; text-decoration: none; transition: background-color 0.2s;">
                        <i class="fas fa-circle text-success me-3" style="font-size: 0.7rem;"></i> Set as Active
                      </a>
                      <a class="dropdown-item" href="#" onclick="return updateStatus(<?= $user['id'] ?>, 'inactive');" style="color: #e2e8f0; padding: 8px 16px; display: flex; align-items: center; text-decoration: none; transition: background-color 0.2s;">
                        <i class="fas fa-circle text-gray-400 me-3" style="font-size: 0.7rem;"></i> Set as Inactive
                      </a>
                      <div style="height: 1px; background-color: #4a5568; margin: 4px 0;"></div>
                      <a class="dropdown-item" href="#" onclick="return updateStatus(<?= $user['id'] ?>, 'banned');" style="color: #feb2b2; padding: 8px 16px; display: flex; align-items: center; text-decoration: none; transition: background-color 0.2s;">
                        <i class="fas fa-ban me-3" style="width: 14px; text-align: center;"></i> Ban User
                      </a>
                    </div>
                  </div>
                </div>
              </td>
              <td>
                <div class="d-flex">
                  <a href="#" class="action-btn" 
     onclick="viewUser(<?= htmlspecialchars(json_encode($user), ENT_QUOTES, 'UTF-8') ?>, <?= htmlspecialchars(json_encode([
       'points' => $user['points'] ?? 0,
       'recordings_count' => $user['recordings_count'] ?? 0,
       'streaks' => $user['streaks'] ?? 0
     ]), ENT_QUOTES, 'UTF-8') ?>); return false;">
    <i class="fas fa-eye"></i>
  </a>
  <a href="#" class="action-btn" 
     onclick="editUser(<?= htmlspecialchars(json_encode($user), ENT_QUOTES, 'UTF-8') ?>); return false;">
    <i class="fas fa-edit"></i>
  </a>
  <a href="#" class="action-btn" 
     onclick="confirmDelete(<?= $user['id'] ?>, '<?= addslashes($user['full_name']) ?>'); return false;">
    <i class="fas fa-trash"></i>
  </a>
                </div>
              </td>
            </tr>
            <?php endforeach; ?>
          <?php else: ?>
            <tr>
              <td colspan="5" class="text-center py-4">
                No users found
                <?php if (!empty($search) || !empty($status)): ?>
                  <div class="mt-2">
                    <a href="users.php" class="btn btn-sm btn-outline-primary">Clear filters</a>
                  </div>
                <?php endif; ?>
              </td>
            </tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
    
    <?php if ($totalPages > 1): ?>
      <div class="card-footer">
        <nav aria-label="Page navigation">
          <ul class="pagination justify-content-center mb-0">
            <?php for ($i = 1; $i <= $totalPages; $i++): ?>
              <li class="page-item <?= $i === $page ? 'active' : '' ?>">
                <a class="page-link" href="?page=<?= $i ?><?= !empty($search) ? '&search=' . urlencode($search) : '' ?><?= !empty($status) ? '&status=' . urlencode($status) : '' ?>">
                  <?= $i ?>
                </a>
              </li>
            <?php endfor; ?>
          </ul>
        </nav>
      </div>
    <?php endif; ?>
  </div>
  
  <!-- Add Font Awesome for icons -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
  
  <style>
    /* Table Styles */
    .table-container {
      width: 100%;
      overflow-x: auto;
      background: var(--surface);
      border-radius: 8px;
      box-shadow: 0 1px 3px rgba(0,0,0,0.1);
      padding: 0.5rem;
    }
    .table {
      width: 100%;
      min-width: 1000px;
      margin: 0;
      color: var(--text);
      border-collapse: separate;
      border-spacing: 0;
    }
    .table th {
      background: var(--surface-2);
      color: var(--text-muted);
      font-weight: 600;
      text-transform: uppercase;
      font-size: 0.7rem;
      letter-spacing: 0.5px;
      padding: 12px 16px;
      border: none;
      white-space: nowrap;
    }
    .table td {
      padding: 12px 16px;
      border-top: 1px solid var(--border-color);
      vertical-align: middle;
    }
    .table tbody tr:hover {
      background: rgba(255,255,255,0.02);
    }
    
    /* Avatar */
    .avatar {
      width: 36px;
      height: 36px;
      border-radius: 50%;
      background: rgba(255,154,60,0.1);
      color: var(--accent-orange);
      display: flex;
      align-items: center;
      justify-content: center;
      font-weight: 600;
      font-size: 1rem;
      flex-shrink: 0;
    }
    
    /* Card Header */
    .card-header {
      background: var(--surface-2);
      border-bottom: 1px solid var(--border-color);
      padding: 1.25rem 1.5rem;
    }
    
    /* Status Badges */
    .status-badge {
      display: inline-flex;
      align-items: center;
      padding: 4px 10px;
      border-radius: 12px;
      font-size: 0.75rem;
      font-weight: 600;
      text-transform: capitalize;
      white-space: nowrap;
    }
    .status-active {
      background: rgba(40, 167, 69, 0.1);
      color: #28a745;
    }
    .status-inactive {
      background: rgba(108, 117, 125, 0.1);
      color: #6c757d;
    }
    .status-banned {
      background: rgba(220, 53, 69, 0.1);
      color: #dc3545;
    }
    
    /* Action Buttons */
    .action-btn {
      width: 30px;
      height: 30px;
      padding: 0;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      margin: 0 2px;
      border-radius: 6px;
      border: 1px solid #f59e0b;
      color: #f59e0b;
      background: rgba(245, 158, 11, 0.1);
      transition: all 0.2s;
    }
    .action-btn i {
      font-size: 0.9rem;
    }
    .action-btn:hover {
      transform: translateY(-1px);
      background: rgba(245, 158, 11, 0.2);
      color: #f59e0b;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }
    .btn-view {
      color: #3b82f6;
      border-color: #3b82f6;
      background: rgba(59, 130, 246, 0.1);
    }
    .btn-view:hover {
      background: rgba(59, 130, 246, 0.2);
      color: #3b82f6;
    }
    .btn-delete {
      color: #ef4444;
      border-color: #ef4444;
      background: rgba(239, 68, 68, 0.1);
    }
    .btn-delete:hover {
      background: rgba(239, 68, 68, 0.2);
      color: #ef4444;
    }
    
    /* Dropdown hover states */
    .dropdown-item:hover {
      background-color: rgba(255, 255, 255, 0.05) !important;
    }
    
    /* Modal */
    .modal-content {
      background: var(--surface);
      border: 1px solid var(--border-color);
      border-radius: 8px;
      box-shadow: 0 10px 30px rgba(0,0,0,0.2);
    }
    .modal-header {
      border-bottom: 1px solid var(--border-color);
      padding: 1.25rem 1.5rem;
    }
    .modal-body {
      padding: 1.5rem;
    }
    .modal-footer {
      border-top: 1px solid var(--border-color);
      padding: 1rem 1.5rem;
    }
    
    /* Form Styles */
    .form-label {
      font-weight: 500;
      margin-bottom: 0.5rem;
      color: var(--text-muted);
      font-size: 0.85rem;
    }
    .form-control, .form-select {
      background: var(--surface-2);
      border: 1px solid var(--border-color);
      color: var(--text);
      border-radius: 6px;
      padding: 0.5rem 0.75rem;
    }
    .form-control:focus, .form-select:focus {
      background: var(--surface-2);
      border-color: var(--accent-orange);
      box-shadow: 0 0 0 0.25rem rgba(255, 154, 60, 0.15);
    }
    
    /* Responsive */
    @media (max-width: 1200px) {
      .table th, .table td {
        padding: 10px 12px;
      }
    }
  </style>
  </section>
</main>

<!-- View User Modal -->
<div class="modal fade" id="userModal" tabindex="-1" aria-labelledby="userModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="userModalLabel">User Details</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body" id="userModalBody">
        <!-- Content will be loaded dynamically -->
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary" id="saveUserBtn" style="display: none;">Save Changes</button>
      </div>
    </div>
  </div>
</div>

  <!-- Load Bootstrap JS bundle with Popper -->
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
  
  <script>
  // Prevent modals from auto-showing
  document.addEventListener('DOMContentLoaded', function() {
    // Hide any shown modals on page load
    var modals = document.querySelectorAll('.modal');
    modals.forEach(function(modal) {
      modal.style.display = 'none';
      modal.classList.remove('show');
    });
    
    // Remove backdrop if any
    var backdrops = document.querySelectorAll('.modal-backdrop');
    backdrops.forEach(function(backdrop) {
      backdrop.remove();
    });
    
    // Remove modal-open class from body
    document.body.classList.remove('modal-open');
    document.body.style.overflow = '';
    document.body.style.paddingRight = '';
  });
  
// View User Details
function viewUser(user, stats) {
  const modal = new bootstrap.Modal(document.getElementById('userModal'));
  document.getElementById('userModalLabel').textContent = 'User Details: ' + user.full_name;
  
  // Format the user details
  const html = `
    <div class="row">
      <div class="col-md-4 text-center mb-4">
        <div class="avatar mx-auto mb-3" style="width: 100px; height: 100px; font-size: 2.5rem;">
          ${user.full_name ? user.full_name.charAt(0).toUpperCase() : 'U'}
        </div>
        <h5 class="mb-1">${user.full_name || 'Unknown User'}</h5>
        <div class="text-muted mb-3">ID: ${user.id}</div>
        <span class="status-badge status-${user.status || 'active'}">
          ${(user.status || 'active').charAt(0).toUpperCase() + (user.status || 'active').slice(1)}
        </span>
      </div>
      <div class="col-md-8">
        <div class="card mb-4">
          <div class="card-body">
            <h6 class="card-title mb-3">User Information</h6>
            <div class="row mb-3">
              <div class="col-md-6">
                <div class="small text-muted">Age Range</div>
                <div>${user.age_range || 'Not specified'}</div>
              </div>
              <div class="col-md-6">
                <div class="small text-muted">Gender</div>
                <div>${user.gender ? user.gender.charAt(0).toUpperCase() + user.gender.slice(1) : 'Not specified'}</div>
              </div>
            </div>
            <div class="mb-3">
              <div class="small text-muted">Ethnicity</div>
              <div>${user.ethnicity || 'Not specified'}</div>
            </div>
            <h6 class="card-title mb-3 mt-4">Contact Information</h6>
            <div class="mb-3">
              <div class="small text-muted">Phone</div>
              <div>${user.phone || 'N/A'}</div>
            </div>
            <div class="mb-3">
              <div class="small text-muted">Email</div>
              <div>${user.email || 'N/A'}</div>
            </div>
            <div class="mb-3">
              <div class="small text-muted">Member Since</div>
              <div>${user.created_at ? new Date(user.created_at).toLocaleDateString() : 'N/A'}</div>
            </div>
          </div>
        </div>
        
        <div class="card">
          <div class="card-body">
            <h6 class="card-title mb-3">Activity</h6>
            <div class="row text-center">
              <div class="col-4">
                <div class="h4 mb-1">${stats.points || 0}</div>
                <div class="small text-muted">Points</div>
              </div>
              <div class="col-4">
                <div class="h4 mb-1">${stats.recordings_count || 0}</div>
                <div class="small text-muted">Recordings</div>
              </div>
              <div class="col-4">
                <div class="h4 mb-1">${stats.streaks || 0}</div>
                <div class="small text-muted">Day Streak</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  `;
  
  document.getElementById('userModalBody').innerHTML = html;
  document.getElementById('saveUserBtn').style.display = 'none';
  modal.show();
}

// Edit User
function editUser(user) {
  // Create modal HTML
  const modalHTML = `
    <div class="modal fade" id="editUserModal" tabindex="-1" aria-hidden="true">
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
          <div class="modal-header bg-primary text-white py-3">
            <h5 class="modal-title mb-0">
              <i class="fas fa-user-edit me-2"></i>Edit User: ${user.full_name || 'User #' + user.id}
            </h5>
            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body p-4">
            <form id="editUserForm" method="post" class="needs-validation" novalidate>
              <input type="hidden" name="action" value="update">
              <input type="hidden" name="user_id" value="${user.id}">
              
              <!-- Basic Information Section -->
              <div class="mb-4">
                <h6 class="mb-3 text-uppercase text-muted fw-bold">Basic Information</h6>
                <div class="row g-3">
                  <div class="col-md-6">
                    <div class="form-group">
                      <label for="full_name" class="form-label">Full Name <span class="text-danger">*</span></label>
                      <input type="text" class="form-control form-control-lg" id="full_name" name="full_name" 
                             value="${user.full_name || ''}" required>
                      <div class="invalid-feedback">Please enter a name</div>
                    </div>
                  </div>
                  <div class="col-md-6">
                    <div class="form-group">
                      <label for="phone" class="form-label">Phone <span class="text-danger">*</span></label>
                      <input type="tel" class="form-control form-control-lg" id="phone" name="phone" 
                             value="${user.phone || ''}" required>
                      <div class="invalid-feedback">Please enter a valid phone number</div>
                    </div>
                  </div>
                  <div class="col-md-6">
                    <div class="form-group">
                      <label for="email" class="form-label">Email</label>
                      <input type="email" class="form-control form-control-lg" id="email" name="email" 
                             value="${user.email || ''}">
                      <div class="invalid-feedback">Please enter a valid email</div>
                    </div>
                  </div>
                  <div class="col-md-6">
                    <div class="form-group">
                      <label for="status" class="form-label">Status <span class="text-danger">*</span></label>
                      <select class="form-select form-select-lg" id="status" name="status" required>
                        <option value="active" ${user.status === 'active' ? 'selected' : ''}>Active</option>
                        <option value="inactive" ${user.status === 'inactive' ? 'selected' : ''}>Inactive</option>
                        <option value="banned" ${user.status === 'banned' ? 'selected' : ''}>Banned</option>
                      </select>
                    </div>
                  </div>
                </div>
              </div>
              
              <!-- Demographic Information Section -->
              <div class="mb-4">
                <h6 class="mb-3 text-uppercase text-muted fw-bold">Demographic Information</h6>
                <div class="row g-3">
                  <div class="col-md-4">
                    <div class="form-group">
                      <label for="age_range" class="form-label">Age Range</label>
                      <select class="form-select form-select-lg" id="age_range" name="age_range">
                        <option value="">Select age range</option>
                        <option value="18-24" ${user.age_range === '18-24' ? 'selected' : ''}>18-24</option>
                        <option value="25-34" ${user.age_range === '25-34' ? 'selected' : ''}>25-34</option>
                        <option value="35-44" ${user.age_range === '35-44' ? 'selected' : ''}>35-44</option>
                        <option value="45-54" ${user.age_range === '45-54' ? 'selected' : ''}>45-54</option>
                        <option value="55+" ${user.age_range === '55+' ? 'selected' : ''}>55+</option>
                      </select>
                    </div>
                  </div>
                  <div class="col-md-4">
                    <div class="form-group">
                      <label for="gender" class="form-label">Gender</label>
                      <select class="form-select form-select-lg" id="gender" name="gender">
                        <option value="">Select gender</option>
                        <option value="male" ${user.gender === 'male' ? 'selected' : ''}>Male</option>
                        <option value="female" ${user.gender === 'female' ? 'selected' : ''}>Female</option>
                        <option value="other" ${user.gender === 'other' ? 'selected' : ''}>Other</option>
                        <option value="prefer_not_to_say" ${user.gender === 'prefer_not_to_say' ? 'selected' : ''}>Prefer not to say</option>
                      </select>
                    </div>
                  </div>
                  <div class="col-md-4">
                    <div class="form-group">
                      <label for="ethnicity" class="form-label">Ethnicity</label>
                      <input type="text" class="form-control form-control-lg" id="ethnicity" name="ethnicity" 
                             value="${user.ethnicity || ''}" placeholder="e.g., African American, Asian, etc.">
                    </div>
                  </div>
                </div>
              </div>
              
              <!-- Password Section -->
              <div class="mb-3">
                <h6 class="mb-3 text-uppercase text-muted fw-bold">Password</h6>
                <div class="alert alert-info mb-4">
                  <div class="d-flex align-items-center">
                    <i class="fas fa-info-circle me-2"></i>
                    <div>Leave password fields blank to keep the current password</div>
                  </div>
                </div>
                <div class="row g-3">
                  <div class="col-md-6">
                    <div class="form-group">
                      <label for="new_password" class="form-label">New Password</label>
                      <div class="input-group">
                        <input type="password" class="form-control form-control-lg" id="new_password" 
                               name="new_password" placeholder="Enter new password">
                        <button class="btn btn-outline-secondary toggle-password" type="button">
                          <i class="fas fa-eye"></i>
                        </button>
                      </div>
                      <div class="form-text text-muted mt-1">At least 8 characters</div>
                    </div>
                  </div>
                  <div class="col-md-6">
                    <div class="form-group">
                      <label for="confirm_password" class="form-label">Confirm Password</label>
                      <div class="input-group">
                        <input type="password" class="form-control form-control-lg" id="confirm_password" 
                               name="confirm_password" placeholder="Confirm new password">
                        <button class="btn btn-outline-secondary toggle-password" type="button">
                          <i class="fas fa-eye"></i>
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </form>
          </div>
          <div class="modal-footer bg-light p-3">
            <button type="button" class="btn btn-lg btn-outline-secondary" data-bs-dismiss="modal">
              <i class="fas fa-times me-2"></i>Cancel
            </button>
            <button type="submit" form="editUserForm" class="btn btn-lg btn-primary px-4">
              <i class="fas fa-save me-2"></i>Save Changes
            </button>
          </div>
        </div>
      </div>
    </div>
  `;

  // Remove any existing modals
  const existingModal = document.getElementById('editUserModal');
  if (existingModal) {
    existingModal.remove();
  }

  // Add modal to body
  document.body.insertAdjacentHTML('beforeend', modalHTML);
  
  // Initialize form validation
  const form = document.getElementById('editUserForm');
  if (form) {
    form.addEventListener('submit', function(event) {
      if (!form.checkValidity()) {
        event.preventDefault();
        event.stopPropagation();
      }
      form.classList.add('was-validated');
    }, false);
  }
  
  // Show the modal
  const editModal = new bootstrap.Modal(document.getElementById('editUserModal'));
  editModal.show();
  
  // Focus first input
  document.getElementById('full_name').focus();
}

// Toggle dropdown menu
function toggleDropdown(id) {
  // Close all other dropdowns
  document.querySelectorAll('.dropdown-menu').forEach(menu => {
    if (menu.id !== id) menu.style.display = 'none';
  });
  
  // Toggle current dropdown
  const menu = document.getElementById(id);
  if (menu) {
    menu.style.display = menu.style.display === 'block' ? 'none' : 'block';
  }
  
  // Close when clicking outside
  document.addEventListener('click', function closeDropdown(e) {
    if (!e.target.closest('.dropdown') || e.target.closest('.dropdown-item')) {
      if (menu) menu.style.display = 'none';
      document.removeEventListener('click', closeDropdown);
    }
  });
  
  // Prevent event from bubbling up
  event.stopPropagation();
}

// Close dropdowns when clicking outside
document.addEventListener('click', function(e) {
  if (!e.target.closest('.dropdown')) {
    document.querySelectorAll('.dropdown-menu').forEach(menu => {
      menu.style.display = 'none';
    });
  }
});

// Update User Status
function updateStatus(userId, status) {
  if (confirm('Are you sure you want to update this user\'s status?')) {
    const form = document.createElement('form');
    form.method = 'post';
    form.innerHTML = `
      <input type="hidden" name="action" value="update_status">
      <input type="hidden" name="user_id" value="${userId}">
      <input type="hidden" name="status" value="${status}">
    `;
    document.body.appendChild(form);
    form.submit();
  }
  return false; // Prevent default action
}

// Confirm Delete
function confirmDelete(userId, userName) {
  // Create modal HTML
  const modalHTML = `
    <div class="modal fade" id="deleteModal" tabindex="-1" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header bg-danger text-white">
            <h5 class="modal-title">
              <i class="fas fa-exclamation-triangle me-2"></i>Confirm Deletion
            </h5>
            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <p>Are you sure you want to delete <strong>${userName}</strong>?</p>
            <p class="text-danger">This action cannot be undone.</p>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">
              <i class="fas fa-times me-2"></i>Cancel
            </button>
            <button type="button" class="btn btn-danger" id="confirmDeleteBtn">
              <i class="fas fa-trash-alt me-2"></i>Delete
            </button>
          </div>
        </div>
      </div>
    </div>
  `;

  // Remove any existing modals
  const existingModal = document.getElementById('deleteModal');
  if (existingModal) {
    existingModal.remove();
  }

  // Add modal to body
  document.body.insertAdjacentHTML('beforeend', modalHTML);
  
  // Show the modal
  const deleteModal = new bootstrap.Modal(document.getElementById('deleteModal'));
  deleteModal.show();

  // Handle confirm button click
  document.getElementById('confirmDeleteBtn').addEventListener('click', function() {
    const form = document.createElement('form');
    form.method = 'post';
    form.innerHTML = `
      <input type="hidden" name="action" value="delete">
      <input type="hidden" name="user_id" value="${userId}">
    `;
    document.body.appendChild(form);
    form.submit();
  });
}

// Initialize tooltips
var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
  return new bootstrap.Tooltip(tooltipTriggerEl);
});
</script>
</body>
</html>