<?php
require __DIR__ . '/../../app/bootstrap.php';
require __DIR__ . '/../../app/database.php';
require __DIR__ . '/../../app/admin-sidebar.php';
require_login();

$adminName = isset($_SESSION['admin_name']) ? (string)$_SESSION['admin_name'] : 'Admin';
$adminUsername = isset($_SESSION['admin_username']) ? (string)$_SESSION['admin_username'] : 'admin';
$avatarText = strtoupper(substr($adminName !== '' ? $adminName : 'A', 0, 1));

$activeNav = 'plugin_market';
$pageTitle = '插件市场';

$error = '';
$success = '';

// PRG: 处理 POST 安装请求
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'install') {
    require_csrf();
    $installSlug = isset($_POST['slug']) ? trim((string)$_POST['slug']) : '';
    try {
        $result = install_plugin_from_cloud($installSlug);
        $verb = !empty($result['updated']) ? '更新' : '下载安装';
        $_SESSION['plugin_market_flash'] = '插件「' . $result['name'] . '」' . $verb . '成功（v' . $result['version'] . '，共 ' . $result['files_count'] . ' 个文件）。';
        $_SESSION['plugin_market_flash_type'] = 'success';
    } catch (Exception $e) {
        $_SESSION['plugin_market_flash'] = $e->getMessage();
        $_SESSION['plugin_market_flash_type'] = 'error';
    }
    header('Location: /admin/plugin/market.php');
    exit;
}

// 读取 flash
if (isset($_SESSION['plugin_market_flash'])) {
    if (isset($_SESSION['plugin_market_flash_type']) && $_SESSION['plugin_market_flash_type'] === 'error') {
        $error = $_SESSION['plugin_market_flash'];
    } else {
        $success = $_SESSION['plugin_market_flash'];
    }
    unset($_SESSION['plugin_market_flash'], $_SESSION['plugin_market_flash_type']);
}

// 拉取云端列表
$cloudPlugins = array();
$cloudError = '';
try {
    $cloudPlugins = fetch_cloud_plugin_list();
} catch (Exception $e) {
    $cloudError = $e->getMessage();
}

