<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

// Base de datos
$codesDB = new SQLite3('./api/codes_rgvip.db');

// Eliminar código individual
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    $stmt = $codesDB->prepare("DELETE FROM activation_codes WHERE id = :id");
    $stmt->bindValue(':id', $id, SQLITE3_INTEGER);
    $stmt->execute();
    header("Location: gestionar_codigos.php");
    exit;
}

// Eliminar todos los códigos usados
if (isset($_GET['delete_used'])) {
    $stmt = $codesDB->prepare("DELETE FROM activation_codes WHERE used = 1");
    $stmt->execute();
    header("Location: gestionar_codigos.php");
    exit;
}

// Obtener códigos
$result = $codesDB->query("SELECT * FROM activation_codes ORDER BY id DESC");
$codigos = [];
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
    $codigos[] = $row;
}

include 'includes/header.php';
?>
<style>
/* Estilos para tablas con texto blanco */
.table {
    color: #fff !important; /* Texto blanco forzado */
}

.table td, 
.table th {
    border-color: #495057 !important; /* Bordes visibles */
}

/* Estilo para filas y hover */
.table tbody tr {
    background-color: rgba(0, 0, 0, 0.3) !important;
}

.table-hover tbody tr:hover {
    background-color: rgba(0, 0, 0, 0.5) !important;
}

/* Estilos específicos para elementos internos */
.code-text {
    color: #fff !important;
    margin-right: 10px;
}

/* Botones dentro de la tabla */
.btn-outline-secondary {
    color: #fff !important;
    border-color: #6c757d !important;
}

.btn-outline-secondary:hover {
    background-color: #6c757d !important;
    color: #000 !important;
}
</style>
    <h1 class="title-outside-card mb-1 text-center" style="white-space: nowrap;">📋 Códigos Generados</h1>
<div class="col-md-8 mx-auto">
    <div class="mx-auto" style="max-width: 900px;">
        <div class="card border-left-primary shadow h-100 card shadow mb-4">
        <div class="card bg-dark text-white">
           <div class="card-header py-3">
    <div class="row g-2">
      <div class="col-12 col-md-auto mb-2 mb-md-0">
        <a href="generar_codigo.php" class="btn btn-primary w-100">
          ➕ Generar Nuevo Código
        </a>
      </div>
      <div class="col-12 col-md-auto mb-2 mb-md-0">
        <a href="?delete_used=1" class="btn btn-danger w-100" onclick="return confirm('¿Seguro que deseas eliminar todos los códigos usados?')">
          🗑️ Eliminar Todos los Usados
        </a>
      </div>
      <div class="col-12 col-md-auto mb-2 mb-md-0">
        <a href="activar.php" class="btn btn-success w-100">
          ⚙️ Activar Usuario
        </a>
      </div>
    </div>
  </div>
  <div class="card-body">
    <div class="table-responsive" style="max-width: 1000px; margin: 0 auto;">
      <table class="table table-bordered table-sm table-hover">
        <thead class="thead-dark">
          <tr>
            <th>Nombre</th>
            <th>MAC</th>
            <th>Usuario</th>
            <th>Código</th>
            <th>Estado</th>
            <th>Acciones</th>
          </tr>
        </thead>
            <tbody>
                <?php foreach ($codigos as $row): ?>
                    <tr>
                        <td><?= htmlspecialchars($row['cliente_nombre']) ?></td>
                        <td><?= htmlspecialchars($row['mac_address']) ?></td>
                        <td><?= htmlspecialchars($row['username']) ?></td>
                        <td>
                            <span class="code-text"><?= $row['code'] ?></span>
                            <button class="btn btn-outline-secondary btn-sm copy-btn" data-code="<?= $row['code'] ?>" title="Copiar código">
                                📋 Copiar
                            </button>
                        </td>
                        <td><?= $row['used'] ? '✅ Usado' : '⏳ No usado'; ?></td>
                        <td>
                            <a href="?delete=<?= $row['id'] ?>" class="btn btn-outline-danger btn-sm" title="Eliminar">
                                🗑️ Eliminar
                            </a>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- ✅ Script para copiar el código -->
<script>
document.addEventListener("DOMContentLoaded", function () {
    document.querySelectorAll('.copy-btn').forEach(function (btn) {
        btn.addEventListener('click', function () {
            const code = this.dataset.code;
            navigator.clipboard.writeText(code).then(() => {
                this.textContent = "✅ Copiado";
                setTimeout(() => {
                    this.textContent = "📋 Copiar";
                }, 1500);
            }).catch(() => {
                alert("No se pudo copiar el código.");
            });
        });
    });
});
</script>

<?php
$codesDB->close();
include 'includes/footer.php';
?>
