{include file="app/manage/view/index/emlog_nav"}

<h1 class="page-title">
    <i class="fas fa-users"></i>
    社区管理 - 小组管理
</h1>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div class="action-buttons">
        <button class="btn btn-primary" onclick="openGroupModal(0)">
            <i class="fas fa-plus"></i> 新增小组
        </button>
        <button class="btn btn-outline-success" onclick="location.reload()">
            <i class="fas fa-sync-alt"></i> 刷新
        </button>
        <a href="index.php?r=manage/forum/board" class="btn btn-outline-info">
            <i class="fas fa-th-large"></i> 板块管理
        </a>
    </div>
    <div class="text-muted small">
        <i class="fas fa-info-circle"></i> 小组是可选归属到板块下的兴趣圈，用户在小组内发帖讨论
    </div>
</div>

<div class="card">
    <div class="card-header">
        <i class="fas fa-table"></i> 小组列表
        <span class="badge badge-info float-right mt-1"><?php echo count($groups); ?> 个小组</span>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover table-striped">
                <thead class="thead-light">
                    <tr>
                        <th class="w-60">ID</th>
                        <th class="w-60">排序</th>
                        <th class="w-56">图标</th>
                        <th>小组名称</th>
                        <th class="w-120">所属板块</th>
                        <th>简介</th>
                        <th class="w-80">成员</th>
                        <th class="w-180">操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!empty($groups)): ?>
                    <?php
                    // 构建板块 id => name 映射，避免循环内查库
                    $boardMap = array();
                    if (!empty($boards)) {
                        foreach ($boards as $b) {
                            $boardMap[(int)$b['id']] = $b['name'];
                        }
                    }
                    ?>
                    <?php foreach ($groups as $row): ?>
                    <?php
                    $gid = (int)$row['id'];
                    $gname = $row['groupname'] ?? '';
                    $gpx = (int)($row['px'] ?? 0);
                    $gIcon = $row['icon'] ?? '';
                    $gDesc = $row['desc'] ?? '';
                    $gBankuaiId = (int)($row['bankuai_id'] ?? 0);
                    $gMembers = (int)($row['member_count'] ?? 0);
                    $gBankuaiName = isset($boardMap[$gBankuaiId]) ? $boardMap[$gBankuaiId] : '';
                    // JS 安全转义
                    $jsGname = htmlspecialchars($gname, ENT_QUOTES, 'UTF-8');
                    $jsGdesc = htmlspecialchars($gDesc, ENT_QUOTES, 'UTF-8');
                    $jsGicon = htmlspecialchars($gIcon, ENT_QUOTES, 'UTF-8');
                    ?>
                    <tr id="group-row-<?php echo $gid; ?>">
                        <td><?php echo $gid; ?></td>
                        <td><?php echo $gpx; ?></td>
                        <td>
                            <?php if (!empty($gIcon)): ?>
                            <img src="<?php echo $jsGicon; ?>" alt="" class="w-36 h-36" style="object-fit: cover ; border-radius: 8px">
                            <?php else: ?>
                            <div class="w-36 h-36 d-flex" style="border-radius: 8px ; background: linear-gradient(135deg, #667eea, #764ba2) ; color: #fff ; align-items: center ; justify-content: center ; font-weight: 600">
                                <?php echo htmlspecialchars(mb_substr($gname, 0, 1, 'UTF-8'), ENT_QUOTES, 'UTF-8'); ?>
                            </div>
                            <?php endif; ?>
                        </td>
                        <td><strong><?php echo htmlspecialchars($gname, ENT_QUOTES, 'UTF-8'); ?></strong></td>
                        <td>
                            <?php if (!empty($gBankuaiName)): ?>
                            <span class="badge badge-info"><?php echo htmlspecialchars($gBankuaiName, ENT_QUOTES, 'UTF-8'); ?></span>
                            <?php else: ?>
                            <span class="text-muted">—</span>
                            <?php endif; ?>
                        </td>
                        <td><small class="text-muted"><?php echo htmlspecialchars(mb_substr($gDesc, 0, 30, 'UTF-8'), ENT_QUOTES, 'UTF-8'); ?><?php echo mb_strlen($gDesc, 'UTF-8') > 30 ? '…' : ''; ?></small></td>
                        <td><span class="badge badge-secondary"><?php echo $gMembers; ?></span></td>
                        <td>
                            <div class="btn-group btn-group-sm" role="group">
                                <button class="btn btn-outline-primary" onclick="openGroupModal(<?php echo $gid; ?>, '<?php echo $jsGname; ?>', <?php echo $gpx; ?>, <?php echo $gBankuaiId; ?>, '<?php echo $jsGicon; ?>', '<?php echo $jsGdesc; ?>')">
                                    <i class="fas fa-edit"></i> 编辑
                                </button>
                                <button class="btn btn-outline-danger" onclick="delGroup(<?php echo $gid; ?>)">
                                    <i class="fas fa-trash"></i> 删除
                                </button>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php else: ?>
                    <tr>
                        <td colspan="8" class="text-center py-5">
                            <div class="empty-state">
                                <i class="fas fa-users fa-3x text-muted mb-3"></i>
                                <h5 class="text-muted">暂无小组</h5>
                                <p class="text-muted">点击"新增小组"按钮创建第一个小组</p>
                            </div>
                        </td>
                    </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- 小组编辑弹窗 -->
