<?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';
?>
    <h1 class="title-outside-card mb-1 text-center" style="white-space: nowrap;">📋 Generated Codes</h1>
<div class="container-fluid">
    <div class="mx-auto" style="max-width: 900px;">
        <div class="card border-left-primary shadow h-100 card shadow mb-4">
           <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">
          ➕ Generate New Code
        </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('Do you really want to delete all used codes?')">
          🗑️ Delete All Users
        </a>
      </div>
      <div class="col-12 col-md-auto mb-2 mb-md-0">
        <a href="activar.php" class="btn btn-success w-100">
          ⚙️ Activate User
        </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>Name</th>
            <th>MAC</th>
            <th>User</th>
            <th>Code</th>
            <th>Status</th>
            <th>Actions</th>
          </tr>
        </thead>
            <tbody>
                <?php foreach ($codigos as $row): ?>
                    <tr>
                        <td><?= htmlspecialchars($row['title']) ?></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">
                                📋 Copy
                            </button>
                        </td>
                        <td><?= $row['used'] ? '✅ Used' : '⏳ No used'; ?></td>
                        <td>
                            <a href="?delete=<?= $row['id'] ?>" class="btn btn-outline-danger btn-sm" title="Eliminar">
                                🗑️ Delete
                            </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 = "✅ Copied";
                setTimeout(() => {
                    this.textContent = "📋 Copy";
                }, 1500);
            }).catch(() => {
                alert("The code could not be copied.");
            });
        });
    });
});
</script>

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