<?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
)');

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

// Verificar si es POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');

    try {
        $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();

        if (!$mac || !$username || !$password || !$dns || !$title || !$expire_date) {
            throw new Exception("Todos los campos son obligatorios.");
        }

        $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();

        // URL para activar
        $protocolo = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://";
        $host = $_SERVER['HTTP_HOST'];
        $path = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/\\');
        $activar_url = $protocolo . $host . dirname($path) . '/activar.php';

        // Mensaje para WhatsApp
        $mensaje = "🎉 ¡Código de activación generado! 🎯\n\n🔐 *Código:* $code\n🖥️ *MAC:* $mac\n\n✅ Ve a la página de activación:\n$activar_url";

        echo json_encode([
            'success' => true,
            'codigo' => $code,
            'mac' => $mac,
            'mensaje' => $mensaje,
            'activar_url' => $activar_url
        ]);
    } catch (Exception $e) {
        echo json_encode([
            'success' => false,
            'error' => $e->getMessage()
        ]);
    }

    exit;
}
// Obtener opciones DNS desde la base de datos
$dnsOptions = [];
$result = $mainDB->query("SELECT * FROM dns");
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
    $dnsOptions[] = $row['url'];
}
$mainDB->close();




