<?php // content-only ?>
<section style="max-width:1200px; margin:20px auto; padding:0 16px">
  <!-- Header con estadísticas -->
  <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px; flex-wrap: wrap; gap: 16px;">
    <div>
      <h1 style="margin: 0; color: #1a1d23; font-size: 1.8rem;">Gestión de Usuarios</h1>
      <p style="margin: 4px 0 0 0; color: #64748b; font-size: 0.9rem;">
        Administra y modera los usuarios de la red social
      </p>
    </div>
    <div style="display: flex; gap: 16px; font-size: 0.9rem;">
      <div style="text-align: center;">
        <div style="font-weight: 600; color: #1a1d23;"><?php echo count($users ?? []); ?></div>
        <div style="color: #64748b;">Mostrados</div>
      </div>
      <div style="width: 1px; background: #e2e8f0;"></div>
      <div style="text-align: center;">
        <div style="font-weight: 600; color: #1a1d23;"><?php echo $stats['total_users'] ?? 0; ?></div>
        <div style="color: #64748b;">Total</div>
      </div>
      <div style="width: 1px; background: #e2e8f0;"></div>
      <div style="text-align: center;">
        <div style="font-weight: 600; color: #1a1d23;">
          <a href="<?php echo base_url('/admin/ban-management'); ?>" style="color: inherit; text-decoration: none;">
            <?php 
            $banned_count = 0;
            foreach ($users ?? [] as $u) {
                if (($u['status'] ?? '') === 'banned') $banned_count++;
            }
            echo $banned_count;
            ?>
          </a>
        </div>
        <div style="color: #64748b;">Baneados</div>
      </div>
    </div>
  </div>

  <!-- Filtros mejorados -->
  <div class="filter-card" style="background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 12px; padding: 20px; margin-bottom: 24px;">
    <form method="get" style="display: grid; grid-template-columns: 1fr auto auto auto auto; gap: 12px; align-items: end;">
      <div>
        <label style="display: block; margin-bottom: 6px; font-weight: 500; color: #374151; font-size: 0.9rem;">Buscar usuario</label>
        <input type="text" name="q" placeholder="Email, nick, nombre..." 
               value="<?php echo htmlspecialchars($_GET['q'] ?? ''); ?>" 
               style="width: 100%; padding: 10px 12px; border: 1px solid #d1d5db; border-radius: 8px; font-size: 0.9rem;">
      </div>
      
      <div>
        <label style="display: block; margin-bottom: 6px; font-weight: 500; color: #374151; font-size: 0.9rem;">Rol</label>
        <select name="role" style="width: 100%; padding: 10px 12px; border: 1px solid #d1d5db; border-radius: 8px; font-size: 0.9rem; background: white;">
          <option value="">Todos los roles</option>
          <option value="user" <?php echo (($_GET['role'] ?? '') === 'user') ? 'selected' : ''; ?>>Usuario</option>
          <option value="moderator" <?php echo (($_GET['role'] ?? '') === 'moderator') ? 'selected' : ''; ?>>Moderador</option>
          <option value="admin" <?php echo (($_GET['role'] ?? '') === 'admin') ? 'selected' : ''; ?>>Administrador</option>
        </select>
      </div>
      
      <div>
        <label style="display: block; margin-bottom: 6px; font-weight: 500; color: #374151; font-size: 0.9rem;">Estado</label>
        <select name="status" style="width: 100%; padding: 10px 12px; border: 1px solid #d1d5db; border-radius: 8px; font-size: 0.9rem; background: white;">
          <option value="">Todos los estados</option>
          <option value="active" <?php echo (($_GET['status'] ?? '') === 'active') ? 'selected' : ''; ?>>Activo</option>
          <option value="disabled" <?php echo (($_GET['status'] ?? '') === 'disabled') ? 'selected' : ''; ?>>Deshabilitado</option>
          <option value="banned" <?php echo (($_GET['status'] ?? '') === 'banned') ? 'selected' : ''; ?>>Baneado</option>
        </select>
      </div>

      <div>
        <label style="display: block; margin-bottom: 6px; font-weight: 500; color: #374151; font-size: 0.9rem;">Ordenar por</label>
        <select name="sort" style="width: 100%; padding: 10px 12px; border: 1px solid #d1d5db; border-radius: 8px; font-size: 0.9rem; background: white;">
          <option value="newest" <?php echo (($_GET['sort'] ?? '') === 'newest') ? 'selected' : ''; ?>>Más nuevos</option>
          <option value="oldest" <?php echo (($_GET['sort'] ?? '') === 'oldest') ? 'selected' : ''; ?>>Más antiguos</option>
          <option value="last_login" <?php echo (($_GET['sort'] ?? '') === 'last_login') ? 'selected' : ''; ?>>Último login</option>
          <option value="name" <?php echo (($_GET['sort'] ?? '') === 'name') ? 'selected' : ''; ?>>Nombre</option>
        </select>
      </div>
      
      <div>
        <button type="submit" class="btn-primary" style="padding: 10px 20px; background: #6366f1; color: white; border: none; border-radius: 8px; font-weight: 500; cursor: pointer; font-size: 0.9rem;">
          🔍 Filtrar
        </button>
        <?php if (!empty($_GET['q']) || !empty($_GET['role']) || !empty($_GET['status']) || !empty($_GET['sort'])): ?>
          <a href="<?php echo base_url('/admin/users'); ?>" style="display: block; margin-top: 8px; color: #64748b; text-decoration: none; font-size: 0.8rem;">
            Limpiar filtros
          </a>
        <?php endif; ?>
      </div>
    </form>
  </div>

  <!-- Mensajes Flash -->
  <?php if (!empty($_SESSION['flash'])): ?>
    <div style="padding: 12px 16px; background: #dbeafe; border: 1px solid #93c5fd; border-radius: 8px; margin-bottom: 20px; color: #1e40af;">
      <?php echo htmlspecialchars($_SESSION['flash']); unset($_SESSION['flash']); ?>
    </div>
  <?php endif; ?>

  <!-- Acciones rápidas -->
  <div style="display: flex; gap: 12px; margin-bottom: 16px; flex-wrap: wrap;">
    <a href="<?php echo base_url('/admin/ban-management'); ?>" 
       style="padding: 10px 16px; background: #fef3c7; color: #92400e; text-decoration: none; border-radius: 8px; border: 1px solid #f59e0b; font-size: 0.9rem;">
      🕒 Gestión de Baneos
    </a>
    <form method="post" action="<?php echo base_url('/admin/check-expired-bans'); ?>" style="margin: 0;">
      <button type="submit" style="padding: 10px 16px; background: #d1fae5; color: #065f46; border: 1px solid #10b981; border-radius: 8px; font-size: 0.9rem; cursor: pointer;">
        🔄 Revisar Baneos Expirados
      </button>
    </form>
  </div>

  <!-- Tabla mejorada -->
  <div style="background: white; border: 1px solid #e2e8f0; border-radius: 12px; overflow: hidden; box-shadow: 0 1px 3px rgba(0,0,0,0.1);">
    <div style="overflow: auto;">
      <table style="width: 100%; border-collapse: collapse; min-width: 1200px;">
        <thead>
          <tr style="background: #f8fafc; border-bottom: 1px solid #e2e8f0;">
            <th style="padding: 16px; text-align: left; font-weight: 600; color: #374151; font-size: 0.9rem; width: 60px;">ID</th>
            <th style="padding: 16px; text-align: left; font-weight: 600; color: #374151; font-size: 0.9rem;">Usuario</th>
            <th style="padding: 16px; text-align: left; font-weight: 600; color: #374151; font-size: 0.9rem;">Email</th>
            <th style="padding: 16px; text-align: left; font-weight: 600; color: #374151; font-size: 0.9rem; width: 150px;">Estado</th>
            <th style="padding: 16px; text-align: left; font-weight: 600; color: #374151; font-size: 0.9rem; width: 130px;">Rol</th>
            <th style="padding: 16px; text-align: left; font-weight: 600; color: #374151; font-size: 0.9rem; width: 100px;">Registro</th>
            <th style="padding: 16px; text-align: left; font-weight: 600; color: #374151; font-size: 0.9rem; width: 120px;">Último login</th>
            <th style="padding: 16px; text-align: left; font-weight: 600; color: #374151; font-size: 0.9rem; width: 250px;">Acciones</th>
          </tr>
        </thead>
        <tbody>
          <?php if (!empty($users)): ?>
            <?php foreach ($users as $u): ?>
              <tr style="border-bottom: 1px solid #f1f5f9; transition: background 0.2s;">
                <td style="padding: 16px; font-size: 0.9rem; color: #64748b; font-weight: 500;">#<?php echo (int)$u['id']; ?></td>
                
                <td style="padding: 16px;">
                  <div style="font-weight: 600; color: #1a1d23;"><?php echo htmlspecialchars($u['nick']); ?></div>
                  <div style="font-size: 0.8rem; color: #64748b; margin-top: 2px;">
                    <?php 
                    $full_name = trim(($u['first_name'] ?? '') . ' ' . ($u['last_name'] ?? ''));
                    echo htmlspecialchars($full_name ?: '—'); 
                    ?>
                  </div>
                </td>
                
                <td style="padding: 16px; font-size: 0.9rem; color: #374151;">
                  <div><?php echo htmlspecialchars($u['email']); ?></div>
                  <?php if (!empty($u['last_login'])): ?>
                    <div style="font-size: 0.75rem; color: #64748b; margin-top: 2px;">
                      Login: <?php echo date('d/m H:i', strtotime($u['last_login'])); ?>
                    </div>
                  <?php endif; ?>
                </td>
                
                <td style="padding: 16px;">
                  <!-- Información de ban temporal -->
                  <?php if (($u['status'] ?? '') === 'banned' && !empty($u['banned_until'])): ?>
                    <div style="margin-bottom: 8px;">
                      <div style="font-size: 0.75rem; color: #dc2626; font-weight: 500;">
                        ⏳ Hasta: <?php echo date('d/m/Y H:i', strtotime($u['banned_until'])); ?>
                      </div>
                      <?php if (!empty($u['ban_reason'])): ?>
                        <div style="font-size: 0.7rem; color: #991b1b; margin-top: 2px;">
                          <?php echo htmlspecialchars(substr($u['ban_reason'], 0, 50)); ?><?php echo strlen($u['ban_reason']) > 50 ? '...' : ''; ?>
                        </div>
                      <?php endif; ?>
                    </div>
                  <?php endif; ?>
                  
                  <form method="post" action="<?php echo base_url('/admin/users/status'); ?>" style="margin: 0;">
                    <input type="hidden" name="id" value="<?php echo (int)$u['id']; ?>">
                    <select name="status" onchange="if(this.value==='banned'){showBanModal(<?php echo (int)$u['id']; ?>, '<?php echo htmlspecialchars($u['nick']); ?>')}else{this.form.submit()}" 
                            style="padding: 6px 8px; border: 1px solid #d1d5db; border-radius: 6px; font-size: 0.8rem; background: white; width: 100%; cursor: pointer;"
                            class="status-<?php echo $u['status'] ?? 'active'; ?>">
                      <option value="active" <?php echo (($u['status'] ?? '') === 'active') ? 'selected' : ''; ?>>🟢 Activo</option>
                      <option value="disabled" <?php echo (($u['status'] ?? '') === 'disabled') ? 'selected' : ''; ?>>🟡 Deshabilitado</option>
                      <option value="banned" <?php echo (($u['status'] ?? '') === 'banned') ? 'selected' : ''; ?>>🔴 Baneado</option>
                    </select>
                  </form>
                </td>
                
                <td style="padding: 16px;">
                  <form method="post" action="<?php echo base_url('/admin/users/role'); ?>" style="margin: 0;">
                    <input type="hidden" name="id" value="<?php echo (int)$u['id']; ?>">
                    <select name="role" onchange="this.form.submit()" 
                            style="padding: 6px 8px; border: 1px solid #d1d5db; border-radius: 6px; font-size: 0.8rem; background: white; width: 100%; cursor: pointer;"
                            class="role-<?php echo $u['role'] ?? 'user'; ?>">
                      <option value="user" <?php echo (($u['role'] ?? '') === 'user') ? 'selected' : ''; ?>>👤 Usuario</option>
                      <option value="moderator" <?php echo (($u['role'] ?? '') === 'moderator') ? 'selected' : ''; ?>>🛡️ Moderador</option>
                      <option value="admin" <?php echo (($u['role'] ?? '') === 'admin') ? 'selected' : ''; ?>>⚡ Admin</option>
                    </select>
                  </form>
                </td>
                
                <td style="padding: 16px; font-size: 0.9rem; color: #64748b;">
                  <?php echo !empty($u['created_at']) ? date('d/m/Y', strtotime($u['created_at'])) : '—'; ?>
                </td>
                
                <td style="padding: 16px; font-size: 0.9rem; color: #64748b;">
                  <?php if (!empty($u['last_login'])): ?>
                    <?php echo date('d/m/Y', strtotime($u['last_login'])); ?>
                    <div style="font-size: 0.75rem; color: #94a3b8;">
                      <?php echo date('H:i', strtotime($u['last_login'])); ?>
                    </div>
                  <?php else: ?>
                    <span style="color: #94a3b8;">Nunca</span>
                  <?php endif; ?>
                </td>
                
                <td style="padding: 16px;">
                  <div style="display: flex; gap: 6px; flex-wrap: wrap;">
                    <a href="<?php echo base_url('/admin/users/profile?id=' . (int)$u['id']); ?>" target="_blank" rel="noopener noreferrer" 
                       target="_blank"
                       style="padding: 6px 10px; background: #f1f5f9; color: #374151; text-decoration: none; border-radius: 6px; font-size: 0.8rem; border: 1px solid #e2e8f0; transition: all 0.2s;">
                      👁️ Ver perfil
                    </a>
                    
                    <!-- Acciones específicas para usuarios baneados -->
                    <?php if (($u['status'] ?? 'active') === 'banned'): ?>
                      <form method="post" action="<?php echo base_url('/admin/users/unban'); ?>" style="margin: 0;">
                        <input type="hidden" name="id" value="<?php echo (int)$u['id']; ?>">
                        <button type="submit" style="padding: 6px 10px; background: #10b981; color: white; border: none; border-radius: 6px; font-size: 0.8rem; cursor: pointer;">
                          ✅ Desbanear
                        </button>
                      </form>
                    <?php else: ?>
                      <button type="button" onclick="showBanModal(<?php echo (int)$u['id']; ?>, '<?php echo htmlspecialchars($u['nick']); ?>')" 
                              style="padding: 6px 10px; background: #ef4444; color: white; border: none; border-radius: 6px; font-size: 0.8rem; cursor: pointer;">
                        🚫 Banear
                      </button>
                    <?php endif; ?>
                    
                    <!-- Promover a admin rápido -->
                    <?php if (($u['role'] ?? 'user') !== 'admin'): ?>
                      <form method="post" action="<?php echo base_url('/admin/users/role'); ?>" style="margin: 0;">
                        <input type="hidden" name="id" value="<?php echo (int)$u['id']; ?>">
                        <input type="hidden" name="role" value="admin">
                        <button type="submit" onclick="return confirm('¿Promover a administrador?')" 
                                style="padding: 6px 10px; background: #6366f1; color: white; border: none; border-radius: 6px; font-size: 0.8rem; cursor: pointer;">
                          ⚡ Admin
                        </button>
                      </form>
                    <?php endif; ?>
                  </div>
                </td>
              </tr>
            <?php endforeach; ?>
          <?php else: ?>
            <tr>
              <td colspan="8" style="padding: 60px 20px; text-align: center; color: #64748b;">
                <div style="font-size: 3rem; margin-bottom: 16px;">👥</div>
                <div style="font-size: 1.2rem; margin-bottom: 8px; font-weight: 500;">No se encontraron usuarios</div>
                <div style="font-size: 0.9rem; color: #94a3b8;">
                  <?php if (!empty($_GET['q']) || !empty($_GET['role']) || !empty($_GET['status'])): ?>
                    Prueba con otros criterios de búsqueda
                  <?php else: ?>
                    No hay usuarios registrados en el sistema
                  <?php endif; ?>
                </div>
              </td>
            </tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>

  <!-- Información y consejos -->
  <div style="margin-top: 24px; display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
    <div style="padding: 16px; background: #f0f9ff; border: 1px solid #bae6fd; border-radius: 8px;">
      <div style="display: flex; gap: 12px; align-items: start;">
        <div style="font-size: 1.2rem;">💡</div>
        <div>
          <div style="font-weight: 600; color: #0369a1; margin-bottom: 4px;">Consejos de moderación</div>
          <div style="font-size: 0.9rem; color: #0369a1;">
            • <strong>Deshabilitado</strong>: Cuentas temporales<br>
            • <strong>Baneos temporales</strong>: 1-30 días para infracciones<br>
            • <strong>Baneos permanentes</strong>: Para reincidentes graves
          </div>
        </div>
      </div>
    </div>
    
    <div style="padding: 16px; background: #fefce8; border: 1px solid #fef08a; border-radius: 8px;">
      <div style="display: flex; gap: 12px; align-items: start;">
        <div style="font-size: 1.2rem;">⚠️</div>
        <div>
          <div style="font-weight: 600; color: #ca8a04; margin-bottom: 4px;">Precauciones</div>
          <div style="font-size: 0.9rem; color: #ca8a04;">
            • Los baneos temporales se levantan automáticamente<br>
            • No elimines el último administrador<br>
            • Documenta siempre el motivo del ban
          </div>
        </div>
      </div>
    </div>
  </div>
