<?php
// includes/addon_loader.php
require_once __DIR__ . '/../config/db.php';

/**
 * --- TRUCO DE SALIDA (Output Buffering) ---
 * Reemplaza {user:ID} por el Nombre + Medallas en toda la web.
 */
ob_start(function($buffer) use ($pdo) {
    return preg_replace_callback('/\{user:(\d+)\}/', function($matches) use ($pdo) {
        $userId = $matches[1];
        
        $stmt = $pdo->prepare("SELECT username FROM users WHERE id = ? LIMIT 1");
        $stmt->execute([$userId]);
        $user = $stmt->fetch();
        
        if (!$user) return "Usuario #$userId";

        $badges = "";
        if (function_exists('get_user_badges')) {
            $badges = get_user_badges($userId, $pdo);
        }
        
        return htmlspecialchars($user['username']) . ' ' . $badges;
    }, $buffer);
});

/**
 * --- CARGA DINÁMICA DE ADDONS ---
 */
$current_page = basename($_SERVER['PHP_SELF']);
$editing_addon = isset($_GET['name']) ? $_GET['name'] : '';

try {
    $stmt = $pdo->query("SELECT folder_name FROM addons WHERE status = 'active'");
    $active_addons = $stmt->fetchAll(PDO::FETCH_COLUMN);

    if ($active_addons) {
        foreach ($active_addons as $addon) {
            
            // Regla de seguridad: No cargar el addon si lo estamos configurando
            if ($current_page === 'addon_settings.php' && $editing_addon === $addon) {
                continue; 
            }

            // Regla de seguridad: No bloquear el panel de administración
            if ($current_page === 'addons.php' && strpos($addon, 'maintenance') !== false) {
                continue;
            }

            $addon_path = __DIR__ . "/../addons/$addon/main.php";
            if (file_exists($addon_path)) {
                include_once $addon_path;
            }
        }
    }
} catch (PDOException $e) { }

/**
 * Función global para chequear estado de addons
 */
function is_addon_active($folder_name, $pdo) {
    $check = $pdo->prepare("SELECT status FROM addons WHERE folder_name = ? LIMIT 1");
    $check->execute([$folder_name]);
    $res = $check->fetch();
    return ($res && $res['status'] === 'active');
}