<?php
/**
 * 用户管理模块 - 支持封禁功能
 */
$db = getDB();

// 分页
$pageNum = isset($_GET['p']) ? (int)$_GET['p'] : 1;
$pageSize = 20;
$offset = ($pageNum - 1) * $pageSize;

$total = $db->query("SELECT COUNT(*) as cnt FROM users")->fetch()['cnt'];
$users = $db->prepare("SELECT id, username, real_name, student_id, email, wechat_nickname, is_banned, ban_reason, ban_expire_at, created_at FROM users ORDER BY id DESC LIMIT ? OFFSET ?");
$users->execute([$pageSize, $offset]);
$users = $users->fetchAll();

$totalPages = ceil($total / $pageSize);

// 检查封禁状态（过期自动解封）
$now = date('Y-m-d H:i:s');
foreach ($users as $u) {
    if ($u['is_banned'] && $u['ban_expire_at'] && $u['ban_expire_at'] !== '9999-12-31 23:59:59' && $u['ban_expire_at'] < $now) {
        $stmt = $db->prepare("UPDATE users SET is_banned = 0, ban_reason = '', ban_expire_at = NULL WHERE id = ?");
        $stmt->execute([$u['id']]);
    }
}
?>

<div class="toolbar">
    <div class="toolbar-title">用户管理 <span style="font-size:13px;color:#9ca3af;">(<?php echo $total; ?>个用户)</span></div>
</div>

<div class="panel-card">
    <table class="data-table">
        <thead>
            <tr>
                <th>ID</th>
                <th>用户名</th>
                <th>姓名</th>
                <th>学号</th>
                <th>状态</th>
                <th>注册时间</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($users as $u): ?>
            <?php
            // 重新检查封禁状态
            $isBanned = $u['is_banned'];
            if ($isBanned && $u['ban_expire_at'] && $u['ban_expire_at'] !== '9999-12-31 23:59:59' && $u['ban_expire_at'] < $now) {
                $isBanned = 0;
            }
            ?>
            <tr>
                <td><?php echo $u['id']; ?></td>
                <td><?php echo htmlspecialchars($u['wechat_nickname'] ?: $u['username']); ?></td>
                <td><?php echo htmlspecialchars($u['real_name'] ?: '-'); ?></td>
                <td><?php echo htmlspecialchars($u['student_id'] ?: '-'); ?></td>
                <td>
                    <?php if ($isBanned): ?>
                    <span class="status-tag banned">已封禁</span>
                    <?php else: ?>
                    <span class="status-tag active">正常</span>
                    <?php endif; ?>
                </td>
                <td><?php echo substr($u['created_at'], 0, 16); ?></td>
                <td>
                    <div class="table-actions">
                        <button class="btn-sm btn-edit" onclick="viewUser(<?php echo $u['id']; ?>)">详情</button>
                        <?php if ($isBanned): ?>
                        <button class="btn-sm btn-unban" onclick="unbanUser(<?php echo $u['id']; ?>)">解封</button>
                        <?php else: ?>
                        <button class="btn-sm btn-ban" onclick="banUser(<?php echo $u['id']; ?>)">封禁</button>
                        <?php endif; ?>
                        <button class="btn-sm btn-del" onclick="deleteUser(<?php echo $u['id']; ?>)">删除</button>
                    </div>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>

    <!-- 分页 -->
    <?php if ($totalPages > 1): ?>
    <div style="display:flex; justify-content:center; gap:8px; padding:16px;">
        <?php for ($p = 1; $p <= $totalPages; $p++): ?>
        <button class="<?php echo $p === $pageNum ? 'btn-primary' : 'btn-secondary'; ?>" onclick="location.href='?page=users&p=<?php echo $p; ?>'" style="padding:6px 12px;"><?php echo $p; ?></button>
        <?php endfor; ?>
    </div>
    <?php endif; ?>
</div>

