<?php
/**
 * HuSNS - 圈子管理后台页面
 */
?>
<div class="admin-page">
    <div class="page-header">
        <h2>圈子管理</h2>
        <a href="<?php echo Helper::url('admin/circles/add'); ?>" class="btn btn-primary">
            添加圈子
        </a>
    </div>
    
    <div class="search-form">
        <input type="hidden" name="r" value="admin/circles">
        <input type="text" name="keyword" value="<?php echo $this->escape($keyword ?? ''); ?>" placeholder="搜索圈子名称或描述">
        <select name="status">
            <option value="-1" <?php echo $status == -1 ? 'selected' : ''; ?>>全部状态</option>
            <option value="1" <?php echo $status == 1 ? 'selected' : ''; ?>>启用</option>
            <option value="0" <?php echo $status == 0 ? 'selected' : ''; ?>>禁用</option>
        </select>
        <button type="submit" class="btn">搜索</button>
    </div>
    
    <?php if ($this->hasFlash('success')): ?>
    <div class="alert alert-success"><?php echo $this->flash('success'); ?></div>
    <?php endif; ?>
    
    <?php if ($this->hasFlash('error')): ?>
    <div class="alert alert-error"><?php echo $this->flash('error'); ?></div>
    <?php endif; ?>
    
    <table class="data-table">
        <thead>
            <tr>
                <th>圈子头像</th>
                <th>圈子名称</th>
                <th>描述</th>
                <th>状态</th>
                <th>类型</th>
                <th>认证状态</th>
                <th>认证类型</th>
                <th>认证信息</th>
                <th>成员数</th>
                <th>帖子数</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($circles as $circle): ?>
            <tr>
                <td>
                    <img src="<?php echo $circle['avatar'] ? $this->uploadUrl($circle['avatar']) : $this->asset('images/default-circle-avatar.png'); ?>" 
                         alt="" style="width: 40px; height: 40px; border-radius: 50%;">
                </td>
                <td>
                    <strong><?php echo $this->escape($circle['name']); ?></strong>
                </td>
                <td><?php echo $this->escape(mb_substr($circle['description'], 0, 30)); ?>...</td>
                <td>
                    <span class="status-badge <?php echo $circle['status'] ? 'active' : 'inactive'; ?>">
                        <?php echo $circle['status'] ? '启用' : '禁用'; ?>
                    </span>
                </td>
                <td>
                    <span class="status-badge <?php echo empty($circle['is_private']) ? 'active' : 'inactive'; ?>">
                        <?php echo empty($circle['is_private']) ? '公开' : '私密'; ?>
                    </span>
                </td>
                <td>
                    <?php if ($circle['is_verified'] == 1): ?>
                    <span class="status-badge active">已认证</span>
                    <?php else: ?>
                    <span class="status-badge inactive">未认证</span>
                    <?php endif; ?>
                </td>
                <td>
                    <?php 
                    $verifyTypes = ['无', '官方认证', '企业认证', '个人认证'];
                    $verifyType = isset($circle['verify_type']) ? (int)$circle['verify_type'] : 0;
                    echo $verifyTypes[$verifyType] ?? '无';
                    ?>
                </td>
                <td><?php echo $this->escape($circle['verify_info'] ?? ''); ?></td>
                <td><?php echo $circle['member_count']; ?></td>
                <td><?php echo $circle['post_count']; ?></td>
                <td>
                    <button class="btn btn-sm" onclick="window.location.href='<?php echo Helper::url('admin/circles/edit?id=' . $circle['id']); ?>'">编辑</button>
                    <button class="btn btn-sm" onclick="window.location.href='<?php echo Helper::url('admin/circles/members?circle_id=' . $circle['id']); ?>'">成员管理</button>
                    <button class="btn btn-sm <?php echo $circle['is_verified'] == 1 ? 'btn-warning' : 'btn-success'; ?>" onclick="showVerifyModal(<?php echo $circle['id']; ?>, '<?php echo $this->escape($circle['name']); ?>', <?php echo $circle['is_verified'] == 1 ? '1' : '0'; ?>)">
                        <?php echo $circle['is_verified'] == 1 ? '取消认证' : '认证'; ?>
                    </button>
                    <button class="btn btn-sm btn-danger" onclick="deleteCircle(<?php echo $circle['id']; ?>)">删除</button>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    
    <?php if (empty($circles)): ?>
    <div style="text-align: center; padding: 40px; color: #999;">
        <p>暂无圈子数据</p>
    </div>
    <?php endif; ?>
    
    <?php if ($totalPages > 1): ?>
    <div class="pagination">
        <?php for ($i = 1; $i <= $totalPages; $i++): ?>
        <a href="?r=admin/circles&page=<?php echo $i; ?>&keyword=<?php echo urlencode($keyword ?? ''); ?>&status=<?php echo $status; ?>" class="<?php echo $i == $page ? 'active' : ''; ?>">
            <?php echo $i; ?>
        </a>
        <?php endfor; ?>
    </div>
    <?php endif; ?>
</div>

