<?php
/**
 * 轻量插件钩子：plugins/<slug>/plugin.php
 * 插件内可调用 plugin_register('home_bottom', function(){ echo '...'; });
 */

$GLOBALS['PLUGIN_HOOKS'] = [];

function plugin_register($hook, $callback)
{
    if (!isset($GLOBALS['PLUGIN_HOOKS'][$hook])) {
        $GLOBALS['PLUGIN_HOOKS'][$hook] = [];
    }
    $GLOBALS['PLUGIN_HOOKS'][$hook][] = $callback;
}

function plugin_call($hook, array $args = [])
{
    foreach ($GLOBALS['PLUGIN_HOOKS'][$hook] ?? [] as $cb) {
        try {
            $result = call_user_func($cb, $args);
            if ($result !== null) {
                return $result;
            }
        } catch (Throwable $e) {
            // 插件异常不阻断主流程
        }
    }
    return null;
}

function plugin_hook($hook, array $args = [])
{
    ob_start();
    foreach ($GLOBALS['PLUGIN_HOOKS'][$hook] ?? [] as $cb) {
        try {
            call_user_func($cb, $args);
        } catch (Exception $e) {
            echo '<!-- plugin error: ' . e($e->getMessage()) . ' -->';
        }
    }
    return ob_get_clean();
}

/** 内容提交前的统一广告/违规检测入口；命中返回 block 结果，未命中返回 null。 */
function plugin_content_check($context, $content, array $extra = [])
{
    $result = plugin_call('content_filter', [
        'context' => (string) $context,
        'content' => (string) $content,
        'user' => current_user(),
        'extra' => $extra,
    ]);
    if (is_array($result) && !empty($result['blocked'])) {
        return [
            'blocked' => true,
            'message' => (string) ($result['message'] ?? '内容已被插件拦截'),
            'keyword' => (string) ($result['keyword'] ?? ''),
            'context' => (string) $context,
        ];
    }
    return null;
}

function plugin_render_settings($slug)
{
    return plugin_hook('plugin_settings', ['slug' => (string) $slug]);
}

function plugin_dispatch_action($slug, $action, array $payload = [])
{
    $result = plugin_call('plugin_action', [
        'slug' => (string) $slug,
        'action' => (string) $action,
        'payload' => $payload,
    ]);
    return is_array($result) ? $result : null;
}

/** 首次升级时登记内置插件；用户主动卸载后不再自动重建。 */
/**
 * 普通管理员的插件中心权限：all=可见可上传，view=可见不能上传，hidden=不可见。
 * 超级管理员始终为 all。
 */
function plugin_access_mode($user)
{
    if (!$user || !is_admin($user) || is_superadmin($user)) {
        return 'all';
    }
    $mode = (string) ($user['plugin_access'] ?? 'all');
    return in_array($mode, ['all', 'view', 'hidden'], true) ? $mode : 'all';
}

function plugin_access_can_view($user)
{
    return plugin_access_mode($user) !== 'hidden';
}

function plugin_access_can_upload($user)
{
    return plugin_access_mode($user) === 'all';
}

function plugins_register_builtin()
{
    // 广告杀手已移除：清掉旧启用记录，并永久停止自动登记。
    if (setting('ad_killer_removed', '') !== '1') {
        try {
            DB::run('DELETE FROM ' . DB::table('plugins') . ' WHERE slug = ?', ['ad-killer']);
            set_setting('ad_killer_removed', '1');
        } catch (Throwable $e) {
            // 插件表尚未就绪时忽略
        }
    }
}

function plugins_boot()
{
    static $loaded = false;
    if ($loaded) {
        return;
    }
    $loaded = true;
    plugins_register_builtin();
    try {
        $rows = DB::all('SELECT * FROM ' . DB::table('plugins') . ' WHERE status = 1');
    } catch (Exception $e) {
        return;
    }
    foreach ($rows as $p) {
        $slug = preg_replace('/[^a-z0-9\-_]/', '', strtolower($p['slug']));
        if ($slug === '') {
            continue;
        }
        if ($slug === 'ad-killer') {
            continue;
        }
        $candidates = [
            APP_ROOT . '/plugins/' . $slug . '/plugin.php',
            APP_ROOT . '/storage/plugins/' . $slug . '/plugin.php',
        ];
        foreach ($candidates as $file) {
            if (is_file($file)) {
                include_once $file;
                break;
            }
        }
    }
}
