{% extends "online/base.html" %}
{% block title %}Administración{% endblock %}
{% block content %}
<header>
  <p class="eyebrow">PANEL DEL SERVIDOR</p>
  <h1>Administración</h1>
  <p>Gestión auditada de universos, jugadores, moderación, colaboradores, privacidad y comercio.</p>
</header>
<nav class="admin-nav" aria-label="Secciones administrativas">
  {% if 'dashboard.view' in permissions %}<a href="{{ url_for('admin_dashboard') }}" {% if admin_section == 'dashboard' %}aria-current="page"{% endif %}>Resumen</a>{% endif %}
  {% if 'universe.manage' in permissions %}<a href="{{ url_for('admin_universes') }}" {% if admin_section in ['universes','universe_detail'] %}aria-current="page"{% endif %}>Universos</a>{% endif %}
  {% if 'player.view' in permissions %}<a href="{{ url_for('admin_players') }}" {% if admin_section in ['players','player_detail'] %}aria-current="page"{% endif %}>Jugadores</a>{% endif %}
  {% if 'report.manage' in permissions %}<a href="{{ url_for('admin_reports') }}" {% if admin_section in ['reports','report_detail'] %}aria-current="page"{% endif %}>Reportes</a><a href="{{ url_for('admin_privacy_requests') }}" {% if admin_section == 'privacy' %}aria-current="page"{% endif %}>Privacidad</a>{% endif %}
  {% if 'staff.manage' in permissions %}<a href="{{ url_for('admin_staff') }}" {% if admin_section == 'staff' %}aria-current="page"{% endif %}>Colaboradores</a>{% endif %}
  {% if 'commerce.manage' in permissions %}<a href="{{ url_for('admin_commerce') }}" {% if admin_section == 'commerce' %}aria-current="page"{% endif %}>PayPal y tienda</a>{% endif %}
  {% if 'operations.manage' in permissions %}<a href="{{ url_for('admin_operations') }}" {% if admin_section == 'operations' %}aria-current="page"{% endif %}>Operaciones</a>{% endif %}
  {% if 'settings.manage' in permissions %}<a href="{{ url_for('admin_settings') }}" {% if admin_section == 'settings' %}aria-current="page"{% endif %}>Configuración</a>{% endif %}
  {% if 'audit.view' in permissions %}<a href="{{ url_for('admin_audit') }}" {% if admin_section == 'audit' %}aria-current="page"{% endif %}>Auditoría</a>{% endif %}
</nav>

{% if admin_section == "dashboard" %}
<section aria-labelledby="admin-summary-title">
  <h2 id="admin-summary-title">Estado del servicio</h2>
  {% if stats.staff_without_mfa %}<div class="notice notice-warning" role="status">{{ stats.staff_without_mfa }} cuentas del equipo no han activado todavía la verificación en dos pasos.</div>{% endif %}
  <div class="metric-grid metric-grid-six">
    <article><span>Cuentas</span><strong>{{ stats.accounts }}</strong></article>
    <article><span>Activas en 5 minutos</span><strong>{{ stats.online }}</strong></article>
    <article><span>Universos</span><strong>{{ stats.universes }}</strong></article>
    <article><span>Reportes pendientes</span><strong>{{ stats.reports }}</strong></article>
    <article><span>Compras a revisar</span><strong>{{ stats.review_purchases }}</strong></article>
    <article><span>Capturado</span><strong>{{ "%.2f"|format(stats.revenue_cents / 100) }}</strong></article>
  </div>
</section>
<div class="admin-columns">
  <section class="server-card"><h2>Reportes recientes</h2>{% for report in admin_reports %}<p><a href="{{ url_for('admin_report_detail', report_id=report.id) }}">#{{ report.id }} {{ report.subject }}</a> — {{ report.username }} — {{ report.priority }}</p>{% else %}<p>No hay reportes urgentes.</p>{% endfor %}</section>
  <section class="server-card"><h2>Actividad reciente</h2>{% for item in recent_actions %}<p>{{ item.created_at|date_label }} — {{ item.username or "cuenta eliminada" }} — {{ item.endpoint }} — HTTP {{ item.result_status }}</p>{% else %}<p>No hay actividad registrada.</p>{% endfor %}</section>
</div>

