<?php
/**
 * 插件商城：本地插件仓库、上传、下载并自动启用
 * 与后台「插件中心」共用 storage/plugins 与 plugins 表。
 */

function plugin_mall_root()
{
    return APP_ROOT . '/storage/plugin_mall';
}

function plugin_mall_packages_dir()
{
    return plugin_mall_root() . '/packages';
}

function plugin_mall_catalog_file()
{
    return plugin_mall_root() . '/catalog.json';
}

function plugin_mall_builtin_items()
{
    return [
        [
            'slug' => 'ad-killer',
            'name' => '广告杀手',
            'version' => '1.0.0',
            'description' => '命中广告关键词自动驳回，并按违规次数自动禁言或封禁；管理员与超级管理员免检。内置插件，购买价格为 0 积分。',
            'price' => 0,
            'builtin' => true,
            'file' => '',
            'size' => 0,
            'uploaded_at' => '内置插件',
        ],
    ];
}

function plugin_mall_catalog()
{
    $raw = @file_get_contents(plugin_mall_catalog_file());
    $list = json_decode((string) $raw, true);
    if (!is_array($list)) {
        $list = [];
    }
    $out = [];
    foreach ($list as $item) {
        if (!is_array($item) || empty($item['slug'])) {
            continue;
        }
        if (empty($item['file']) && empty($item['builtin'])) {
            continue;
        }
        $item['price'] = max(0, (int) ($item['price'] ?? 0));
        $item['price'] = min(999999, $item['price']);
        $out[] = $item;
    }
    $slugs = [];
    foreach ($out as $item) {
        $slugs[(string) $item['slug']] = true;
    }
    foreach (plugin_mall_builtin_items() as $builtin) {
        if (!isset($slugs[(string) $builtin['slug']])) {
            array_unshift($out, $builtin);
        }
    }
    return $out;
}

