<?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));

$deleteStatus = isset($_GET['delete_status']) ? trim((string)$_GET['delete_status']) : '';
$dbError = '';
$modules = array();
$domains = array();
$widgetTypes = module_widget_types();

try {
    $domains = list_enabled_domain_options();
    $modules = list_modules();
} catch (Exception $e) {
    $dbError = $e->getMessage();
}
?><!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(APP_NAME); ?> - 模块管理</title>
    <link rel="stylesheet" href="/assets/css/admin-ui.css">
</head>
<body>
<div class="admin-shell">
    <?php render_admin_sidebar('components', $adminName, $adminUsername, $avatarText); ?>
    <main class="admin-content">
        <div class="content-wrap">
            <header class="topbar">
                <div><h1>模块管理</h1><p>通过组合基础组件（标题、文本、图片、链接等）创建自定义模块，每个模块生成独立的模板调用变量。</p></div>
                <div class="topbar-actions"><a class="btn-primary" href="/admin/component/edit.php">新增模块</a></div>
            </header>
            <section class="page-card">
                <?php if ($deleteStatus === 'success'): ?>
                    <div class="mini-item" style="margin-bottom:16px; border-color: rgba(34,197,94,0.18); background: rgba(34,197,94,0.06);"><strong style="color:#15803d;">删除成功</strong><p style="margin:0; color:#166534;">模块已删除。</p></div>
                <?php elseif ($deleteStatus === 'error'): ?>
                    <div class="mini-item" style="margin-bottom:16px; border-color: rgba(220,38,38,0.18); background: rgba(220,38,38,0.06);"><strong style="color:#dc2626;">删除失败</strong><p style="margin:0; color:#b91c1c;">请稍后重试。</p></div>
                <?php endif; ?>
                <?php if ($dbError !== ''): ?>
                    <div class="mini-item" style="margin-bottom:16px; border-color: rgba(220,38,38,0.18); background: rgba(220,38,38,0.06);"><strong style="color:#dc2626;">数据库读取失败</strong><p style="margin:0; color:#b91c1c;"><?php echo e($dbError); ?></p></div>
                <?php endif; ?>

                <table class="data-table">
                    <thead><tr><th>ID</th><th>模块名称</th><th>调用变量</th><th>组件数</th><th>适用域名</th><th>状态</th><th>更新时间</th><th>操作</th></tr></thead>
                    <tbody>
                    <?php if (!empty($modules)): ?>
                        <?php foreach ($modules as $item): ?>
                            <?php
                                $domainLabel = '全局';
                                if ((int)$item['domain_id'] > 0) {
                                    foreach ($domains as $d) {
                                        if ((int)$d['id'] === (int)$item['domain_id']) { $domainLabel = (string)$d['domain']; break; }
                                    }
                                }
                                $itemsArr = json_decode((string)$item['mod_items'], true);
                                $widgetCount = is_array($itemsArr) ? count($itemsArr) : 0;
                                $varTag = '{{mod_' . e($item['mod_code']) . '}}';
                            ?>
                            <tr>
                                <td><?php echo (int)$item['id']; ?></td>
                                <td><strong><?php echo e($item['mod_name']); ?></strong></td>
                                <td><code style="background:#f1f5f9; padding:2px 8px; border-radius:4px; font-size:12px; color:#4f46e5;"><?php echo e($varTag); ?></code></td>
                                <td><?php echo $widgetCount; ?> 个</td>
                                <td><?php echo e($domainLabel); ?></td>
                                <td><span class="badge <?php echo $item['status'] === 'enabled' ? 'success' : 'info'; ?>"><?php echo e($item['status'] === 'enabled' ? '启用' : '停用'); ?></span></td>
                                <td><?php echo e($item['updated_at']); ?></td>
                                <td>
                                    <a href="/admin/component/edit.php?id=<?php echo (int)$item['id']; ?>">编辑</a> /
                                    <form method="post" action="/admin/component/delete.php" style="display:inline;" onsubmit="return confirm('确认删除模块「<?php echo e($item['mod_name']); ?>」吗？');">
                                        <?php echo csrf_field(); ?>
                                        <input type="hidden" name="id" value="<?php echo (int)$item['id']; ?>">
                                        <button type="submit" class="link-btn" style="color:#dc2626;">删除</button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr><td colspan="8" class="empty-note"><?php echo $dbError === '' ? '暂无模块，点击「新增模块」开始创建。' : '无法加载模块数据。'; ?></td></tr>
                    <?php endif; ?>
                    </tbody>
                </table>

                <div style="margin-top:24px; padding:20px; background:#f8fafc; border:1px solid #e2e8f0; border-radius:10px;">
                    <h3 style="font-size:14px; font-weight:600; margin:0 0 8px; color:#334155;">可用基础组件</h3>
                    <div style="display:flex; flex-wrap:wrap; gap:8px; margin-bottom:16px;">
                        <?php foreach ($widgetTypes as $wk => $wv): ?>
                            <span style="display:inline-flex; align-items:center; gap:4px; padding:4px 12px; background:#fff; border:1px solid #e2e8f0; border-radius:6px; font-size:13px;"><strong style="min-width:18px; text-align:center;"><?php echo $wv['icon']; ?></strong> <?php echo e($wv['label']); ?></span>
                        <?php endforeach; ?>
                    </div>
                    <h3 style="font-size:14px; font-weight:600; margin:0 0 8px; color:#334155;">使用方式</h3>
                    <p style="font-size:13px; color:#64748b; margin:0;">新增模块 → 设置模块编码（如 <code>about_us</code>）→ 添加组件并填写内容 → 保存后在模板中使用 <code>{{mod_about_us}}</code> 调用。</p>
                </div>
            </section>
        </div>
    </main>
</div>
<script src="/assets/js/admin-ui.js"></script>
</body>
</html>
