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

$activeNav = 'plugins';
$pageTitle = '插件管理';

// 处理上传安装
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'upload_plugin') {
    require_csrf();
    try {
        if (!isset($_FILES['plugin_zip'])) {
            throw new Exception('请选择插件 ZIP 文件。');
        }
        $result = install_plugin_from_upload($_FILES['plugin_zip']);
        $verb = !empty($result['updated']) ? '更新' : '安装';
        $_SESSION['flash_success'] = '插件「' . $result['name'] . '」' . $verb . '成功（v' . $result['version'] . '，共 ' . $result['files_count'] . ' 个文件）。';
    } catch (Exception $e) {
        $_SESSION['flash_error'] = $e->getMessage();
    }
    header('Location: /admin/plugin/list.php');
    exit;
}

// 处理操作
$action = isset($_GET['action']) ? trim((string)$_GET['action']) : '';
$slug = isset($_GET['slug']) ? trim((string)$_GET['slug']) : '';

if ($action !== '' && $slug !== '' && $_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['_csrf_token'])) {
    // CSRF 验证
    $token = trim((string)$_GET['_csrf_token']);
    if ($token === '' || empty($_SESSION['_csrf_token']) || !hash_equals($_SESSION['_csrf_token'], $token)) {
        $_SESSION['flash_error'] = 'CSRF token 验证失败';
    } else {
        switch ($action) {
            case 'enable':
                if (plugin_enable($slug)) {
                    $_SESSION['flash_success'] = '插件 "' . $slug . '" 已启用';
                }
                break;
            case 'disable':
                if (plugin_disable($slug)) {
                    $_SESSION['flash_success'] = '插件 "' . $slug . '" 已禁用';
                }
                break;
            case 'delete':
                if (plugin_delete($slug)) {
                    $_SESSION['flash_success'] = '插件 "' . $slug . '" 已删除';
                }
                break;
        }
    }
    header('Location: /admin/plugin/list.php');
    exit;
}

// 获取所有插件
$plugins = plugin_scan_all();
$enabledList = plugin_enabled_list();

$flashSuccess = isset($_SESSION['flash_success']) ? $_SESSION['flash_success'] : '';
$flashError = isset($_SESSION['flash_error']) ? $_SESSION['flash_error'] : '';
unset($_SESSION['flash_success'], $_SESSION['flash_error']);