</section>

<!-- Modal para baneos -->
<div id="banModal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 1000; justify-content: center; align-items: center;">
  <div style="background: white; padding: 24px; border-radius: 12px; width: 90%; max-width: 500px; box-shadow: 0 10px 25px rgba(0,0,0,0.2);">
    <h3 style="margin: 0 0 16px 0; color: #1a1d23;">Banear Usuario</h3>
    <form id="banForm" method="post" action="<?php echo base_url('/admin/users/status'); ?>">
      <input type="hidden" name="id" id="banUserId">
      <input type="hidden" name="status" value="banned">
      
      <div style="margin-bottom: 16px;">
        <label style="display: block; margin-bottom: 6px; font-weight: 500; color: #374151;">Duración del ban</label>
        <select name="ban_duration" style="width: 100%; padding: 10px 12px; border: 1px solid #d1d5db; border-radius: 8px; font-size: 0.9rem;">
          <option value="0">Permanente</option>
          <option value="1">1 día</option>
          <option value="3">3 días</option>
          <option value="7">7 días</option>
          <option value="15">15 días</option>
          <option value="30">30 días</option>
          <option value="90">90 días</option>
        </select>
      </div>
      
      <div style="margin-bottom: 20px;">
        <label style="display: block; margin-bottom: 6px; font-weight: 500; color: #374151;">Motivo del ban</label>
        <textarea name="ban_reason" placeholder="Describe el motivo del ban..." 
                  style="width: 100%; padding: 10px 12px; border: 1px solid #d1d5db; border-radius: 8px; font-size: 0.9rem; min-height: 80px; resize: vertical;"></textarea>
      </div>
      
      <div style="display: flex; gap: 12px; justify-content: flex-end;">
        <button type="button" onclick="hideBanModal()" 
                style="padding: 10px 20px; background: #f1f5f9; color: #374151; border: 1px solid #d1d5db; border-radius: 8px; cursor: pointer;">
          Cancelar
        </button>
        <button type="submit" 
                style="padding: 10px 20px; background: #ef4444; color: white; border: none; border-radius: 8px; cursor: pointer;">
          🚫 Banear Usuario
        </button>
      </div>
    </form>
  </div>