{% elif admin_section == "universes" %}
<section class="server-card" aria-labelledby="create-universe-title">
  <h2 id="create-universe-title">Crear un universo administrado</h2>
  <p>Puede ser solo humano, solo IA o mixto. Los jugadores humanos comienzan con el mismo perfil inicial que una IA normal.</p>
  <form method="post" class="admin-form">
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
    <div class="admin-columns">
      <label>Nombre del universo<input name="name" maxlength="40" value="Universo servidor" required></label>
      <label>Participantes<select name="access_mode">{% for key, label in UNIVERSE_ACCESS_MODES.items() %}<option value="{{ key }}">{{ label }}</option>{% endfor %}</select></label>
      <label>Política de idioma<select name="language_policy"><option value="mixed">Mixto: cada jugador usa su idioma</option><option value="single">Un solo idioma de comunicación</option></select></label>
      <label>Idioma de comunicación<select name="communication_language">{% for code, language in LANGUAGES.items() %}<option value="{{ code }}" {% if code == site.default_language %}selected{% endif %}>{{ language.native_name }}</option>{% endfor %}</select></label>
      <label>Plazas humanas<input name="human_slots" type="number" min="0" value="32"></label>
      <label>Rivales IA<input name="ai_count" type="number" min="0" value="8"></label>
      <label>Granjas IA<input name="farm_ai_count" type="number" min="0" value="4"></label>
      <label>Dificultad<select name="difficulty"><option value="easy">Relajada</option><option value="normal" selected>Equilibrada</option><option value="hard">Veterana</option></select></label>
      <label>Velocidad<select name="speed"><option>1</option><option>5</option><option selected>10</option><option>20</option><option>50</option></select></label>
      <label>Galaxias<input name="galaxy_count" type="number" min="1" value="1"></label>
      <label>Sistemas por galaxia<input name="galaxy_size" type="number" min="1" value="30"></label>
      <label>Semilla<input name="universe_seed" maxlength="80"></label>
      <label>Minutos de paz<input name="peace_minutes" type="number" min="0" max="1440" value="30"></label>
      <label>Modo de victoria<select name="victory_mode"><option value="sandbox">Libre</option><option value="score">Puntuación</option><option value="domination">Dominación</option></select></label>
      <label>Puntuación de victoria<input name="victory_score" type="number" min="5000" max="1000000" value="50000"></label>
      <label>Riqueza de recursos<select name="resource_richness"><option value="scarce">Escasa</option><option value="standard" selected>Estándar</option><option value="abundant">Abundante</option><option value="lavish">Excepcional</option></select></label>
      <label>Riqueza agrícola<select name="agricultural_richness"><option value="scarce">Escasa</option><option value="standard" selected>Estándar</option><option value="abundant">Abundante</option><option value="lavish">Excepcional</option></select></label>
      <label>Agresividad IA<select name="ai_aggression"><option value="peaceful">Pacífica</option><option value="low">Baja</option><option value="normal" selected>Normal</option><option value="high">Alta</option><option value="relentless">Implacable</option></select></label>
      <label>Adaptabilidad IA<select name="ai_adaptability"><option value="predictable">Predecible</option><option value="adaptive" selected>Adaptativa</option><option value="chaotic">Caótica</option></select></label>
      <label>Frecuencia de eventos<select name="event_frequency"><option value="off">Desactivada</option><option value="low">Baja</option><option value="normal" selected>Normal</option><option value="high">Alta</option><option value="chaotic">Caótica</option></select></label>
      <label>Multiplicador económico<select name="economy_multiplier"><option>0.5</option><option selected>1</option><option>2</option><option>4</option></select></label>
      <label>Multiplicador de flotas<select name="fleet_speed_multiplier"><option>0.5</option><option selected>1</option><option>2</option><option>4</option></select></label>
      <label>Multiplicador científico<select name="research_speed_multiplier"><option>0.5</option><option selected>1</option><option>2</option><option>4</option></select></label>
      <label>Topología de sistemas<select name="system_topology"><option value="linear">Lineal</option><option value="circular">Circular</option></select></label>
      <label>Topología galáctica<select name="galaxy_topology"><option value="linear">Lineal</option><option value="circular">Circular</option></select></label>
      <label>Escombros de flota, porcentaje<input name="fleet_debris_percent" type="number" min="0" max="100" value="30"></label>
      <label>Escombros de defensas, porcentaje<input name="defense_debris_percent" type="number" min="0" max="100" value="0"></label>
      <label>Deuterio en escombros, porcentaje<input name="deuterium_debris_percent" type="number" min="0" max="100" value="0"></label>
      <label>Recursos raros<select name="rare_resource_richness"><option value="scarce">Escasos</option><option value="standard" selected>Estándar</option><option value="abundant">Abundantes</option><option value="wild">Salvajes</option></select></label>
      <label>Volatilidad de expediciones<select name="expedition_volatility"><option value="safe">Segura</option><option value="normal" selected>Normal</option><option value="dangerous">Peligrosa</option><option value="anomalous">Anómala</option></select></label>
      <label>Presión ecológica<select name="ecology_pressure"><option value="relaxed">Relajada</option><option value="standard" selected>Estándar</option><option value="harsh">Dura</option><option value="catastrophic">Catastrófica</option></select></label>
      <label>Densidad de anomalías<select name="anomaly_density"><option value="sparse">Dispersa</option><option value="standard" selected>Estándar</option><option value="dense">Densa</option><option value="surreal">Surrealista</option></select></label>
      <label>Era inicial<select name="starting_era"><option value="pioneer">Pionera</option><option value="established">Establecida</option><option value="advanced">Avanzada</option></select></label>
      <label>Ventaja inicial<select name="starting_boon"><option value="none">Ninguna</option><option value="industrial">Industrial</option><option value="scientific">Científica</option><option value="exploratory">Exploratoria</option><option value="diplomatic">Diplomática</option><option value="ecological">Ecológica</option><option value="random">Aleatoria</option></select></label>
    </div>
    <p class="notice notice-warning">El servidor no impone topes de plazas, IA, granjas, galaxias ni sistemas. El administrador debe dimensionar el hardware y dar al universo espacio suficiente para todos sus imperios.</p>
    <button class="button button-primary" type="submit">Crear universo</button>
  </form>
</section>
<section aria-labelledby="universe-list-title"><h2 id="universe-list-title">Universos existentes</h2>
  <div class="server-table-wrap"><table class="server-table"><thead><tr><th>Universo</th><th>Estado</th><th>Humanos</th><th>IA</th><th>Granjas</th><th>Tipo</th><th>Idioma</th></tr></thead><tbody>
  {% for item in universes %}<tr><td><a href="{{ url_for('admin_universe_detail', game_id=item.row.id) }}">{{ item.row.name }}</a></td><td>{{ item.row.status }}</td><td>{{ item.counts.humans or 0 }}</td><td>{{ item.counts.ais or 0 }}</td><td>{{ item.counts.farms or 0 }}</td><td>{{ UNIVERSE_ACCESS_MODES.get(item.config.access_mode, "Local o anterior") }}</td><td>{{ "Mixto" if item.config.language_policy != "single" else LANGUAGES.get(item.config.communication_language or "es", LANGUAGES.es).native_name }}</td></tr>{% endfor %}
  </tbody></table></div>
</section>

{% elif admin_section == "universe_detail" %}
<p><a href="{{ url_for('admin_universes') }}">Volver a universos</a></p>
<section class="server-card"><p class="eyebrow">UNIVERSO #{{ game.id }}</p><h2>{{ game.name }}</h2>
  <dl class="definition-list"><dt>Estado</dt><dd>{{ game.status }}</dd><dt>Velocidad</dt><dd>×{{ game.speed }}</dd><dt>Tamaño</dt><dd>{{ game_config.galaxy_count or 1 }} galaxias × {{ game.galaxy_size }} sistemas</dd><dt>Modo fuera de línea</dt><dd>{{ game_config.offline_mode }}</dd></dl>
  <form method="post" class="admin-form">
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input type="hidden" name="action" value="configuration">
    <label>Nombre del universo<input name="name" maxlength="80" value="{{ game.name }}" required></label>
    <label>Participantes<select name="access_mode">{% for key, label in UNIVERSE_ACCESS_MODES.items() %}<option value="{{ key }}" {% if game_config.access_mode == key %}selected{% endif %}>{{ label }}</option>{% endfor %}</select></label>
    <label>Política de idioma<select name="language_policy"><option value="mixed" {% if game_config.language_policy != "single" %}selected{% endif %}>Mixto: cada jugador usa su idioma</option><option value="single" {% if game_config.language_policy == "single" %}selected{% endif %}>Un solo idioma de comunicación</option></select></label>
    <label>Idioma de comunicación<select name="communication_language">{% for code, language in LANGUAGES.items() %}<option value="{{ code }}" {% if (game_config.communication_language or "es") == code %}selected{% endif %}>{{ language.native_name }}</option>{% endfor %}</select></label>
    <p>En un universo de un solo idioma, la interfaz sigue la preferencia personal, pero informes, avisos y comunicación se generan en el idioma indicado.</p>
    <label>Plazas humanas<input name="human_slots" type="number" min="0" value="{{ game_config.human_slots or 0 }}"></label>
    <label>Dificultad<select name="difficulty"><option value="easy" {% if game.difficulty == 'easy' %}selected{% endif %}>Relajada</option><option value="normal" {% if game.difficulty == 'normal' %}selected{% endif %}>Equilibrada</option><option value="hard" {% if game.difficulty == 'hard' %}selected{% endif %}>Veterana</option></select></label>
    <label>Velocidad<input name="speed" type="number" min="1" value="{{ game.speed }}"></label>
    <label class="check-label"><input type="checkbox" name="registration_open" value="1" {% if game_config.registration_open %}checked{% endif %}> Permitir nuevas incorporaciones</label>
    <label class="check-label"><input type="checkbox" name="store_enabled" value="1" {% if game_config.store_enabled %}checked{% endif %}> Habilitar tienda en este universo</label>
    <button class="button button-primary" type="submit">Guardar acceso y tienda</button>
  </form>
  <form method="post"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input type="hidden" name="action" value="pause"><button class="button" type="submit">{{ "Reanudar" if game.status == "paused" else "Pausar" }} universo</button></form>