require __DIR__ . '/../../app/admin-sidebar.php';
?>
<!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>
.plugin-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(360px,1fr));gap:20px;margin-top:20px}
.plugin-card{background:#fff;border-radius:12px;padding:24px;border:1px solid #e5e7eb;transition:box-shadow .2s}
.plugin-card:hover{box-shadow:0 4px 12px rgba(0,0,0,.08)}
.plugin-card-header{display:flex;align-items:center;gap:12px;margin-bottom:12px}
.plugin-icon{width:44px;height:44px;border-radius:10px;background:#f0f4ff;display:flex;align-items:center;justify-content:center;font-size:22px}
.plugin-title{font-size:16px;font-weight:600;color:#1a1a2e}
.plugin-version{font-size:12px;color:#6b7280;margin-left:8px;background:#f3f4f6;padding:2px 6px;border-radius:4px}
.plugin-desc{font-size:13px;color:#6b7280;line-height:1.6;margin-bottom:16px;min-height:40px}
.plugin-meta{display:flex;align-items:center;gap:12px;font-size:12px;color:#9ca3af;margin-bottom:16px}
.plugin-actions{display:flex;gap:8px;align-items:center}
.plg-btn{display:inline-flex;align-items:center;gap:4px;padding:7px 14px;border-radius:6px;font-size:13px;font-weight:500;text-decoration:none;cursor:pointer;border:none;transition:all .15s}
.plg-btn-enable{background:#ecfdf5;color:#065f46;border:1px solid #a7f3d0}
.plg-btn-enable:hover{background:#d1fae5}
.plg-btn-disable{background:#fef3c7;color:#92400e;border:1px solid #fde68a}
.plg-btn-disable:hover{background:#fde68a}
.plg-btn-delete{background:#fef2f2;color:#991b1b;border:1px solid #fecaca}
.plg-btn-delete:hover{background:#fecaca}
.plg-btn-config{background:#f0f4ff;color:#1e40af;border:1px solid #bfdbfe}
.plg-btn-config:hover{background:#dbeafe}
.plugin-status{display:inline-flex;align-items:center;gap:4px;font-size:12px;font-weight:500;padding:3px 8px;border-radius:20px}
.status-enabled{background:#d1fae5;color:#065f46}
.status-disabled{background:#f3f4f6;color:#6b7280}
.plugin-empty{text-align:center;padding:60px 20px;color:#9ca3af}
.plugin-empty p{font-size:15px;margin-top:12px}
.plugin-empty .empty-icon{font-size:48px;margin-bottom:8px}
.upload-btn{display:inline-flex;align-items:center;gap:6px;padding:8px 16px;border-radius:6px;font-size:13px;font-weight:500;background:#4f46e5;color:#fff;border:none;cursor:pointer;transition:background .15s}
.upload-btn:hover{background:#4338ca}
.plg-modal-overlay{display:none;position:fixed;inset:0;background:rgba(0,0,0,.45);z-index:1000;justify-content:center;align-items:center}
.plg-modal-overlay.is-open{display:flex}
.plg-modal{background:#fff;border-radius:14px;width:480px;max-width:92vw;box-shadow:0 20px 60px rgba(0,0,0,.18);overflow:hidden}
.plg-modal-head{display:flex;align-items:center;justify-content:space-between;padding:18px 22px;border-bottom:1px solid #f1f5f9}
.plg-modal-head h3{font-size:16px;font-weight:600;color:#1a1a2e;margin:0}
.plg-modal-close{background:none;border:none;font-size:22px;color:#94a3b8;cursor:pointer;padding:0 4px}
.plg-modal-close:hover{color:#475569}
.plg-modal-body{padding:22px}
.plg-upload-zone{border:2px dashed #d1d5db;border-radius:10px;padding:40px 20px;text-align:center;cursor:pointer;transition:border-color .15s,background .15s}
.plg-upload-zone:hover,.plg-upload-zone.drag-over{border-color:#4f46e5;background:#f5f3ff}
.plg-upload-zone .icon{font-size:36px;margin-bottom:8px}
.plg-upload-zone p{margin:0;font-size:13px;color:#6b7280}
.plg-upload-zone .file-name{margin-top:10px;font-size:14px;font-weight:600;color:#4f46e5}
.plg-submit-btn{display:block;width:100%;padding:10px;margin-top:16px;border:none;border-radius:8px;font-size:14px;font-weight:600;background:#4f46e5;color:#fff;cursor:pointer;transition:background .15s}
.plg-submit-btn:hover{background:#4338ca}
.plg-submit-btn:disabled{background:#a5b4fc;cursor:not-allowed}
.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}
@media(max-width:768px){
    .plugin-grid{grid-template-columns:1fr}
}
</style>
</head>
<body>
<div class="admin-shell">
<?php
$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));
render_admin_sidebar($activeNav, $adminName, $adminUsername, $avatarText);
?>
<main class="admin-content">
<div class="content-wrap">
    <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:6px;">
        <h2 style="font-size:20px;font-weight:700;color:#1a1a2e;margin:0;">插件管理</h2>
        <button class="upload-btn" type="button" onclick="document.getElementById('uploadModal').classList.add('is-open')">📦 上传插件</button>
    </div>
    <div class="tab-nav">
        <a href="/admin/plugin/list.php" class="active">本地插件</a>
        <a href="/admin/plugin/market.php">插件市场</a>
        <a href="/admin/plugin/doc.php">开发规范</a>
    </div>

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

    <?php if (empty($plugins)): ?>
        <div class="plugin-empty">
            <div class="empty-icon">🔌</div>
            <p>暂无已安装的插件</p>
            <p style="font-size:13px;margin-top:8px;color:#b0b0b0">将插件目录放入 <code>plugins/</code> 文件夹即可识别</p>
        </div>
    <?php else: ?>
        <div class="plugin-grid">
            <?php foreach ($plugins as $pSlug => $meta): ?>
                <div class="plugin-card">
                    <div class="plugin-card-header">
                        <div class="plugin-icon"><?php echo $meta['icon']; ?></div>
                        <div>
                            <span class="plugin-title"><?php echo e($meta['name']); ?></span>
                            <span class="plugin-version">v<?php echo e($meta['version']); ?></span>
                        </div>
                    </div>
                    <div class="plugin-desc"><?php echo e($meta['description']); ?></div>
                    <div class="plugin-meta">
                        <?php if ($meta['author']): ?>
                            <span>作者: <?php echo e($meta['author']); ?></span>
                        <?php endif; ?>
                        <?php if ($meta['requires']): ?>
                            <span>要求: v<?php echo e($meta['requires']); ?>+</span>
                        <?php endif; ?>
                        <span class="plugin-status <?php echo $meta['enabled'] ? 'status-enabled' : 'status-disabled'; ?>">
                            <?php echo $meta['enabled'] ? '已启用' : '未启用'; ?>
                        </span>
                    </div>
                    <div class="plugin-actions">
                        <?php if ($meta['enabled']): ?>
                            <a class="plg-btn plg-btn-disable" href="?action=disable&slug=<?php echo e($pSlug); ?>&_csrf_token=<?php echo e(csrf_token()); ?>" onclick="return confirm('确定禁用此插件？')">禁用</a>
                            <?php
                            $configFile = PLUGINS_PATH . '/' . $pSlug . '/views/settings.php';
                            if (is_file($configFile)):
                            ?>
                                <a class="plg-btn plg-btn-config" href="/admin/plugin/page.php?slug=<?php echo e($pSlug); ?>&view=settings">配置</a>
                            <?php endif; ?>
                        <?php else: ?>
                            <a class="plg-btn plg-btn-enable" href="?action=enable&slug=<?php echo e($pSlug); ?>&_csrf_token=<?php echo e(csrf_token()); ?>">启用</a>
                        <?php endif; ?>
                        <a class="plg-btn plg-btn-delete" href="?action=delete&slug=<?php echo e($pSlug); ?>&_csrf_token=<?php echo e(csrf_token()); ?>" onclick="return confirm('确定删除此插件？此操作不可恢复！')">删除</a>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>
</main>
</div>

<!-- 上传插件弹窗 -->
<div class="plg-modal-overlay" id="uploadModal">
    <div class="plg-modal">
        <div class="plg-modal-head">
            <h3>📦 上传本地插件</h3>
            <button type="button" class="plg-modal-close" onclick="document.getElementById('uploadModal').classList.remove('is-open')">&times;</button>
        </div>
        <div class="plg-modal-body">
            <form method="POST" enctype="multipart/form-data" id="uploadForm">
                <?php echo csrf_field(); ?>
                <input type="hidden" name="action" value="upload_plugin">
                <div class="plg-upload-zone" id="dropZone" onclick="document.getElementById('zipInput').click()">
                    <div class="icon">📁</div>
                    <p>点击选择或拖拽 .zip 插件包到此处</p>
                    <p style="font-size:12px;color:#94a3b8;margin-top:6px;">ZIP 内须包含 plugin.php 入口文件</p>
                    <div class="file-name" id="fileName" style="display:none;"></div>
                </div>
                <input type="file" name="plugin_zip" id="zipInput" accept=".zip" style="display:none" onchange="showFileName(this)">
                <button type="submit" class="plg-submit-btn" id="submitBtn" disabled>安装插件</button>
            </form>
        </div>
    </div>
</div>
<script>
function showFileName(input) {
    var fn = document.getElementById('fileName');
    var btn = document.getElementById('submitBtn');
    if (input.files && input.files.length > 0) {
        fn.textContent = input.files[0].name;
        fn.style.display = 'block';
        btn.disabled = false;
    } else {
        fn.style.display = 'none';
        btn.disabled = true;
    }
}
(function(){
    var zone = document.getElementById('dropZone');
    var input = document.getElementById('zipInput');
    zone.addEventListener('dragover', function(e){ e.preventDefault(); zone.classList.add('drag-over'); });
    zone.addEventListener('dragleave', function(){ zone.classList.remove('drag-over'); });
    zone.addEventListener('drop', function(e){
        e.preventDefault(); zone.classList.remove('drag-over');
        if (e.dataTransfer.files.length > 0) {
            input.files = e.dataTransfer.files;
            showFileName(input);
        }
    });
    document.getElementById('uploadModal').addEventListener('click', function(e){
        if (e.target === this) this.classList.remove('is-open');
    });
    document.getElementById('uploadForm').addEventListener('submit', function(){
        var btn = document.getElementById('submitBtn');
        btn.disabled = true; btn.textContent = '安装中…';
    });
})();
</script>
</body>
</html>