<script>
function viewUser(id) {
    apiRequest('get_user', {id: id}, function(res) {
        if (res.code === 1) {
            var d = res.data;
            var banInfo = '';
            if (d.is_banned == 1) {
                var expireText = d.ban_expire_at ? d.ban_expire_at : '永久';
                if (expireText === '9999-12-31 23:59:59') expireText = '永久';
                banInfo = '<div style="color:#ef4444;font-weight:600;"><strong>封禁状态:</strong> 已封禁</div>' +
                    '<div><strong>封禁原因:</strong> ' + (d.ban_reason || '-') + '</div>' +
                    '<div><strong>封禁到期:</strong> ' + expireText + '</div>';
            }
            var body = '<div style="font-size:14px;line-height:2;">' +
                '<div><strong>ID:</strong> ' + d.id + '</div>' +
                '<div><strong>用户名:</strong> ' + (d.username || '-') + '</div>' +
                '<div><strong>微信昵称:</strong> ' + (d.wechat_nickname || '-') + '</div>' +
                '<div><strong>姓名:</strong> ' + (d.real_name || '-') + '</div>' +
                '<div><strong>学号:</strong> ' + (d.student_id || '-') + '</div>' +
                '<div><strong>邮箱:</strong> ' + (d.email || '-') + '</div>' +
                '<div><strong>微信OpenID:</strong> ' + (d.wechat_openid || '-') + '</div>' +
                '<div><strong>注册时间:</strong> ' + (d.created_at || '-') + '</div>' +
                banInfo +
                '</div>';
            showModal('用户详情', body);
        } else {
            showToast(res.msg, 'error');
        }
    });
}

function banUser(id) {
    var body = '<div class="form-group">' +
        '<label class="form-label">封禁时长</label>' +
        '<select class="form-select" id="ban_duration">' +
        '<option value="1h">1小时</option>' +
        '<option value="6h">6小时</option>' +
        '<option value="1d">1天</option>' +
        '<option value="7d">7天</option>' +
        '<option value="30d">30天</option>' +
        '<option value="forever">永久</option>' +
        '</select>' +
        '</div>' +
        '<div class="form-group">' +
        '<label class="form-label">封禁原因</label>' +
        '<textarea class="form-textarea" id="ban_reason" placeholder="请输入封禁原因" rows="3"></textarea>' +
        '</div>';
    var footer = '<button class="btn-secondary" onclick="closeModal()">取消</button>' +
        '<button class="btn-primary" onclick="doBanUser(' + id + ')">确认封禁</button>';
    showModal('封禁用户', body, footer);
}

function doBanUser(id) {
    var duration = document.getElementById('ban_duration').value;
    var reason = document.getElementById('ban_reason').value;
    if (!reason) {
        showToast('请填写封禁原因', 'error');
        return;
    }
    apiRequest('ban_user', {id: id, duration: duration, reason: reason}, function(res) {
        if (res.code === 1) {
            showToast(res.msg, 'success');
            setTimeout(function() { location.reload(); }, 500);
        } else {
            showToast(res.msg, 'error');
        }
    });
}

function unbanUser(id) {
    window._unbanUserId = id;
    confirmAction('确认解封此用户？', 'doUnbanUser');
}

function doUnbanUser() {
    apiRequest('unban_user', {id: window._unbanUserId}, function(res) {
        if (res.code === 1) {
            showToast(res.msg, 'success');
            setTimeout(function() { location.reload(); }, 500);
        } else {
            showToast(res.msg, 'error');
        }
    });
}

function deleteUser(id) {
    window._deleteUserId = id;
    confirmAction('删除用户将同时删除其课表、成绩等所有数据，确认删除？', 'doDeleteUser');
}

function doDeleteUser() {
    apiRequest('delete_user', {id: window._deleteUserId}, function(res) {
        if (res.code === 1) {
            showToast(res.msg, 'success');
            setTimeout(function() { location.reload(); }, 500);
        } else {
            showToast(res.msg, 'error');
        }
    });
}
</script>