</section>
<section class="server-card"><h2>Reglas avanzadas y futuras</h2><p>Editor completo del objeto de reglas. Conserva automáticamente el modo administrado y admite nuevas claves que se incorporen al juego sin tener que ampliar este formulario.</p><form method="post" class="admin-form"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input type="hidden" name="action" value="rules_json"><label>Configuración JSON<textarea name="rules_json" rows="24" spellcheck="false" required>{{ game_config|tojson(indent=2) }}</textarea></label><button class="button button-primary" type="submit">Validar y guardar todas las reglas</button></form></section>
<section class="server-card danger-zone" aria-labelledby="delete-universe-title">
  <h2 id="delete-universe-title">Eliminar universo definitivamente</h2>
  <p>La opción está visible aunque el universo siga activo. Elimina jugadores, IA, planetas y todo su progreso. Antes se crea automáticamente una copia verificada de la base de datos.</p>
  {% if purchase_count %}
  <p><strong>Borrado bloqueado:</strong> este universo tiene {{ purchase_count }} compras vinculadas y debe conservarse para mantener pedidos, reembolsos y auditoría.</p>
  {% else %}
  <form method="post" class="admin-form">
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
    <input type="hidden" name="action" value="delete">
    <label>Escribe exactamente {{ game.name }} para confirmar
      <input name="confirmation" autocomplete="off" required>
    </label>
    <button class="button button-danger" type="submit">Eliminar universo definitivamente</button>
  </form>
  {% endif %}
</section>
<div class="admin-columns">
<section class="server-card"><h2>Ampliar universo</h2><p>Sin límites artificiales. Puede añadir rivales, granjas y espacio en una sola operación.</p><form method="post" class="admin-form"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input type="hidden" name="action" value="add_ai"><label>Rivales IA adicionales<input name="additional_ai" type="number" min="0" value="0"></label><label>Granjas IA adicionales<input name="additional_farms" type="number" min="0" value="0"></label><label>Total de galaxias solicitado<input name="requested_galaxies" type="number" min="{{ game_config.galaxy_count or 1 }}" value="{{ game_config.galaxy_count or 1 }}"></label><label>Sistemas por galaxia solicitados<input name="requested_systems" type="number" min="{{ game.galaxy_size }}" value="{{ game.galaxy_size }}"></label><button class="button button-primary" type="submit">Ampliar universo</button></form></section>
<section class="server-card"><h2>Retirar IA</h2><form method="post" class="admin-form"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input type="hidden" name="action" value="remove_ai"><label>Imperio IA<select name="empire_id">{% for ai in ais %}<option value="{{ ai.id }}">{{ ai.name }}{% if ai.is_farm_world %} — granja{% endif %}</option>{% endfor %}</select></label><button class="button" type="submit">Retirar IA seleccionada</button></form></section>
</div>
<section><h2>Jugadores humanos</h2>{% if members %}<div class="server-table-wrap"><table class="server-table"><thead><tr><th>Cuenta</th><th>Imperio</th><th>Estado</th><th>Planetas</th><th>Puntos</th></tr></thead><tbody>{% for member in members %}<tr><td><a href="{{ url_for('admin_player_detail', account_id=member.account_id) }}">{{ member.username }}</a></td><td>{{ member.empire_name }}</td><td>{{ member.status }}</td><td>{{ member.planet_count }}</td><td>{{ member.score|number }}</td></tr>{% endfor %}</tbody></table></div>{% else %}<p>Sin jugadores humanos.</p>{% endif %}</section>
<section><h2>Imperios IA</h2>{% if ais %}<div class="server-table-wrap"><table class="server-table"><thead><tr><th>Imperio</th><th>Comandante</th><th>Tipo</th><th>Planetas</th><th>Puntos</th></tr></thead><tbody>{% for ai in ais %}<tr><td>{{ ai.name }}</td><td>{{ ai.commander }}</td><td>{{ "Granja" if ai.is_farm_world else "Rival" }}</td><td>{{ ai.planet_count }}</td><td>{{ ai.score|number }}</td></tr>{% endfor %}</tbody></table></div>{% endif %}</section>

{% elif admin_section == "players" %}
<section aria-labelledby="players-title"><h2 id="players-title">Jugadores</h2>
  {% if 'player.moderate' in permissions %}<details class="server-card"><summary>Crear una cuenta manualmente</summary><form method="post" class="admin-form"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><label>Usuario<input name="username" minlength="3" maxlength="30" required></label><label>Correo<input name="email" type="email" required></label><label>Contraseña temporal segura<input name="password" type="password" minlength="12" maxlength="128" autocomplete="new-password" required></label><label>Estado<select name="status"><option value="active">Activa</option><option value="pending">Pendiente</option></select></label><label class="check-label"><input type="checkbox" name="email_verified" value="1"> Correo ya verificado</label><label class="check-label"><input type="checkbox" name="age_confirmed" value="1" checked> Edad mínima confirmada</label><button class="button button-primary" type="submit">Crear cuenta sin cupo global</button></form></details>{% endif %}
  <form method="get" class="server-form"><label for="q">Buscar por usuario o correo</label><input id="q" name="q" value="{{ search_query }}"><button class="button" type="submit">Buscar</button></form>
  <p>{{ total_players }} cuentas encontradas. Página {{ player_page }} de {{ player_pages }}.</p>
  <div class="server-table-wrap"><table class="server-table"><thead><tr><th>Usuario</th><th>Correo</th><th>Estado</th><th>Universos</th><th>Rol</th><th>Última actividad</th></tr></thead><tbody>{% for item in players %}<tr><td><a href="{{ url_for('admin_player_detail', account_id=item.id) }}">{{ item.username }}</a></td><td>{{ item.email }}</td><td>{{ ACCOUNT_STATUSES.get(item.status, item.status) }}</td><td>{{ item.universe_count }}</td><td>{{ ROLE_LABELS.get(item.staff_role, "Jugador") }}</td><td>{{ item.last_seen_at|date_label if item.last_seen_at else "Nunca" }}</td></tr>{% endfor %}</tbody></table></div>
  <nav class="server-actions" aria-label="Paginación de jugadores">{% if player_page > 1 %}<a class="button" href="{{ url_for('admin_players', q=search_query, page=player_page-1) }}">Página anterior</a>{% endif %}{% if player_page < player_pages %}<a class="button" href="{{ url_for('admin_players', q=search_query, page=player_page+1) }}">Página siguiente</a>{% endif %}</nav>