</div>

<style>
.status-active { border-color: #10b981 !important; background: #f0fdf4 !important; color: #065f46 !important; }
.status-disabled { border-color: #f59e0b !important; background: #fffbeb !important; color: #92400e !important; }
.status-banned { border-color: #ef4444 !important; background: #fef2f2 !important; color: #991b1b !important; }

.role-user { border-color: #6b7280 !important; background: #f9fafb !important; color: #374151 !important; }
.role-moderator { border-color: #f59e0b !important; background: #fffbeb !important; color: #92400e !important; }
.role-admin { border-color: #6366f1 !important; background: #eef2ff !important; color: #3730a3 !important; }

.btn-primary:hover { background: #4f46e5 !important; transform: translateY(-1px); box-shadow: 0 2px 8px rgba(99, 102, 241, 0.3); }

tr:hover { background: #f8fafc !important; }

select:focus, textarea:focus { outline: none; border-color: #6366f1 !important; box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1); }

a:hover { background: #e2e8f0 !important; transform: translateY(-1px); }

button:hover { transform: translateY(-1px); box-shadow: 0 2px 4px rgba(0,0,0,0.1); }

@media (max-width: 768px) {
  .filter-card form {
    grid-template-columns: 1fr !important;
  }
  
  section {
    padding: 0 12px !important;
  }
}
</style>

<script>
function showBanModal(userId, userName) {
    document.getElementById('banUserId').value = userId;
    document.getElementById('banModal').style.display = 'flex';
    document.querySelector('#banModal h3').textContent = `Banear a ${userName}`;
}

function hideBanModal() {
    document.getElementById('banModal').style.display = 'none';
}

// Cerrar modal al hacer click fuera
document.getElementById('banModal').addEventListener('click', function(e) {
    if (e.target === this) {
        hideBanModal();
    }
});
</script>