<?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;">Generate Code</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>Details</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">Code generated successfully!</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>Code:</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()">馃搵 Copy Code</button>
          <a class="btn btn-success m-1" target="_blank" href="https://wa.me/?text=<?= $mensajeWhatsApp ?>">馃摬 Share in WhatsApp</a>
          <a class="btn btn-info m-1" href="<?= $urlActivar ?>">馃殌 Activate client</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>User</label>
            <input type="text" name="username" class="form-control" required>
        </div>
        <div class="form-group">
            <label>Password</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="">Select 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>Server/ Client Name</label>
            <input type="text" name="title" class="form-control" required>
        </div>
        <div class="form-group">
            <label>Expiration Date</label>
            <input type="date" name="expire_date" class="form-control" required>
        </div>
        <button type="submit" class="btn btn-primary btn-block">Generate Code</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'; ?>