</section>

{% elif admin_section == "player_detail" %}
<p><a href="{{ url_for('admin_players') }}">Volver a jugadores</a></p>
<section class="server-card"><p class="eyebrow">CUENTA #{{ player.id }}</p><h2>{{ player.username }}</h2><dl class="definition-list"><dt>Correo</dt><dd>{{ player.email }}</dd><dt>Correo verificado</dt><dd>{{ "Sí" if player.email_verified else "No" }}</dd><dt>Estado</dt><dd>{{ ACCOUNT_STATUSES.get(player.status, player.status) }}</dd><dt>Registro</dt><dd>{{ player.created_at|date_label }}</dd><dt>Último acceso</dt><dd>{{ player.last_login_at|date_label if player.last_login_at else "Nunca" }}</dd><dt>Nota de moderación</dt><dd>{{ player.moderation_note or "Sin nota" }}</dd></dl></section>
{% if 'player.moderate' in permissions %}
<div class="admin-columns">
<section class="server-card"><h2>Identidad de la cuenta</h2><form method="post" class="admin-form"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input type="hidden" name="action" value="identity"><label>Usuario<input name="username" minlength="3" maxlength="30" value="{{ player.username }}" required></label><label>Correo<input name="email" type="email" value="{{ player.email }}" required></label><label class="check-label"><input type="checkbox" name="email_verified" value="1" {% if player.email_verified %}checked{% endif %}> Correo verificado</label><button class="button button-primary" type="submit">Guardar identidad y cerrar sesiones</button></form></section>
<section class="server-card"><h2>Estado de la cuenta</h2><form method="post" class="admin-form"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input type="hidden" name="action" value="status"><label>Nuevo estado<select name="status">{% for key, label in ACCOUNT_STATUSES.items() %}{% if key != 'deleted' %}<option value="{{ key }}" {% if player.status == key %}selected{% endif %}>{{ label }}</option>{% endif %}{% endfor %}</select></label><label>Motivo interno<textarea name="moderation_note" maxlength="2000">{{ player.moderation_note }}</textarea></label><button class="button button-primary" type="submit">Cambiar estado y cerrar sesiones</button></form></section>
<section class="server-card"><h2>Seguridad</h2><form method="post"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input type="hidden" name="action" value="invalidate_sessions"><button class="button" type="submit">Cerrar todas sus sesiones</button></form><form method="post"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input type="hidden" name="action" value="unlock"><button class="button" type="submit">Retirar bloqueo por intentos fallidos</button></form><form method="post"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input type="hidden" name="action" value="reset_link"><button class="button" type="submit">Generar enlace de recuperación de una hora</button></form>{% if not player.email_verified %}<form method="post"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input type="hidden" name="action" value="verify_email"><button class="button" type="submit">Marcar correo como verificado</button></form>{% endif %}<form method="post"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input type="hidden" name="action" value="reset_mfa"><button class="button" type="submit">Retirar segundo factor para recuperación</button></form></section>
</div>
<section class="server-card"><h2>Medidas de moderación</h2><p>Permite advertencias, suspensiones y expulsiones globales o limitadas a un universo, temporales o permanentes. El motivo público explica la decisión al jugador y el interno conserva el contexto del equipo.</p><form method="post" class="admin-form"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input type="hidden" name="action" value="sanction"><label>Medida<select name="sanction_type"><option value="warning">Advertencia</option><option value="suspension">Suspensión</option><option value="ban">Expulsión</option></select></label><label>Ámbito<select name="sanction_game_id"><option value="0">Toda la cuenta</option>{% for membership in memberships %}<option value="{{ membership.game_id }}">{{ membership.game_name }}</option>{% endfor %}</select></label><label>Duración en horas, cero permanente<input name="duration_hours" type="number" min="0" value="24"></label><label>Código de motivo<input name="reason_code" maxlength="80" value="conducta"></label><label>Motivo visible para el jugador<textarea name="public_reason" maxlength="2000" required></textarea></label><label>Nota interna<textarea name="internal_note" maxlength="2000"></textarea></label><button class="button button-primary" type="submit">Aplicar medida</button></form></section>
<section><h2>Historial de medidas</h2>{% for sanction in sanctions %}<article class="server-card"><h3>#{{ sanction.id }} — {{ sanction.sanction_type }} — {{ sanction.game_name or "cuenta completa" }}</h3><p>{{ sanction.public_reason }}</p><p><small>Aplicada por {{ sanction.creator_name or "sistema" }} el {{ sanction.created_at|date_label }}. {% if sanction.expires_at %}Caduca: {{ sanction.expires_at|date_label }}.{% else %}Sin caducidad.{% endif %} {% if sanction.revoked_at %}Revocada por {{ sanction.revoker_name or "sistema" }}: {{ sanction.revocation_reason }}{% endif %}</small></p>{% if not sanction.revoked_at %}<form method="post" class="admin-form"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input type="hidden" name="action" value="revoke_sanction"><input type="hidden" name="sanction_id" value="{{ sanction.id }}"><label>Motivo de revocación<input name="revocation_reason" maxlength="1000" value="Revisión administrativa"></label><button type="submit">Revocar medida</button></form>{% endif %}</article>{% else %}<p>No hay medidas registradas.</p>{% endfor %}</section>
{% if 'settings.manage' in permissions and player.id != account.id %}<section class="server-card danger-zone"><h2>Pseudonimizar y cerrar la cuenta</h2><p>Utiliza esta operación solo después de verificar una solicitud de supresión y las obligaciones de conservación. Retira correo, credenciales, segundo factor, sesiones, roles y nombres de imperios; conserva referencias contables pseudónimas.</p><form method="post" class="admin-form"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input type="hidden" name="action" value="anonymize"><label>Escribe ELIMINAR para confirmar<input name="confirmation" autocomplete="off" required></label><button class="button button-danger" type="submit">Pseudonimizar cuenta de forma irreversible</button></form></section>{% endif %}
{% endif %}
<section><h2>Membresías</h2>{% if 'player.moderate' in permissions and available_games %}<details class="server-card"><summary>Incorporar manualmente a otro universo</summary><p>La administración puede incorporar la cuenta aunque el registro del universo esté cerrado; debe existir espacio físico para el planeta.</p><form method="post" class="admin-form"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input type="hidden" name="action" value="join_universe"><label>Universo<select name="game_id">{% for available_game in available_games %}<option value="{{ available_game.id }}">{{ available_game.name }}</option>{% endfor %}</select></label><label>Comandante<input name="commander" maxlength="30" required></label><label>Imperio<input name="empire_name" maxlength="40" required></label><button class="button button-primary" type="submit">Incorporar jugador</button></form></details>{% endif %}<div class="server-grid">{% for membership in memberships %}<article class="server-card"><h3>{{ membership.game_name }}</h3><p>{{ membership.empire_name }} — {{ membership.score|number }} puntos — {{ membership.status }}</p>{% if 'player.moderate' in permissions %}<form method="post" class="admin-form"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input type="hidden" name="action" value="membership"><input type="hidden" name="membership_id" value="{{ membership.id }}"><label>Estado de membresía<select name="membership_status">{% for state in ['active','suspended','banned','left'] %}<option {% if membership.status == state %}selected{% endif %}>{{ state }}</option>{% endfor %}</select></label><button class="button" type="submit">Actualizar membresía</button></form><details><summary>Transferir imperio a otra cuenta</summary><form method="post" class="admin-form"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input type="hidden" name="action" value="transfer_membership"><input type="hidden" name="membership_id" value="{{ membership.id }}"><label>ID de la cuenta de destino<input name="destination_account_id" type="number" min="1" required></label><button type="submit">Transferir membresía e imperio</button></form></details>{% endif %}</article>{% endfor %}</div></section>
{% if 'player.moderate' in permissions %}<section><h2>Ajuste administrativo de recursos</h2><p>Puede sumar, retirar o fijar una cantidad exacta. Los valores nunca quedan por debajo de cero y toda modificación queda auditada.</p><form method="post" class="admin-form server-card"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input type="hidden" name="action" value="adjust_resource"><label>Planeta<select name="planet_id">{% for planet in player_planets %}<option value="{{ planet.id }}" data-membership="{{ planet.membership_id }}">{{ planet.game_name }} — {{ planet.name }}</option>{% endfor %}</select></label><label>Membresía<select name="membership_id">{% for membership in memberships %}<option value="{{ membership.id }}">{{ membership.game_name }}</option>{% endfor %}</select></label><label>Recurso<select name="item">{% for key in ['metal','crystal','deuterium','food','credits'] %}<option value="{{ key }}">{{ key }}</option>{% endfor %}{% for key in strategic_resource_keys %}<option value="{{ key }}">{{ key }}</option>{% endfor %}</select></label><label>Operación<select name="adjustment_mode"><option value="change">Sumar o retirar</option><option value="set">Fijar cantidad exacta</option></select></label><label>Cantidad, negativa para retirar<input name="amount" type="number" value="0"></label><button class="button button-primary" type="submit">Aplicar recurso</button></form></section>{% endif %}
{% if 'player.moderate' in permissions %}
<section><h2>Editor administrativo de progreso</h2><p>Permite reparar estados o conceder contenido. No procesa un pago y todas las acciones quedan auditadas.</p><div class="admin-columns">
  <form method="post" class="admin-form server-card"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input type="hidden" name="action" value="set_level"><h3>Fijar edificio o tecnología</h3><label>Membresía<select name="membership_id">{% for membership in memberships %}<option value="{{ membership.id }}">{{ membership.game_name }}</option>{% endfor %}</select></label><label>Planeta<select name="planet_id">{% for planet in player_planets %}<option value="{{ planet.id }}">{{ planet.game_name }} — {{ planet.name }}</option>{% endfor %}</select></label><label>Clase<select name="level_kind"><option value="building">Edificio</option><option value="technology">Tecnología imperial</option></select></label><label>Clave de edificio o tecnología<input name="item" list="admin-level-items" required></label><datalist id="admin-level-items">{% for key in BUILDINGS %}<option value="{{ key }}">{% endfor %}{% for key in TECHNOLOGIES %}<option value="{{ key }}">{% endfor %}</datalist><label>Nivel exacto, cero para retirar<input name="level" type="number" min="0" value="0"></label><button class="button button-primary" type="submit">Fijar nivel</button></form>
  <form method="post" class="admin-form server-card"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input type="hidden" name="action" value="adjust_unit"><h3>Ajustar naves o defensas</h3><label>Membresía<select name="membership_id">{% for membership in memberships %}<option value="{{ membership.id }}">{{ membership.game_name }}</option>{% endfor %}</select></label><label>Planeta<select name="planet_id">{% for planet in player_planets %}<option value="{{ planet.id }}">{{ planet.game_name }} — {{ planet.name }}</option>{% endfor %}</select></label><label>Unidad<input name="item" list="admin-unit-items" required></label><datalist id="admin-unit-items">{% for key in SHIPS %}<option value="{{ key }}">{% endfor %}{% for key in DEFENSES %}<option value="{{ key }}">{% endfor %}</datalist><label>Operación<select name="adjustment_mode"><option value="change">Sumar o retirar</option><option value="set">Fijar cantidad exacta</option></select></label><label>Cantidad, negativa para retirar<input name="amount" type="number" value="0"></label><button class="button button-primary" type="submit">Aplicar unidades</button></form>
  <section class="server-card"><h3>Propiedades de planetas</h3><p>Cada formulario parte de los valores reales del planeta y permite cambiar nombre, tamaño, clima, población y ecología.</p>{% for planet in player_planets %}<details><summary>{{ planet.game_name }} — {{ planet.name }} — {{ planet.fields_max }} campos</summary><form method="post" class="admin-form"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input type="hidden" name="action" value="planet_properties"><input type="hidden" name="membership_id" value="{{ planet.membership_id }}"><input type="hidden" name="planet_id" value="{{ planet.id }}"><label>Nombre<input name="planet_name" maxlength="80" value="{{ planet.name }}" required></label><label>Campos máximos<input name="fields_max" type="number" min="1" value="{{ planet.fields_max }}"></label><label>Temperatura<input name="temperature" type="number" value="{{ planet.temperature }}"></label><label>Población<input name="population" type="number" min="0" step="any" value="{{ planet.population }}"></label><label>Moral, de cero a cien<input name="morale" type="number" min="0" max="100" step="any" value="{{ planet.morale }}"></label><label>Contaminación<input name="pollution" type="number" min="0" step="any" value="{{ planet.pollution }}"></label><label>Habitabilidad, de cero a cien<input name="habitability" type="number" min="0" max="100" step="any" value="{{ planet.habitability }}"></label><button class="button button-primary" type="submit">Guardar este planeta</button></form></details>{% endfor %}</section>
  <section class="server-card"><h3>Crear, editar o retirar lunas</h3>{% for planet in player_planets %}<details><summary>{{ planet.game_name }} — {{ planet.name }} — {{ "con luna" if planet.moon_id else "sin luna" }}</summary><form method="post" class="admin-form"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input type="hidden" name="action" value="moon"><input type="hidden" name="membership_id" value="{{ planet.membership_id }}"><input type="hidden" name="planet_id" value="{{ planet.id }}"><label>Acción<select name="moon_action">{% if planet.moon_id %}<option value="edit">Editar luna existente</option><option value="delete">Eliminar luna existente</option>{% else %}<option value="create">Crear luna</option>{% endif %}</select></label><label>Nombre lunar<input name="moon_name" maxlength="80" value="{{ planet.moon_name or ('Luna de ' ~ planet.name) }}"></label><label>Diámetro<input name="moon_diameter" type="number" min="1" value="{{ planet.moon_diameter or 8000 }}"></label><label>Campos lunares máximos<input name="moon_fields_max" type="number" min="1" value="{{ planet.moon_fields_max or 12 }}"></label><button class="button button-primary" type="submit">Aplicar a esta luna</button></form></details>{% endfor %}</section>