<div class="modal fade" id="groupModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <form id="groupForm" onsubmit="return false;">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-edit"></i> <span id="groupModalTitle">新增小组</span></h5>
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                </div>
                <div class="modal-body">
                    <input type="hidden" id="groupId" name="id" value="0">
                    <div class="form-row">
                        <div class="form-group col-md-7">
                            <label class="font-weight-bold">小组名称 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="groupName" name="groupname" maxlength="50" required>
                        </div>
                        <div class="form-group col-md-3">
                            <label class="font-weight-bold">所属板块</label>
                            <select class="form-control" id="groupBankuai" name="bankuai_id">
                                <option value="0">— 不归属 —</option>
                                <?php if (!empty($boards)): ?>
                                <?php foreach ($boards as $b): ?>
                                <option value="<?php echo (int)$b['id']; ?>"><?php echo htmlspecialchars($b['name'], ENT_QUOTES, 'UTF-8'); ?></option>
                                <?php endforeach; ?>
                                <?php endif; ?>
                            </select>
                        </div>
                        <div class="form-group col-md-2">
                            <label class="font-weight-bold">排序</label>
                            <input type="number" class="form-control" id="groupPx" name="px" value="0" min="0">
                            <small class="form-text text-muted">越小越靠前</small>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="font-weight-bold">小组图标</label>
                        <div class="d-flex align-items-center gap-2">
                            <div id="groupIconPreview" class="w-56 h-56 d-flex of-hidden" style="border-radius: 10px ; background: #f5f5f5 ; align-items: center ; justify-content: center ; flex-shrink: 0 ; border: 1px solid #eee">
                                <i class="fas fa-image text-muted"></i>
                            </div>
                            <input type="text" class="form-control" id="groupIcon" name="icon" placeholder="留空则使用首字母头像" style="flex: 1;">
                            <button type="button" class="btn btn-outline-secondary" onclick="uploadGroupIcon()">
                                <i class="fas fa-upload"></i> 上传
                            </button>
                            <button type="button" class="btn btn-outline-danger" onclick="clearGroupIcon()" title="清空">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                        <small class="form-text text-muted">建议尺寸 200x200，支持 jpg/png/webp。仅接受 upload/ 路径或 http(s):// 开头</small>
                    </div>
                    <div class="form-group">
                        <label class="font-weight-bold">小组简介</label>
                        <textarea class="form-control" id="groupDesc" name="desc" rows="2" maxlength="255" placeholder="一句话介绍小组定位（最多 255 字）"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="saveGroup()">
                        <i class="fas fa-save"></i> 保存
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

{include file="app/manage/view/index/emlog_footer"}