function plugin_mall_catalog_save(array $items)
{
    $dir = plugin_mall_root();
    if (!is_dir($dir) && !@mkdir($dir, 0775, true) && !is_dir($dir)) {
        throw new Exception('无法创建插件商城目录');
    }
    $json = json_encode(array_values($items), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    if (@file_put_contents(plugin_mall_catalog_file(), $json, LOCK_EX) === false) {
        throw new Exception('无法写入插件商城清单');
    }
}

function plugin_mall_find($slug)
{
    $slug = plugin_slugify($slug);
    foreach (plugin_mall_catalog() as $item) {
        if ((string) $item['slug'] === $slug) {
            return $item;
        }
    }
    return null;
}

function plugin_mall_upsert(array $entry)
{
    $items = plugin_mall_catalog();
    $found = false;
    foreach ($items as $i => $item) {
        if ((string) $item['slug'] === (string) $entry['slug']) {
            $items[$i] = $entry;
            $found = true;
            break;
        }
    }
    if (!$found) {
        array_unshift($items, $entry);
    }
    plugin_mall_catalog_save($items);
}

function plugin_mall_package_path(array $item)
{
    $file = (string) ($item['file'] ?? '');
    if ($file === '' || strpos($file, '..') !== false || strpos($file, '/') !== false) {
        return '';
    }
    $path = plugin_mall_packages_dir() . '/' . $file;
    $real = realpath($path);
    if ($real === false || strpos($real, realpath(plugin_mall_packages_dir())) !== 0 || !is_file($real)) {
        return '';
    }
    return $real;
}

function plugin_mall_add_package($tmpFile, array $manifest, $ext, $originalName, $price = 0)
{
    $dir = plugin_mall_packages_dir();
    if (!is_dir($dir) && !@mkdir($dir, 0775, true) && !is_dir($dir)) {
        throw new Exception('无法创建插件商城包目录');
    }
    $ext = strtolower($ext) === 'json' ? 'json' : 'zip';
    $filename = $manifest['slug'] . '-' . preg_replace('/[^0-9A-Za-z._-]/', '-', $manifest['version']) . '.' . $ext;
    $dest = $dir . '/' . $filename;
    if (!@copy($tmpFile, $dest)) {
        throw new Exception('插件包写入商城失败');
    }
    @chmod($dest, 0644);
    $size = (int) @filesize($dest);
    $sha = (string) @hash_file('sha256', $dest);
    $entry = [
        'slug' => $manifest['slug'],
        'name' => $manifest['name'],
        'version' => $manifest['version'],
        'description' => $manifest['description'],
        'hook' => $manifest['hook'],
        'file' => $filename,
        'size' => $size,
        'sha256' => $sha,
        'mime' => $ext === 'json' ? 'application/json' : 'application/zip',
        'original_name' => (string) $originalName,
        'price' => max(0, min(999999, (int) $price)),
        'uploaded_at' => now(),
    ];
    plugin_mall_upsert($entry);
    return $entry;
}

function plugin_mall_remove_package_file($file)
{
    $file = basename((string) $file);
    if ($file === '' || $file === '.' || $file === '..') {
        return;
    }
    $path = plugin_mall_packages_dir() . '/' . $file;
    if (is_file($path)) {
        @unlink($path);
    }
}

/** 从商城目录移除条目及插件包文件；不自动卸载本站已安装插件。 */
function plugin_mall_delete($slug)
{
    $slug = plugin_slugify($slug);
    $items = plugin_mall_catalog();
    $found = null;
    foreach ($items as $i => $item) {
        if ((string) $item['slug'] === $slug) {
            $found = $item;
            unset($items[$i]);
            break;
        }
    }
    if ($found === null) {
        return false;
    }
    if (!empty($found['file'])) {
        plugin_mall_remove_package_file((string) $found['file']);
    }
    plugin_mall_catalog_save(array_values($items));
    return true;
}

/** 当前用户是否已经购买过某个商城插件。 */
function plugin_mall_purchased($userId, $slug)
{
    $userId = (int) $userId;
    $slug = plugin_slugify($slug);
    if ($userId <= 0 || $slug === '') {
        return false;
    }
    try {
        return (int) DB::val(
            'SELECT COUNT(*) FROM ' . DB::table('plugin_purchases') . ' WHERE user_id = ? AND slug = ?',
            [$userId, $slug],
            0
        ) > 0;
    } catch (Throwable $e) {
        return false;
    }
}

/**
 * 购买插件：同一账号对同一插件只扣一次积分。
 * 返回 ['already'=>bool,'charged'=>int,'points'=>int]。
 */
function plugin_mall_purchase($user, array $item)
{
    if (!$user || empty($user['id'])) {
        throw new Exception('请先登录后再购买插件');
    }
    $userId = (int) $user['id'];
    $slug = plugin_slugify((string) ($item['slug'] ?? ''));
    $name = trim((string) ($item['name'] ?? $slug));
    $price = max(0, (int) ($item['price'] ?? 0));
    if ($slug === '') {
        throw new Exception('插件记录不正确');
    }
    if (plugin_mall_purchased($userId, $slug)) {
        return ['already' => true, 'charged' => 0, 'points' => (int) DB::val('SELECT points FROM ' . DB::table('users') . ' WHERE id = ?', [$userId], 0)];
    }

    $isSuper = is_superadmin($user);
    $charged = $price;
    if ($price > 0 && !$isSuper) {
        $points = (int) DB::val('SELECT points FROM ' . DB::table('users') . ' WHERE id = ?', [$userId], 0);
        if ($points < $price) {
            throw new Exception('积分不足：该插件售价 ' . $price . ' 积分，当前可用 ' . max(0, $points) . ' 积分');
        }
        add_points($userId, -$price);
    } elseif ($isSuper) {
        // 超级管理员积分为无限，保留流水但不产生负数余额。
        $charged = 0;
    }

    DB::insert('plugin_purchases', [
        'user_id' => $userId,
        'slug' => $slug,
        'price' => $charged,
        'created_at' => now(),
    ]);
    DB::insert('point_logs', [
        'user_id' => $userId,
        'action' => 'plugin_buy',
        'delta' => $isSuper ? 0 : -$charged,
        'note' => '购买插件「' . $name . '」' . ($isSuper ? '（超级管理员积分无限）' : ''),
        'ref_id' => 0,
        'created_at' => now(),
    ]);

    return [
        'already' => false,
        'charged' => $charged,
        'points' => (int) DB::val('SELECT points FROM ' . DB::table('users') . ' WHERE id = ?', [$userId], 0),
    ];
}