</div></section>
{% endif %}
<section><h2>Últimas acciones</h2><div class="server-table-wrap"><table class="server-table"><thead><tr><th>Fecha</th><th>Acción</th><th>Resultado</th><th>Universo</th></tr></thead><tbody>{% for item in player_actions %}<tr><td>{{ item.created_at|date_label }}</td><td>{{ item.endpoint }}</td><td>HTTP {{ item.result_status }}</td><td>{{ item.game_id or "—" }}</td></tr>{% endfor %}</tbody></table></div></section>
<section><h2>Compras</h2><div class="server-table-wrap"><table class="server-table"><thead><tr><th>Pedido</th><th>Producto</th><th>Importe</th><th>Estado</th></tr></thead><tbody>{% for item in purchases %}<tr><td>#{{ item.id }}</td><td>{{ item.product_name }}</td><td>{{ "%.2f"|format(item.amount_cents / 100) }} {{ item.currency }}</td><td>{{ item.status }}</td></tr>{% endfor %}</tbody></table></div></section>

{% elif admin_section == "reports" %}
<section><h2>Expedientes de moderación y soporte</h2><form method="get" class="server-form"><label for="status-filter">Filtrar por estado</label><select id="status-filter" name="status"><option value="">Todos</option>{% for state in ['open','reviewing','actioned','dismissed','closed','appealed'] %}<option {% if status_filter == state %}selected{% endif %}>{{ state }}</option>{% endfor %}</select><button class="button" type="submit">Aplicar filtro</button></form>
<div class="server-table-wrap"><table class="server-table"><thead><tr><th>Expediente</th><th>Asunto</th><th>Reporta</th><th>Señalado</th><th>Estado</th><th>Prioridad</th><th>Responsable</th></tr></thead><tbody>{% for report in admin_reports %}<tr><td><a href="{{ url_for('admin_report_detail', report_id=report.id) }}">#{{ report.id }}</a></td><td>{{ report.subject }}</td><td>{{ report.reporter_username }}</td><td>{{ report.target_username or "—" }}</td><td>{{ report.status }}</td><td>{{ report.priority }}</td><td>{{ report.assigned_username or "Sin asignar" }}</td></tr>{% endfor %}</tbody></table></div></section>