<script>
function openGroupModal(id, name, px, bankuaiId, icon, desc) {
    document.getElementById('groupId').value = id || 0;
    document.getElementById('groupName').value = name || '';
    document.getElementById('groupPx').value = px || 0;
    document.getElementById('groupBankuai').value = bankuaiId || 0;
    document.getElementById('groupIcon').value = icon || '';
    document.getElementById('groupDesc').value = desc || '';
    document.getElementById('groupModalTitle').innerText = (id && id > 0) ? '编辑小组' : '新增小组';
    refreshIconPreview(icon || '');
    $('#groupModal').modal('show');
}

function refreshIconPreview(url) {
    var box = document.getElementById('groupIconPreview');
    if (!box) return;
    if (url) {
        var img = new Image();
        img.onload = function() {
            box.innerHTML = '';
            box.appendChild(img);
            img.style.width = '100%';
            img.style.height = '100%';
            img.style.objectFit = 'cover';
        };
        img.onerror = function() {
            box.innerHTML = '<i class="fas fa-image text-muted"></i>';
        };
        img.src = url;
    } else {
        box.innerHTML = '<i class="fas fa-image text-muted"></i>';
    }
}

// 图标输入框变化时实时预览
document.addEventListener('DOMContentLoaded', function() {
    var iconInput = document.getElementById('groupIcon');
    if (iconInput) {
        iconInput.addEventListener('input', function() {
            refreshIconPreview(this.value.trim());
        });
    }
});

function uploadGroupIcon() {
    var input = document.createElement('input');
    input.type = 'file';
    input.accept = 'image/*';
    input.onchange = function(e) {
        var file = e.target.files[0];
        if (!file) return;
        if (file.size > 10 * 1024 * 1024) {
            alert('图片不能超过 10MB');
            return;
        }
        var formData = new FormData();
        formData.append('file', file);
        var xhr = new XMLHttpRequest();
        xhr.open('POST', 'index.php?r=manage/File/upload&type=forum', true);
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4 && xhr.status == 200) {
                try {
                    var r = JSON.parse(xhr.responseText);
                    if (r.error === 0 && r.url) {
                        document.getElementById('groupIcon').value = r.url;
                        refreshIconPreview(r.url);
                    } else {
                        alert(r.message || '上传失败');
                    }
                } catch (e) {
                    alert('上传失败: ' + xhr.responseText.substring(0, 200));
                }
            }
        };
        xhr.send(formData);
    };
    input.click();
}

function clearGroupIcon() {
    document.getElementById('groupIcon').value = '';
    refreshIconPreview('');
}

function saveGroup() {
    var id = parseInt(document.getElementById('groupId').value) || 0;
    var name = document.getElementById('groupName').value.trim();
    var px = parseInt(document.getElementById('groupPx').value) || 0;
    var bankuaiId = parseInt(document.getElementById('groupBankuai').value) || 0;
    var icon = document.getElementById('groupIcon').value.trim();
    var desc = document.getElementById('groupDesc').value.trim();
    if (!name) { alert('请填写小组名称'); return; }

    var params = {
        id: id,
        groupname: name,
        px: px,
        bankuai_id: bankuaiId,
        icon: icon,
        desc: desc
    };
    var data = Object.keys(params).map(function(k) {
        return encodeURIComponent(k) + '=' + encodeURIComponent(params[k]);
    }).join('&');

    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'index.php?r=manage/forum/saveGroup', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            try {
                var r = JSON.parse(xhr.responseText);
                alert(r.info);
                if (r.status === 'y') {
                    $('#groupModal').modal('hide');
                    location.reload();
                }
            } catch (e) {
                alert('保存失败: ' + xhr.responseText.substring(0, 200));
            }
        }
    };
    xhr.send(data);
}

function delGroup(id) {
    if (!confirm('删除小组后，该小组下的帖子可能会失去归属，确定要删除吗？')) return;
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'index.php?r=manage/forum/deleteGroup&id=' + id, true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            try {
                var r = JSON.parse(xhr.responseText);
                alert(r.info);
                if (r.status === 'y') {
                    var row = document.getElementById('group-row-' + id);
                    if (row) row.style.display = 'none';
                }
            } catch (e) {
                alert('删除失败');
            }
        }
    };
    xhr.send();
}
</script>
