<?php
// Configuración robusta
set_time_limit(30);
ini_set('memory_limit', '128M');
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Función optimizada para conexión a SQLite
function connectSQLite($path) {
    $max_retries = 5;
    $retry_delay = 200000;

    $lock_files = ['.db.db-shm', '.db.db-wal', 'codes_rgvip.db-shm', 'codes_rgvip.db-wal'];
    foreach ($lock_files as $file) {
        if (file_exists('./' . $file) && is_writable('./' . $file)) {
            @unlink('./' . $file);
        }
    }

    for ($i = 0; $i < $max_retries; $i++) {
        try {
            $db = new SQLite3($path);
            $db->enableExceptions(true);
            $db->busyTimeout(30000);
            $db->exec("PRAGMA journal_mode = WAL");
            $db->exec("PRAGMA synchronous = NORMAL");
            $db->exec("PRAGMA temp_store = MEMORY");
            return $db;
        } catch (Exception $e) {
            if (strpos($e->getMessage(), 'locked') !== false && $i < ($max_retries - 1)) {
                usleep($retry_delay * ($i + 1));
                continue;
            }
            error_log("Error de conexión SQLite: " . $e->getMessage());
            return false;
        }
    }
}

$db = connectSQLite('./.db.db');
$codesDB = connectSQLite('./codes_rgvip.db');

if ($codesDB) {
    $codesDB->exec("CREATE TABLE IF NOT EXISTS activation_codes (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        code TEXT UNIQUE,
        mac_address TEXT,
        username TEXT,
        password TEXT,
        dns TEXT,
        title TEXT,
        expire_date TEXT,
        used INTEGER DEFAULT 0,
        created_at TEXT
    )");
}

$readonly_mode = !$db || !$codesDB;

if ($readonly_mode) {
    echo '<div class="alert alert-warning">⚠️ El sistema está en modo solo lectura. Intente más tarde.</div>';
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['code'])) {
    $code = trim($_POST['code']);

    if (empty($code)) {
        echo '<div class="alert alert-danger">❌ Por favor ingrese un código válido.</div>';
        exit;
    }

    try {
        $stmt = $codesDB->prepare("SELECT * FROM activation_codes WHERE code = :code AND used = 0 LIMIT 1");
        $stmt->bindValue(':code', $code, SQLITE3_TEXT);
        $result = $stmt->execute();
        $data = $result->fetchArray(SQLITE3_ASSOC);
        $stmt->close();

        if ($data) {
            $query = sprintf(
                "INSERT INTO ibo (mac_address, username, password, expire_date, url, title, created_at) 
                 VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s')",
                SQLite3::escapeString(strtoupper($data['mac_address'])),
                SQLite3::escapeString($data['username']),
                SQLite3::escapeString($data['password']),
                SQLite3::escapeString($data['expire_date']),
                SQLite3::escapeString($data['dns']),
                SQLite3::escapeString($data['title']),
                SQLite3::escapeString(date('Y-m-d H:i:s'))
            );

            if ($db->exec($query)) {
                $codesDB->exec("UPDATE activation_codes SET used = 1 WHERE code = '" . SQLite3::escapeString($code) . "'");
                // ✅ También insertar en la tabla subscription
    $subscriptionInsert = sprintf(
        "INSERT INTO subscription (mac_address, expire_date) 
         VALUES ('%s', '%s')",
        SQLite3::escapeString(strtoupper($data['mac_address'])),
        SQLite3::escapeString($data['expire_date'])
    );
    $db->exec($subscriptionInsert);
                echo '<div class="alert alert-success">✅ Activación exitosa para MAC: ' . htmlspecialchars($data['mac_address']) . '</div>';
            } else {
                echo '<div class="alert alert-danger">❌ Error al guardar en la base de datos.</div>';
            }
        } else {
            echo '<div class="alert alert-danger">❌ Código inválido o ya utilizado.</div>';
        }
    } catch (Exception $e) {
        echo '<div class="alert alert-danger">❌ Error: ' . htmlspecialchars($e->getMessage()) . '</div>';
    }
} else {
    echo '<div class="alert alert-danger">❌ Solicitud inválida.</div>';
}
?>