{% elif admin_section == "report_detail" %}
<p><a href="{{ url_for('admin_reports') }}">Volver a reportes</a></p>
<section class="server-card"><p class="eyebrow">EXPEDIENTE #{{ report.id }}</p><h2>{{ report.subject }}</h2><dl class="definition-list"><dt>Reporta</dt><dd>{{ report.reporter_username }}</dd><dt>Señalado</dt><dd>{{ report.target_username or "Nadie" }}</dd><dt>Universo</dt><dd>{{ report.game_name or "General" }}</dd><dt>Categoría</dt><dd>{{ REPORT_CATEGORIES.get(report.category, report.category) }}</dd><dt>Descripción</dt><dd>{{ report.description }}</dd><dt>Evidencias</dt><dd>{{ report.evidence or "Sin referencias" }}</dd></dl>
<form method="post" class="admin-form"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input type="hidden" name="action" value="update"><label>Estado<select name="status">{% for state in ['open','reviewing','actioned','dismissed','closed','appealed'] %}<option {% if report.status == state %}selected{% endif %}>{{ state }}</option>{% endfor %}</select></label><label>Prioridad<select name="priority">{% for state in ['low','normal','high','urgent'] %}<option {% if report.priority == state %}selected{% endif %}>{{ state }}</option>{% endfor %}</select></label><label>Responsable<select name="assigned_account_id"><option value="0">Sin asignar</option>{% for item in staff %}<option value="{{ item.id }}" {% if report.assigned_account_id == item.id %}selected{% endif %}>{{ item.username }} — {{ ROLE_LABELS.get(item.role, item.role) }}</option>{% endfor %}</select></label><label>Código de resolución<input name="resolution_code" maxlength="80" value="{{ report.resolution_code }}"></label><label>Respuesta visible para el jugador<textarea name="public_response" maxlength="3000">{{ report.public_response }}</textarea></label><button class="button button-primary" type="submit">Actualizar expediente</button></form></section>
<section><h2>Mensajes del expediente</h2>{% for message in report_messages %}<article class="server-card"><h3>{{ message.username or "Sistema" }}{% if message.internal %} — nota interna{% endif %}</h3><p>{{ message.body }}</p><small>{{ message.created_at|date_label }}</small></article>{% endfor %}<form method="post" class="admin-form server-card"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input type="hidden" name="action" value="message"><label for="report-message">Mensaje</label><textarea id="report-message" name="body" maxlength="3000" required></textarea><label class="check-label"><input type="checkbox" name="internal" value="1"> Nota interna, oculta para el jugador</label><button class="button button-primary" type="submit">Añadir mensaje</button></form></section>

{% elif admin_section == "staff" %}
<section class="server-card"><h2>Asignar colaborador</h2><p>Los roles aportan permisos predeterminados. Los permisos marcados se añaden de forma explícita.</p><form method="post" class="admin-form"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><label>Cuenta<select name="account_id">{% for item in candidates %}<option value="{{ item.id }}">{{ item.username }} — {{ item.email }}</option>{% endfor %}</select></label><label>Rol<select name="role">{% for key, label in ROLE_LABELS.items() %}<option value="{{ key }}">{{ label }}</option>{% endfor %}</select></label><fieldset><legend>Permisos explícitos adicionales</legend>{% for key, label in PERMISSIONS.items() %}<label class="check-label"><input type="checkbox" name="permissions" value="{{ key }}"> {{ label }}</label>{% endfor %}</fieldset><label class="check-label"><input type="checkbox" name="active" value="1" checked> Acceso administrativo activo</label><button class="button button-primary" type="submit">Guardar colaborador</button></form></section>
<section><h2>Equipo actual</h2><div class="server-table-wrap"><table class="server-table"><thead><tr><th>Cuenta</th><th>Correo</th><th>Rol</th><th>Activo</th><th>Segundo factor</th><th>Permisos adicionales</th></tr></thead><tbody>{% for item in staff %}<tr><td>{{ item.username }}</td><td>{{ item.email }}</td><td>{{ ROLE_LABELS.get(item.role, item.role) }}</td><td>{{ "Sí" if item.active else "No" }}</td><td>{{ "Activo" if item.totp_enabled else "Pendiente" }}</td><td>{{ item.permissions_json }}</td></tr>{% endfor %}</tbody></table></div></section>