// 本地已安装映射: slug => version
$localPlugins = plugin_scan_all();
$localInstalled = array();
foreach ($localPlugins as $lSlug => $lMeta) {
    $localInstalled[$lSlug] = isset($lMeta['version']) ? $lMeta['version'] : '0.0.0';
}
?><!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?php echo e($pageTitle); ?> - <?php echo e(APP_NAME); ?></title>
<link rel="stylesheet" href="/assets/css/admin-ui.css">
<style>
.tab-nav{display:flex;gap:8px;margin-bottom:18px}
.tab-nav a{padding:8px 16px;border-radius:6px;font-size:13px;font-weight:500;text-decoration:none;color:#6b7280;background:#f3f4f6}
.tab-nav a.active{background:#4f46e5;color:#fff}
.flash-msg{padding:12px 16px;border-radius:8px;font-size:14px;margin-bottom:16px;border:1px solid transparent}
.flash-success{background:#ecfdf5;color:#065f46;border-color:#a7f3d0}
.flash-error{background:#fef2f2;color:#991b1b;border-color:#fecaca}
.market-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(360px,1fr));gap:18px;margin-top:18px}
.market-card{background:#fff;border:1px solid #e5e7eb;border-radius:12px;padding:18px;display:flex;gap:14px;transition:box-shadow .15s,border-color .15s}
.market-card:hover{border-color:#c7d2fe;box-shadow:0 4px 12px rgba(79,70,229,.08)}
.market-card-icon{flex-shrink:0;width:56px;height:56px;border-radius:12px;background:linear-gradient(135deg,#eef2ff,#ede9fe);display:flex;align-items:center;justify-content:center;font-size:28px}
.market-card-body{flex:1;min-width:0;display:flex;flex-direction:column}
.market-card-top{display:flex;align-items:flex-start;justify-content:space-between;gap:8px;margin-bottom:4px}
.market-card-title{font-size:15px;font-weight:600;color:#1a1a2e;margin:0;line-height:1.4;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.market-card-desc{font-size:12px;color:#6b7280;line-height:1.6;margin:0 0 auto;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;padding-bottom:10px}
.market-card-footer{display:flex;align-items:center;justify-content:space-between;gap:8px;padding-top:8px;border-top:1px solid #f1f5f9}
.market-card-meta{font-size:11px;color:#787c82;display:flex;flex-wrap:wrap;gap:4px 10px}
.btn-install{display:inline-flex;align-items:center;gap:4px;padding:5px 14px;font-size:12px;font-weight:500;border:none;border-radius:5px;cursor:pointer;transition:all .15s;white-space:nowrap}
.btn-install.available{background:#4f46e5;color:#fff}
.btn-install.available:hover{background:#4338ca}
.btn-install.installed{background:#f0fdf4;color:#15803d;cursor:default;border:1px solid #bbf7d0}
.btn-install.updatable{background:#fef3c7;color:#92400e;border:1px solid #fcd34d}
.btn-install.updatable:hover{background:#fde68a}
.market-card-badge{display:inline-flex;align-items:center;padding:2px 7px;font-size:10px;font-weight:600;border-radius:4px}
.market-card-badge.update{background:#fef3c7;color:#92400e}
.market-card-badge.new{background:#dcfce7;color:#166534}
.market-empty{text-align:center;padding:60px 20px;color:#94a3b8;background:#fff;border:1px dashed #e5e7eb;border-radius:12px}
.market-empty .icon{font-size:48px;margin-bottom:12px}
.market-filter{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:14px}
.market-filter .filter-btn{padding:6px 14px;font-size:12px;border:1px solid #e5e7eb;border-radius:6px;background:#fff;color:#50575e;cursor:pointer}
.market-filter .filter-btn.active{background:#4f46e5;color:#fff;border-color:#4f46e5}
</style>
</head>
<body>
<div class="admin-shell">
<?php render_admin_sidebar($activeNav, $adminName, $adminUsername, $avatarText); ?>
<main class="admin-content">
<div class="content-wrap">
    <h2 style="font-size:20px;font-weight:700;color:#1a1a2e;margin-bottom:6px;">插件管理</h2>
    <div class="tab-nav">
        <a href="/admin/plugin/list.php">本地插件</a>
        <a href="/admin/plugin/market.php" class="active">插件市场</a>
        <a href="/admin/plugin/doc.php">开发规范</a>
    </div>

    <?php if ($success): ?>
        <div class="flash-msg flash-success"><?php echo e($success); ?></div>
    <?php endif; ?>
    <?php if ($error): ?>
        <div class="flash-msg flash-error"><?php echo e($error); ?></div>
    <?php endif; ?>

    <div class="market-filter">
        <button type="button" class="filter-btn active" onclick="filterMarket(this,'all')">全部 <span id="cnt-all">(<?php echo count($cloudPlugins); ?>)</span></button>
        <button type="button" class="filter-btn" onclick="filterMarket(this,'not-installed')">未安装</button>
        <button type="button" class="filter-btn" onclick="filterMarket(this,'has-update')">🔄 有更新</button>
        <button type="button" class="filter-btn" onclick="filterMarket(this,'installed')">已安装</button>
    </div>

    <?php if ($cloudError): ?>
        <div class="market-empty">
            <div class="icon">⚠️</div>
            <p style="color:#dc2626;font-size:14px;"><?php echo e($cloudError); ?></p>
            <p style="font-size:12px;margin-top:6px;">请确认 cloud.beeai.chat 可正常访问，或稍后重试。</p>
        </div>
    <?php elseif (empty($cloudPlugins)): ?>
        <div class="market-empty">
            <div class="icon">📦</div>
            <p>云端暂无可用插件</p>
        </div>
    <?php else: ?>
        <div class="market-grid" id="marketGrid">
            <?php foreach ($cloudPlugins as $cp):
                $cSlug = isset($cp['slug']) ? $cp['slug'] : '';
                $cName = isset($cp['name']) ? $cp['name'] : $cSlug;
                $cDesc = isset($cp['description']) ? $cp['description'] : '';
                $cVersion = isset($cp['version']) ? $cp['version'] : '1.0.0';
                $cAuthor = isset($cp['author']) ? $cp['author'] : '';
                $cIcon = isset($cp['icon']) && $cp['icon'] !== '' ? $cp['icon'] : '🔌';
                $cSize = isset($cp['file_size']) ? (int)$cp['file_size'] : 0;
                $cDate = isset($cp['updated_at']) ? trim((string)$cp['updated_at']) : '';
                $cChangelog = isset($cp['changelog']) ? trim((string)$cp['changelog']) : '';
                $isInstalled = isset($localInstalled[$cSlug]);
                $localVer = $isInstalled ? $localInstalled[$cSlug] : '';
                $isUpdatable = $isInstalled && version_compare($cVersion, $localVer, '>');
                $isNew = !$isInstalled && $cDate !== '' && strtotime($cDate) >= strtotime('-7 days');
            ?>
            <div class="market-card" data-installed="<?php echo $isInstalled ? '1' : '0'; ?>" data-updatable="<?php echo $isUpdatable ? '1' : '0'; ?>">
                <div class="market-card-icon"><?php echo e($cIcon); ?></div>
                <div class="market-card-body">
                    <div class="market-card-top">
                        <h3 class="market-card-title"><?php echo e($cName); ?></h3>
                        <?php if ($isUpdatable): ?>
                            <form method="post" style="margin:0;" onsubmit="return confirm('确定更新插件【<?php echo e($cName); ?>】到 v<?php echo e($cVersion); ?>？\n将覆盖插件目录中的文件。');">
                                <?php echo csrf_field(); ?>
                                <input type="hidden" name="action" value="install">
                                <input type="hidden" name="slug" value="<?php echo e($cSlug); ?>">
                                <button type="submit" class="btn-install updatable">更新</button>
                            </form>
                        <?php elseif ($isInstalled): ?>
                            <span class="btn-install installed">已安装</span>
                        <?php else: ?>
                            <form method="post" style="margin:0;" onsubmit="this.querySelector('button').disabled=true;this.querySelector('button').textContent='…';">
                                <?php echo csrf_field(); ?>
                                <input type="hidden" name="action" value="install">
                                <input type="hidden" name="slug" value="<?php echo e($cSlug); ?>">
                                <button type="submit" class="btn-install available">安装</button>
                            </form>
                        <?php endif; ?>
                    </div>
                    <p class="market-card-desc"><?php echo e($cDesc); ?></p>
                    <div class="market-card-footer">
                        <div class="market-card-meta">
                            <?php if ($cAuthor !== ''): ?><span>作者: <?php echo e($cAuthor); ?></span><?php endif; ?>
                            <span>v<?php echo e($isInstalled && $localVer !== '' ? $localVer : $cVersion); ?></span>
                            <?php if ($cDate !== ''): ?><span><?php echo e($cDate); ?></span><?php endif; ?>
                            <?php if ($cSize > 0): ?><span><?php echo round($cSize / 1024, 0); ?>KB</span><?php endif; ?>
                        </div>
                        <?php if ($isUpdatable): ?>
                            <span class="market-card-badge update">有新版</span>
                        <?php elseif ($isNew): ?>
                            <span class="market-card-badge new">新上架</span>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>
</main>
</div>

<script>
function filterMarket(btn, type) {
    document.querySelectorAll('.market-filter .filter-btn').forEach(function(b){ b.classList.remove('active'); });
    btn.classList.add('active');
    document.querySelectorAll('.market-card').forEach(function(card){
        var installed = card.getAttribute('data-installed') === '1';
        var updatable = card.getAttribute('data-updatable') === '1';
        var show = true;
        if (type === 'not-installed') show = !installed;
        else if (type === 'installed') show = installed;
        else if (type === 'has-update') show = updatable;
        card.style.display = show ? '' : 'none';
    });
}
</script>
</body>
</html>
