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

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

// Crear tabla si no existe
$codesDB->exec('CREATE TABLE IF NOT EXISTS activation_codes (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    mac_address TEXT,
    username TEXT,
    password TEXT,
    dns TEXT,
    title TEXT,
    expire_date TEXT,
    code TEXT UNIQUE,
    used INTEGER DEFAULT 0,
    created_at TEXT
)');

// Inicializar variables para el modal
$codigoGenerado = null;
$macGenerada = null;
$mostrarModal = false;

// Función para generar código
function generarCodigo() {
    return strtoupper(bin2hex(random_bytes(6)));
}

// Insertar código
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['generate'])) {
    $mac = strtoupper(trim($_POST['mac_address']));
    $username = trim($_POST['username']);
    $password = trim($_POST['password']);
    $dns = trim($_POST['dns']);
    $title = trim($_POST['title']);
    $expire_date = trim($_POST['expire_date']);
    $created_at = date('Y-m-d\TH:i:s');
    $code = generarCodigo();

    $stmt = $codesDB->prepare("INSERT INTO activation_codes 
        (mac_address, username, password, dns, title, expire_date, code, created_at) 
        VALUES (:mac, :username, :password, :dns, :title, :expire_date, :code, :created_at)");

    $stmt->bindValue(':mac', $mac);
    $stmt->bindValue(':username', $username);
    $stmt->bindValue(':password', $password);
    $stmt->bindValue(':dns', $dns);
    $stmt->bindValue(':title', $title);
    $stmt->bindValue(':expire_date', $expire_date);
    $stmt->bindValue(':code', $code);
    $stmt->bindValue(':created_at', $created_at);
    $stmt->execute();

    // Guardar datos para el modal
    $codigoGenerado = $code;
    $macGenerada = $mac;
    $mostrarModal = true;

// Obtener URL completa automáticamente hacia activar.php
$protocolo = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://";
$host = $_SERVER['HTTP_HOST'];
$path = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/\\');
$urlActivar = $protocolo . $host . $path . '/activar.php';

// Construir texto de WhatsApp
$mensajeWhatsApp = urlencode("🎉 ¡Código de activación generado! 🎯\n\n🔐 *Código:* $codigoGenerado\n🖥️ *MAC:* $macGenerada\n\n✅ Ve a la página de activación para activar tu dispositivo:\n$urlActivar");

}

// Obtener opciones DNS
$dnsOptions = [];
$result = $mainDB->query("SELECT * FROM dns");
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
    $dnsOptions[] = $row;
}
// Cierre conexión
$mainDB->close();
include 'includes/header.php';
?>
<div class="container-fluid">
<div class="mx-auto" style="max-width: 900px;">
    <h1 class="title-outside-card mb-1 text-center" style="white-space: nowrap;">🎯 Generar Códigos</h1>
    <div class="card border-left-primary shadow h-100 card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-color"><i class="fas fa-user"></i>Detalles</h6>
        </div>

    <?php if ($mostrarModal && $codigoGenerado && $macGenerada): ?>
<!-- Modal -->
<div class="modal fade" id="codigoModal" tabindex="-1" role="dialog" aria-labelledby="codigoModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content border-success">
      <div class="modal-header bg-success text-white">
        <h5 class="modal-title" id="codigoModalLabel">✅ ¡Código generado con éxito!</h5>
        <button type="button" class="close text-white" data-dismiss="modal" aria-label="Cerrar">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body text-center">
        <p>🔑 <strong>Código:</strong> <span id="codigoGenerado"><?= htmlspecialchars($codigoGenerado) ?></span></p>
        <p>🖥️ <strong>MAC:</strong> <?= htmlspecialchars($macGenerada) ?></p>
        <div class="d-flex justify-content-center flex-wrap mt-3">
          <button class="btn btn-outline-primary m-1" onclick="copiarCodigo()">📋 Copiar código</button>
          <a class="btn btn-success m-1" target="_blank" href="https://wa.me/?text=<?= $mensajeWhatsApp ?>">📲 Compartir por WhatsApp</a>
          <a class="btn btn-info m-1" href="<?= $urlActivar ?>">🚀 Activar cliente</a>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
// Mostrar automáticamente el modal
document.addEventListener("DOMContentLoaded", function() {
    $('#codigoModal').modal('show');
});

// Función para copiar el código
function copiarCodigo() {
    const codigo = document.getElementById("codigoGenerado").innerText;
    navigator.clipboard.writeText(codigo).then(() => {
        alert("✅ Código copiado al portapapeles.");
    });
}
</script>
<?php endif; ?>
<div class="card-body">
            <form method="post">
        <input type="hidden" name="generate" value="1">
        <div class="form-group">
            <label>Mac Address</label>
            <input type="text" name="mac_address" class="form-control mac-input" required>
        </div>
        <div class="form-group">
            <label>Usuario</label>
            <input type="text" name="username" class="form-control" required>
        </div>
        <div class="form-group">
            <label>Contraseña</label>
            <input type="text" name="password" class="form-control" required>
        </div>
        <div class="form-group">
            <label>DNS</label>
            <select name="dns" class="form-control" required>
                <option value="">Seleccionar DNS</option>
                <?php foreach ($dnsOptions as $dns): ?>
                    <option value="<?= htmlspecialchars($dns['url']) ?>"><?= htmlspecialchars($dns['url']) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="form-group">
            <label>Nombre del Servidor o del Cliente</label>
            <input type="text" name="title" class="form-control" required>
        </div>
        <div class="form-group">
            <label>Fecha de Expiración</label>
            <input type="date" name="expire_date" class="form-control" required>
        </div>
        <button type="submit" class="btn btn-primary btn-block">Generar código</button>
    </form>
</div>

<script>
document.addEventListener("DOMContentLoaded", function() {
    const macInput = document.querySelector('.mac-input');

    if (macInput) {
        macInput.addEventListener("input", function(e) {
            let value = e.target.value.replace(/[^a-fA-F0-9]/g, "").toUpperCase();
            let formatted = "";
            for (let i = 0; i < value.length; i++) {
                formatted += value[i];
                if ((i + 1) % 2 === 0 && i < value.length - 1) {
                    formatted += ":";
                }
            }
            e.target.value = formatted;
        });
    }
});
</script>

<?php include 'includes/footer.php'; ?>