{% elif admin_section == "operations" %}
<section><h2>Estado operativo</h2><div class="metric-grid metric-grid-six"><article><span>Base de datos</span><strong>{{ operational_stats.database_bytes|number }} bytes</strong></article><article><span>Cuentas</span><strong>{{ operational_stats.accounts }}</strong></article><article><span>Activas en 5 minutos</span><strong>{{ operational_stats.active_5m }}</strong></article><article><span>Webhooks pendientes o fallidos</span><strong>{{ operational_stats.failed_webhooks }}</strong></article><article><span>Compras a revisar</span><strong>{{ operational_stats.review_purchases }}</strong></article><article><span>Reportes abiertos</span><strong>{{ operational_stats.open_reports }}</strong></article></div></section>
<div class="admin-columns"><section class="server-card"><h2>Mantenimiento global</h2><p>Los colaboradores conservan acceso al panel mientras los jugadores reciben un estado HTTP 503 y el mensaje indicado.</p><form method="post" class="admin-form"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input type="hidden" name="action" value="maintenance"><label class="check-label"><input type="checkbox" name="maintenance_mode" value="1" {% if site.maintenance_mode == '1' %}checked{% endif %}> Activar mantenimiento</label><label>Mensaje público<textarea name="maintenance_message" maxlength="2000" required>{{ site.maintenance_message }}</textarea></label><button class="button button-primary" type="submit">Guardar estado de mantenimiento</button></form></section><section class="server-card"><h2>Integridad y copias</h2><form method="post"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><button name="action" value="integrity" type="submit">Comprobar integridad ahora</button><button name="action" value="backup" type="submit">Crear copia verificada ahora</button></form><h3>Copias recientes</h3><ul>{% for backup in backups %}<li>{{ backup.name }} — {{ backup.size|number }} bytes — {{ backup.modified|date_label }}</li>{% else %}<li>No hay copias.</li>{% endfor %}</ul></section></div>
<section class="server-card"><h2>Exportaciones administrativas CSV</h2><p>Los archivos omiten contraseñas, secretos de segundo factor y credenciales de PayPal. Se neutralizan fórmulas para una apertura segura en hojas de cálculo.</p><nav class="server-actions" aria-label="Exportar datos administrativos"><a class="button" href="{{ url_for('admin_export', dataset='cuentas') }}">Exportar cuentas</a><a class="button" href="{{ url_for('admin_export', dataset='universos') }}">Exportar universos</a><a class="button" href="{{ url_for('admin_export', dataset='reportes') }}">Exportar reportes</a><a class="button" href="{{ url_for('admin_export', dataset='compras') }}">Exportar compras</a><a class="button" href="{{ url_for('admin_export', dataset='auditoria') }}">Exportar auditoría</a></nav></section>

{% elif admin_section == "settings" %}
<section class="server-card"><h2>Identidad, registro y textos públicos</h2><form method="post" class="admin-form"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<div class="admin-columns">
<label>Nombre público<input name="site_name" value="{{ site.site_name }}" required></label><label>URL pública<input name="public_url" type="url" value="{{ site.public_url }}"></label>
<label>Nombre del operador<input name="operator_name" value="{{ site.operator_name }}"></label><label>Correo del operador<input name="operator_email" type="email" value="{{ site.operator_email }}"></label>
<label>Correo de privacidad<input name="privacy_email" type="email" value="{{ site.privacy_email }}"></label><label>País y jurisdicción<input name="legal_country" value="{{ site.legal_country }}"></label>
<label>Registro<select name="registration_mode"><option value="open" {% if site.registration_mode == 'open' %}selected{% endif %}>Abierto</option><option value="approval" {% if site.registration_mode == 'approval' %}selected{% endif %}>Con aprobación</option><option value="closed" {% if site.registration_mode == 'closed' %}selected{% endif %}>Cerrado</option></select></label>
<label>Idioma predeterminado<select name="default_language">{% for code, language in LANGUAGES.items() %}<option value="{{ code }}" {% if site.default_language == code %}selected{% endif %}>{{ language.native_name }}</option>{% endfor %}</select></label>
<label>Verificación de correo<select name="require_email_verification"><option value="0" {% if site.require_email_verification != '1' %}selected{% endif %}>Opcional</option><option value="1" {% if site.require_email_verification == '1' %}selected{% endif %}>Obligatoria antes de acceder</option></select></label>
<label>Edad mínima<input name="minimum_age" type="number" min="13" max="99" value="{{ site.minimum_age }}"></label><label>Versión de condiciones<input name="terms_version" value="{{ site.terms_version }}"></label><label>Versión de privacidad<input name="privacy_version" value="{{ site.privacy_version }}"></label><label>Versión de condiciones de compra<input name="purchase_terms_version" value="{{ site.purchase_terms_version }}"></label>
<label>Días de expedientes<input name="report_retention_days" type="number" min="30" max="3650" value="{{ site.report_retention_days }}"></label><label>Días de acciones<input name="action_log_retention_days" type="number" min="7" max="730" value="{{ site.action_log_retention_days }}"></label>
</div><label>Aviso de tienda<textarea name="store_notice">{{ site.store_notice }}</textarea></label>
<fieldset><legend>Publicar también un aviso</legend><label>Título<input name="announcement_title" maxlength="120"></label><label>Texto<textarea name="announcement_body" maxlength="3000"></textarea></label><label>Severidad<select name="announcement_severity"><option value="info">Información</option><option value="success">Éxito</option><option value="warning">Advertencia</option><option value="critical">Crítica</option></select></label></fieldset>
<button class="button button-primary" type="submit">Guardar configuración</button></form></section>
<section><h2>Avisos publicados</h2>{% for item in announcements %}<article class="server-card"><h3>{{ item.title }}</h3><p>{{ item.body }}</p><small>{{ item.severity }} — {{ item.created_at|date_label }} — {{ "activo" if item.active else "inactivo" }}</small><form method="post" action="{{ url_for('admin_announcement_action', announcement_id=item.id) }}" class="server-actions"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><button name="action" value="toggle" type="submit">{{ "Desactivar" if item.active else "Activar" }} aviso</button><button name="action" value="delete" type="submit">Eliminar aviso</button></form></article>{% else %}<p>No hay avisos.</p>{% endfor %}</section>