<div id="verifyModal" class="modal-overlay" style="display: none;">
    <div class="modal-content">
        <div class="modal-header">
            <h3 id="modalTitle">圈子认证</h3>
            <button class="modal-close" onclick="hideVerifyModal()">&times;</button>
        </div>
        <div class="modal-body">
            <input type="hidden" id="circleId">
            <input type="hidden" id="currentStatus">
            
            <div id="verifyForm" style="display: none;">
                <div class="form-group">
                    <label>认证类型</label>
                    <select id="verifyType">
                        <option value="1">官方认证</option>
                        <option value="2">企业认证</option>
                        <option value="3">个人认证</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>认证信息（例如：XX公司官方账号）</label>
                    <input type="text" id="verifyInfo" placeholder="请输入认证信息">
                </div>
                <p class="tip">认证信息将在圈子名称旁显示，让用户知道这是经过认证的圈子</p>
            </div>
            
            <div id="unverifyForm" style="display: none;">
                <p>确定要取消这个圈子的认证吗？</p>
            </div>
        </div>
        <div class="modal-footer">
            <button class="btn btn-secondary" onclick="hideVerifyModal()">取消</button>
            <button class="btn btn-primary" onclick="submitVerify()">确认</button>
        </div>
    </div>
</div>

<style>
.modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0,0,0,0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
}

.modal-content {
    background: #fff;
    border-radius: 8px;
    width: 90%;
    max-width: 450px;
    max-height: 80vh;
    overflow-y: auto;
}

.modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px 20px;
    border-bottom: 1px solid #eee;
}

.modal-header h3 {
    margin: 0;
}

.modal-close {
    background: none;
    border: none;
    font-size: 24px;
    cursor: pointer;
    color: #999;
}

.modal-body {
    padding: 20px;
}

.modal-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    padding: 15px 20px;
    border-top: 1px solid #eee;
}

.form-group {
    margin-bottom: 15px;
}

.form-group label {
    display: block;
    margin-bottom: 5px;
    font-weight: bold;
}

.form-group select,
.form-group input {
    width: 100%;
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
    box-sizing: border-box;
}

.tip {
    color: #999;
    font-size: 12px;
    margin-top: 10px;
}
</style>

<script>
var circleId = 0;
var currentStatus = 0;

function showVerifyModal(id, name, status) {
    circleId = id;
    currentStatus = status;
    
    var modal = document.getElementById('verifyModal');
    var title = document.getElementById('modalTitle');
    var verifyForm = document.getElementById('verifyForm');
    var unverifyForm = document.getElementById('unverifyForm');
    
    if (status == 1) {
        title.textContent = '取消认证';
        verifyForm.style.display = 'none';
        unverifyForm.style.display = 'block';
    } else {
        title.textContent = '圈子认证 - ' + name;
        verifyForm.style.display = 'block';
        unverifyForm.style.display = 'none';
        document.getElementById('verifyInfo').value = '';
        document.getElementById('verifyType').value = '1';
    }
    
    modal.style.display = 'flex';
}

function hideVerifyModal() {
    document.getElementById('verifyModal').style.display = 'none';
}

function submitVerify() {
    var modal = document.getElementById('verifyModal');
    var formData = new FormData();
    formData.append('id', circleId);
    formData.append('csrf_token', '<?php echo $_SESSION['csrf_token'] ?? ''; ?>');
    
    if (currentStatus == 1) {
        // 取消认证
        formData.append('verified', 0);
        formData.append('verify_type', 0);
        formData.append('verify_info', '');
    } else {
        // 进行认证
        formData.append('verified', 1);
        formData.append('verify_type', document.getElementById('verifyType').value);
        formData.append('verify_info', document.getElementById('verifyInfo').value);
    }
    
    fetch('<?php echo Helper::url('admin/circles/verify'); ?>', {
        method: 'POST',
        body: formData
    })
    .then(function(response) { return response.json(); })
    .then(function(res) {
        alert(res.message || (res.success ? '操作成功' : '操作失败'));
        window.location.reload();
    })
    .catch(function(err) {
        alert('操作失败');
        window.location.reload();
    });
}

function deleteCircle(id) {
    if (confirm('确定要删除这个圈子吗？')) {
        var formData = new FormData();
        formData.append('id', id);
        formData.append('csrf_token', '<?php echo $_SESSION['csrf_token'] ?? ''; ?>');
        
        fetch('<?php echo Helper::url('admin/circles/delete'); ?>', {
            method: 'POST',
            body: formData
        })
        .then(function(response) { return response.json(); })
        .then(function(res) {
            if (res.success) {
                alert(res.message);
                window.location.reload();
            } else {
                alert(res.message);
            }
        })
        .catch(function(err) {
            alert('操作失败');
        });
    }
}

function toggleVerify(id, targetStatus) {
    var action = targetStatus ? '认证' : '取消认证';
    if (confirm('确定要' + action + '这个圈子吗？')) {
        var formData = new FormData();
        formData.append('id', id);
        formData.append('verified', targetStatus);
        formData.append('csrf_token', '<?php echo $_SESSION['csrf_token'] ?? ''; ?>');
        
        fetch('<?php echo Helper::url('admin/circles/verify'); ?>', {
            method: 'POST',
            body: formData
        })
        .then(function(response) { return response.json(); })
        .then(function(res) {
            alert(res.message || (res.success ? '操作成功' : '操作失败'));
            window.location.reload();
        })
        .catch(function(err) {
            alert('操作失败');
            window.location.reload();
        });
    }
}
</script>