{% elif admin_section == "commerce" %}
<section class="server-card"><h2>Configuración de PayPal</h2><p>El secreto se cifra con la clave de pagos del servidor y nunca vuelve a mostrarse. Configurado: {{ "sí" if payment.secret_configured else "no" }}.</p><form method="post" class="admin-form"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input type="hidden" name="action" value="paypal"><label class="check-label"><input type="checkbox" name="enabled" value="1" {% if payment.enabled %}checked{% endif %}> Habilitar pagos</label><label>Entorno<select name="environment"><option value="sandbox" {% if payment.environment == 'sandbox' %}selected{% endif %}>Sandbox de pruebas</option><option value="live" {% if payment.environment == 'live' %}selected{% endif %}>Producción real</option></select></label><label>Client ID<input name="client_id" value="{{ payment.client_id }}" autocomplete="off"></label><label>Client Secret<input name="client_secret" type="password" autocomplete="new-password" aria-describedby="secret-help"><small id="secret-help">Déjalo vacío para conservar el secreto actual.</small></label><label>Webhook ID<input name="webhook_id" value="{{ payment.webhook_id }}"></label><label>Moneda ISO<input name="currency" maxlength="3" value="{{ payment.currency }}"></label><label>Texto del extracto<input name="statement_text" maxlength="22" value="{{ payment.statement_text }}"></label><button class="button button-primary" type="submit">Guardar PayPal</button></form><div class="server-actions"><form method="post"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><button name="action" value="paypal_test" type="submit">Probar credenciales con PayPal</button></form><form method="post"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><button name="action" value="paypal_disconnect" class="button-danger" type="submit">Desconectar y borrar credenciales</button></form></div></section>
<section class="server-card"><h2>Crear producto</h2>
{% set product = none %}{% include "online/_product_form.html" %}
</section>
<section><h2>Productos</h2>{% for product in products %}<details class="server-card"><summary>{{ product.sku }} — {{ product.name }} — {{ "%.2f"|format(product.price_cents / 100) }} {{ product.currency }} — {% if product.archived_at %}archivado{% elif product.active %}activo{% else %}inactivo{% endif %}</summary>{% include "online/_product_form.html" %}<form method="post" action="{{ url_for('admin_product_action', product_id=product.id) }}" class="server-actions"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}">{% if product.archived_at %}<button name="action" value="restore" type="submit">Restaurar producto</button>{% else %}<button name="action" value="archive" type="submit">Archivar producto</button>{% endif %}<button name="action" value="duplicate" type="submit">Duplicar producto</button><button name="action" value="delete" class="button-danger" type="submit">Eliminar si nunca se compró</button></form></details>{% endfor %}</section>
<section><h2>Pedidos recientes</h2><div class="server-table-wrap"><table class="server-table"><thead><tr><th>Pedido</th><th>Jugador</th><th>Producto y destino</th><th>Importe</th><th>Estado</th><th>Acciones</th></tr></thead><tbody>{% for item in purchases %}<tr><td>#{{ item.id }}</td><td><a href="{{ url_for('admin_player_detail', account_id=item.account_id) }}">{{ item.username }}</a></td><td>{{ item.product_name }}<br>{% if item.planet_id %}Planeta #{{ item.planet_id }} {{ item.target_planet_name or "no disponible" }}{% else %}Imperio #{{ item.empire_id }}{% endif %}</td><td>{{ "%.2f"|format(item.amount_cents / 100) }} {{ item.currency }}</td><td>{{ item.status }}{% if item.error_message %}<br>{{ item.error_message }}{% endif %}</td><td><form method="post" action="{{ url_for('admin_purchase_action', purchase_id=item.id) }}" class="admin-form"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><label>Nuevo ID de planeta, solo para entregas planetarias<input name="planet_id" type="number" min="1" value="{{ item.planet_id or '' }}"></label><button name="action" value="retarget" type="submit">Cambiar destino</button><button name="action" value="fulfill" type="submit">Reintentar entrega</button><button name="action" value="cancel" type="submit">Cancelar sin capturar</button><button name="action" value="refund" type="submit">Reembolsar en PayPal</button></form></td></tr>{% endfor %}</tbody></table></div></section>
<section><h2>Webhooks de PayPal</h2><p>Historial de recepción, verificación y procesamiento para investigar entregas, reembolsos y eventos fallidos.</p><div class="server-table-wrap"><table class="server-table"><thead><tr><th>Evento</th><th>Tipo</th><th>Recibido</th><th>Verificado</th><th>Procesado</th><th>Error</th></tr></thead><tbody>{% for item in webhooks %}<tr><td>{{ item.event_id }}</td><td>{{ item.event_type }}</td><td>{{ item.received_at|date_label }}</td><td>{{ "Sí" if item.verified else "No" }}</td><td>{{ "Sí" if item.processed else "No" }}</td><td>{{ item.error_message or "—" }}</td></tr>{% else %}<tr><td colspan="6">Todavía no se han recibido webhooks.</td></tr>{% endfor %}</tbody></table></div></section>

{% elif admin_section == "privacy" %}
<section><h2>Solicitudes de privacidad</h2>{% for item in privacy_requests %}<article class="server-card"><h3>#{{ item.id }} — {{ item.username }} — {{ PRIVACY_REQUEST_TYPES.get(item.request_type, item.request_type) }}</h3><p>{{ item.details or "Sin detalles adicionales." }}</p><form method="post" action="{{ url_for('admin_privacy_action', privacy_id=item.id) }}" class="admin-form"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><label>Estado<select name="status">{% for state in ['open','verifying','completed','rejected','cancelled'] %}<option {% if item.status == state %}selected{% endif %}>{{ state }}</option>{% endfor %}</select></label><label>Respuesta<textarea name="response" maxlength="3000">{{ item.response }}</textarea></label><button class="button button-primary" type="submit">Actualizar solicitud</button></form></article>{% else %}<p>No hay solicitudes.</p>{% endfor %}</section>

{% elif admin_section == "audit" %}
<section><h2>Registro administrativo</h2><p>Últimas mil acciones coincidentes. Los registros identifican quién hizo qué, sobre qué objeto, cuándo y en qué universo. La exportación completa está en Operaciones.</p><form method="get" class="server-form"><label>Buscar por responsable, acción, objeto o resumen<input name="q" value="{{ audit_query }}"></label><button type="submit">Buscar</button></form><div class="server-table-wrap"><table class="server-table"><thead><tr><th>Fecha</th><th>Responsable</th><th>Acción</th><th>Objeto</th><th>Universo</th><th>Resumen</th></tr></thead><tbody>{% for item in audit_logs %}<tr><td>{{ item.created_at|date_label }}</td><td>{{ item.username or "Sistema" }}</td><td>{{ item.action }}</td><td>{{ item.object_type }} {{ item.object_id }}</td><td>{{ item.game_id or "—" }}</td><td>{{ item.summary }}</td></tr>{% endfor %}</tbody></table></div></section>
{% endif %}
{% endblock %}
