<?php
/**
 * 芋头CMS
 * ============================================================================
 * 版权所有 2016-2028 沅陵县乌托邦网络服务有限公司，并保留所有权利。
 * 网站地址: http://www.yutoucms.cn
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 芋头 <mxgsf@qq.com>
 * Date: 2026-5-20
 */

    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_action'])) {
        requireAdminCsrfToken(true);
        while (ob_get_level() > 0) { ob_end_clean(); }
        header('Content-Type: application/json; charset=utf-8');
        $ajaxAct = $_POST['ajax_action'];

        if ($ajaxAct === 'send_message') {
            $ids = json_decode((string) ($_POST['ids'] ?? '[]'), true);
            $ids = is_array($ids) ? array_values(array_unique(array_filter(array_map('intval', $ids)))) : [];
            $ids = array_slice($ids, 0, 200);
            $title = trim((string) ($_POST['title'] ?? ''));
            $content = trim((string) ($_POST['content'] ?? ''));
            if (!$ids || $title === '' || $content === '') { echo json_encode(['code'=>400,'msg'=>'请选择会员并填写消息标题和内容'], JSON_UNESCAPED_UNICODE); exit; }
            $placeholders = implode(',', array_fill(0, count($ids), '?'));
            $members = $db->fetchAll("SELECT id FROM {$db->table('member')} WHERE id IN ($placeholders)", $ids);
            $sent = 0;
            foreach ($members as $target) { if (sendMemberMessage(intval($target['id']), $title, $content, '后台通知')) { $sent++; } }
            addLog('发送消息', '会员管理', '向 '.$sent.' 位会员发送站内消息：'.$title);
            echo json_encode(['code'=>200,'msg'=>'已发送给 '.$sent.' 位会员'], JSON_UNESCAPED_UNICODE); exit;
        }

        if ($ajaxAct === 'delete') {
            $idsRaw = isset($_POST['ids']) ? $_POST['ids'] : '[]';
            $ids = json_decode($idsRaw, true);
            if (!is_array($ids)) { $ids = []; }
            $ids = array_map('intval', $ids);
            if (empty($ids)) { echo json_encode(['code'=>400,'msg'=>'请选择要删除的项']); exit; }
            $placeholders = implode(',', array_fill(0, count($ids), '?'));
            $db->query("DELETE FROM {$db->table('member')} WHERE id IN ($placeholders)", $ids);
            echo json_encode(['code'=>200,'msg'=>'已删除 '.count($ids).' 项']); exit;
        }

        if ($ajaxAct === 'show') {
            $idsRaw = isset($_POST['ids']) ? $_POST['ids'] : '[]';
            $ids = json_decode($idsRaw, true);
            if (!is_array($ids)) { $ids = []; }
            $ids = array_map('intval', $ids);
            if (empty($ids)) { echo json_encode(['code'=>400,'msg'=>'请选择']); exit; }
            $placeholders = implode(',', array_fill(0, count($ids), '?'));
            $db->query("UPDATE {$db->table('member')} SET is_enabled=1, update_time=? WHERE id IN ($placeholders)", array_merge([time()], $ids));
            echo json_encode(['code'=>200,'msg'=>'已显示']); exit;
        }

        if ($ajaxAct === 'hide') {
            $idsRaw = isset($_POST['ids']) ? $_POST['ids'] : '[]';
            $ids = json_decode($idsRaw, true);
            if (!is_array($ids)) { $ids = []; }
            $ids = array_map('intval', $ids);
            if (empty($ids)) { echo json_encode(['code'=>400,'msg'=>'请选择']); exit; }
            $placeholders = implode(',', array_fill(0, count($ids), '?'));
            $db->query("UPDATE {$db->table('member')} SET is_enabled=0, update_time=? WHERE id IN ($placeholders)", array_merge([time()], $ids));
            echo json_encode(['code'=>200,'msg'=>'已隐藏']); exit;
        }
    }


$action = isset($_GET['action']) ? $_GET['action'] : 'list';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    requireAdminCsrfToken($action === 'delete');
    if ($action === 'save') {
        $id = intval($_POST['id']);
        $data = [
            'username' => trim($_POST['username']),
            'nickname' => trim($_POST['nickname']),
            'email' => trim($_POST['email']),
            'phone' => trim($_POST['mobile']),
            'balance' => floatval($_POST['balance'] ?? 0),
            'is_enabled' => isset($_POST['status']) ? 1 : 0,
            'update_time' => time()
        ];
        if (!empty($_POST['password'])) {
            $data['password'] = password_hash(trim($_POST['password']), PASSWORD_DEFAULT);
        }
        if ($id > 0) {
            $db->update('member', $data, 'id = ?', [$id]);
            addLog('修改', '会员管理', '修改会员 ' . $data['username']);
            echo '<script>alert("保存成功");location.href="?act=member";</script>';
        } else {
            if (empty($data['username'])) {
                echo '<script>alert("用户名不能为空");history.back();</script>';
                exit;
            }
            $data['reg_time'] = time();
            $db->insert('member', $data);
            addLog('添加', '会员管理', '添加会员 ' . $data['username']);
            echo '<script>alert("添加成功");location.href="?act=member";</script>';
        }
        exit;
    }
    if ($action === 'delete') {
        $id = intval($_POST['id']);
        $m = $db->fetch("SELECT username FROM {$db->table('member')} WHERE id = ?", [$id]);
        $db->delete('member', 'id = ?', [$id]);
        addLog('删除', '会员管理', '删除会员 ' . ($m['username'] ?? $id));
        echo json_encode(['code' => 200, 'msg' => '删除成功']);
        exit;
    }
}

if ($action === 'list') {
    $page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
    $pageSize = 15;
    $offset = ($page - 1) * $pageSize;
    $lists = $db->fetchAll("SELECT * FROM {$db->table('member')} ORDER BY id DESC LIMIT {$offset}, {$pageSize}");
    $total = $db->fetch("SELECT COUNT(*) as cnt FROM {$db->table('member')}")['cnt'];
    $totalPages = ceil($total / $pageSize);

    $totalMembers = $db->fetch("SELECT COUNT(*) as cnt FROM {$db->table('member')}")['cnt'];
    $activeMembers = $db->fetch("SELECT COUNT(*) as cnt FROM {$db->table('member')} WHERE is_enabled = 1")['cnt'];
    ?>
    <div class="page-container fade-in">
        <div class="page-header">
            <div class="page-title">
                <div class="page-icon"><svg style="width:16px;height:16px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg></div>
                <div><h1>会员管理</h1><p style="font-size:12px;color:#64748b;margin:0;">列表页已统一为轻量后台结构，不再显示摘要卡。</p></div>
            </div>
            <div class="page-actions"><a href="?act=member&action=add" class="btn btn-primary">添加会员</a></div>
        </div>
        <div class="page-context-bar">
            <div class="page-context-item"><span class="page-context-label">会员总数</span><span class="page-context-value"><?php echo $totalMembers; ?> 人</span></div>
            <div class="page-context-item"><span class="page-context-label">正常会员</span><span class="page-context-value"><?php echo $activeMembers; ?> 人</span></div>
            <div class="page-context-item"><span class="page-context-label">分页设置</span><span class="page-context-value">每页 <?php echo $pageSize; ?> 条</span></div>
            <div class="page-context-item"><span class="page-context-label">支持操作</span><span class="page-context-value page-context-muted">启用、禁用、删除</span></div>
        </div>
        <div class="filter-bar">
            <button type="button" class="btn btn-primary" onclick="openMemberMessage(getSelectedIds())">发送消息</button>
            <button type="button" class="btn btn-secondary" onclick="batchAction('show')">批量启用</button>
            <button type="button" class="btn btn-secondary" onclick="batchAction('hide')">批量禁用</button>
            <button type="button" class="btn btn-ghost" style="color:#EF4444;" onclick="batchAction('delete')">批量删除</button>
        </div>
        <div class="content-card">
        <?php if (empty($lists)): ?>
        <div class="empty-state">
            <div class="empty-icon"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg></div>
            <h3>暂无会员</h3>
            <p>添加第一个会员</p>
            <a href="?act=member&action=add" class="btn btn-primary">添加会员</a>
        </div>
        <?php else: ?>
        <table class="data-table">
            <thead>
                <tr><th style="width:44px;text-align:center;"><input type="checkbox" onclick="toggleCheckAll(this)" style="accent-color:#2563eb;width:16px;height:16px;cursor:pointer;"></th><th style="width:50px;">ID</th><th>用户名</th><th>昵称</th><th>邮箱</th><th>手机</th><th style="width:120px;">余额</th><th style="width:150px;">注册时间</th><th style="width:100px;">状态</th><th style="width:250px;">操作</th></tr>
            </thead>
            <tbody>
                <?php foreach ($lists as $item): ?>
                <tr>
                    <td style="text-align:center;"><input type="checkbox" class="row-check" value="<?php echo $item['id']; ?>" style="accent-color:#2563eb;width:16px;height:16px;cursor:pointer;"></td>
                    <td class="id-cell"><?php echo $item['id']; ?></td>
                    <td style="font-weight:500;"><?php echo htmlspecialchars($item['username']); ?></td>
                    <td><?php echo htmlspecialchars($item['nickname'] ?: '-'); ?></td>
                    <td style="color:#64748b;"><?php echo htmlspecialchars($item['email'] ?: '-'); ?></td>
                    <td style="color:#64748b;"><?php echo htmlspecialchars($item['phone'] ?: '-'); ?></td>
                    <td style="font-weight:600;color:#f5a623;">¥<?php echo number_format(floatval($item['balance'] ?? 0), 2); ?></td>
                    <td style="font-size:12px;color:#64748b;"><?php echo $item['reg_time'] ? date('Y-m-d H:i', $item['reg_time']) : '-'; ?></td>
                    <td>
                        <?php if ($item['is_enabled']): ?>
                        <span class="badge badge-success">正常</span>
                        <?php else: ?>
                        <span class="badge badge-secondary">禁用</span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <div class="btn-group">
                            <button type="button" class="btn btn-secondary" onclick="openMemberMessage([<?php echo intval($item['id']); ?>])">消息</button>
                            <a href="?act=member&action=edit&id=<?php echo $item['id']; ?>" class="btn btn-primary"><svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg> 编辑</a>
                            <a href="javascript:delMember(<?php echo $item['id']; ?>);" class="btn btn-ghost" style="color:#EF4444;"><svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg> 删除</a>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <?php if ($totalPages > 1): ?>
        <div class="pagination">
            <?php for ($i = max(1, $page - 2); $i <= min($totalPages, $page + 2); $i++): ?>
            <a href="?act=member&page=<?php echo $i; ?>" <?php echo $i == $page ? 'class="active"' : ''; ?>><?php echo $i; ?></a>
            <?php endfor; ?>
        </div>
        <?php endif; ?>
    </div>
    <?php endif; ?>
    </div>
    <div class="member-message-modal" id="memberMessageModal" hidden><div class="member-message-card"><button type="button" class="member-message-close" onclick="closeMemberMessage()">&times;</button><small>MEMBER MESSAGE</small><h2>发送站内消息</h2><input type="hidden" id="memberMessageIds"><label>消息标题<input type="text" id="memberMessageTitle" maxlength="200" placeholder="请输入消息标题"></label><label>消息内容<textarea id="memberMessageContent" rows="6" maxlength="5000" placeholder="请输入消息内容"></textarea></label><div class="member-message-actions"><button type="button" class="btn btn-secondary" onclick="closeMemberMessage()">取消</button><button type="button" class="btn btn-primary" id="memberMessageSend" onclick="sendMemberMessageForm()">确认发送</button></div></div></div>
    <style>
    .page-context-bar{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px;margin-bottom:16px;}
    .page-context-item{background:#fff;border:1px solid #e2e8f0;border-radius:14px;padding:14px 16px;}
    .page-context-label{display:block;font-size:12px;color:#94a3b8;margin-bottom:6px;}
    .page-context-value{display:block;font-size:14px;font-weight:700;color:#1e293b;line-height:1.6;}
    .page-context-muted{color:#475569;font-weight:600;}
    .member-message-modal{position:fixed;inset:0;z-index:9999;display:flex;align-items:center;justify-content:center;padding:24px;background:rgba(15,23,42,.48);backdrop-filter:blur(4px)}.member-message-modal[hidden]{display:none}.member-message-card{position:relative;width:min(560px,100%);padding:26px;border-radius:20px;background:#fff;box-shadow:0 28px 70px rgba(15,23,42,.24)}.member-message-card small{color:#94a3b8;letter-spacing:.14em}.member-message-card h2{margin:7px 0 20px;color:#1e293b}.member-message-card label{display:block;margin-top:14px;color:#475569;font-size:12px}.member-message-card input,.member-message-card textarea{display:block;width:100%;margin-top:7px;padding:11px 13px;border:1px solid #dbe3ee;border-radius:10px;box-sizing:border-box}.member-message-close{position:absolute;right:18px;top:12px;border:0;background:none;color:#64748b;font-size:28px;cursor:pointer}.member-message-actions{display:flex;justify-content:flex-end;gap:10px;margin-top:20px}
    @media (max-width: 1200px){.page-context-bar{grid-template-columns:repeat(2,minmax(0,1fr));}}
    @media (max-width: 768px){.page-context-bar{grid-template-columns:1fr;}}
    </style>
    <script>
    var memberCsrfToken = <?php echo json_encode(getAdminCsrfToken()); ?>;
    function delMember(id) { if (confirm('确定删除?')) { fetch('?act=member&action=delete', {method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:'id='+id+'&csrf_token='+encodeURIComponent(memberCsrfToken)}).then(r=>r.json()).then(d=>{alert(d.msg);if(d.code==200)location.reload();}); } }
    
    function toggleCheckAll(cb) { document.querySelectorAll('.row-check').forEach(function(c){c.checked=cb.checked;}); }
    function getSelectedIds() { var ids=[]; document.querySelectorAll('.row-check:checked').forEach(function(c){ids.push(c.value);}); return ids; }
    function batchAction(action) {
        var ids = getSelectedIds();
        if (ids.length === 0) { alert('请先勾选要操作的项'); return; }
        if (action === 'delete') {
            if (!confirm('确定删除选中的 ' + ids.length + ' 项？')) return;
        }
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '?act=member&action=batch', true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4 && xhr.status === 200) {
                try { var d = JSON.parse(xhr.responseText); alert(d.msg||'操作完成'); if(d.code==200) location.reload(); }
                catch(e) { alert('JSON解析失败'); }
            }
        };
        xhr.send('ajax_action=' + action + '&ids=' + encodeURIComponent(JSON.stringify(ids)) + '&csrf_token=' + encodeURIComponent(memberCsrfToken));
    }

    function openMemberMessage(ids){if(!ids||!ids.length){alert('请先选择会员');return;}document.getElementById('memberMessageIds').value=JSON.stringify(ids);document.getElementById('memberMessageModal').hidden=false;document.getElementById('memberMessageTitle').focus();}
    function closeMemberMessage(){document.getElementById('memberMessageModal').hidden=true;}
    function sendMemberMessageForm(){var ids=document.getElementById('memberMessageIds').value,title=document.getElementById('memberMessageTitle').value.trim(),content=document.getElementById('memberMessageContent').value.trim(),button=document.getElementById('memberMessageSend');if(!title||!content){alert('请填写消息标题和内容');return;}button.disabled=true;fetch('?act=member',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:'ajax_action=send_message&ids='+encodeURIComponent(ids)+'&title='+encodeURIComponent(title)+'&content='+encodeURIComponent(content)+'&csrf_token='+encodeURIComponent(memberCsrfToken)}).then(function(r){return r.json();}).then(function(d){alert(d.msg);if(d.code===200){closeMemberMessage();document.getElementById('memberMessageTitle').value='';document.getElementById('memberMessageContent').value='';}button.disabled=false;}).catch(function(){alert('发送失败');button.disabled=false;});}
    document.addEventListener('keydown',function(e){if(e.key==='Escape')closeMemberMessage();});

</script>
    <?php
}

if ($action === 'add' || $action === 'edit') {
    $editData = ['id'=>'','username'=>'','password'=>'','nickname'=>'','email'=>'','mobile'=>'','is_enabled'=>1];
    if ($action === 'edit' && isset($_GET['id'])) {
        $editData = $db->fetch("SELECT * FROM {$db->table('member')} WHERE id = ?", [intval($_GET['id'])]);
        $editData['mobile'] = $editData['phone'] ?? '';
        $editData['password'] = '';
    }
    $isEdit = $action === 'edit';
    ?>
    <div class="page-container fade-in">
        <div class="page-header">
            <div class="page-title">
                <div class="page-icon"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="8.5" cy="7" r="4"/><line x1="20" y1="8" x2="20" y2="14"/><line x1="23" y1="11" x2="17" y2="11"/></svg></div>
                <div><h1><?php echo $isEdit ? '编辑会员' : '添加会员'; ?></h1><p style="font-size:12px;color:#64748b;margin:0;">填写会员信息</p></div>
            </div>
            <div class="page-actions"><a href="?act=member" class="btn btn-secondary">&larr; 返回</a></div>
        </div>
        <form method="post" action="?act=member&action=save">
            <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars(getAdminCsrfToken()); ?>">
            <input type="hidden" name="id" value="<?php echo $editData['id']; ?>">
            <div class="form-section">
                <div class="form-section-header"><svg style="width:16px;height:16px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg> 基本信息</div>
                <div class="form-section-body">
                    <div class="form-row">
                        <div class="form-group">
                            <label>用户名 <span class="required">*</span></label>
                            <input type="text" name="username" class="form-control" value="<?php echo htmlspecialchars($editData['username']); ?>" placeholder="<?php echo $isEdit ? '(不可修改)' : '请输入用户名'; ?>" <?php echo $isEdit ? 'readonly' : 'required'; ?> style="<?php echo $isEdit ? 'background:#f1f5f9;cursor:not-allowed;' : ''; ?>">
                        </div>
                        <div class="form-group">
                            <label><?php echo $isEdit ? '新密码（留空不变）' : '密码'; ?> <span class="required">*</span></label>
                            <input type="password" name="password" class="form-control" placeholder="<?php echo $isEdit ? '留空保持原密码' : '请输入密码'; ?>" <?php echo $isEdit ? '' : 'required'; ?>>
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group"><label>昵称</label><input type="text" name="nickname" class="form-control" value="<?php echo htmlspecialchars($editData['nickname']); ?>" placeholder=""></div>
                        <div class="form-group"><label>邮箱</label><input type="email" name="email" class="form-control" value="<?php echo htmlspecialchars($editData['email']); ?>" placeholder=""></div>
                    </div>
                    <div class="form-row">
                        <div class="form-group"><label>手机号</label><input type="text" name="mobile" class="form-control" value="<?php echo htmlspecialchars($editData['mobile']); ?>" placeholder=""></div>
                        <div class="form-group"><label>余额</label><input type="number" name="balance" class="form-control" value="<?php echo floatval($editData['balance'] ?? '0.00'); ?>" step="0.01" min="0" style="width:150px;"></div>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label>状态</label>
                            <label style="display:flex;align-items:center;gap:12px;cursor:pointer;padding-top:8px;">
                                <input type="checkbox" name="status" value="1" <?php echo $editData['is_enabled']?'checked':''; ?> id="statusToggle" style="display:none;">
                                <div id="statusSwitch" style="width:44px;height:24px;background:<?php echo $editData['is_enabled']?'#10b981':'#cbd5e1'; ?>;border-radius:12px;position:relative;transition:all 0.2s;"><div style="width:18px;height:18px;background:#fff;border-radius:50%;position:absolute;top:3px;left:<?php echo $editData['is_enabled']?'23px':'3px'; ?>;transition:all 0.2s;"></div></div>
                                <span id="statusLabel" style="font-weight:500;color:<?php echo $editData['is_enabled']?'#10b981':'#64748b'; ?>;"><?php echo $editData['is_enabled']?'正常':'禁用'; ?></span>
                            </label>
                        </div>
                    </div>
                </div>
            </div>
            <div class="form-actions"><button type="submit" class="btn btn-success btn-lg">OK <?php echo $isEdit?'保存':'添加'; ?></button><a href="?act=member" class="btn btn-secondary btn-lg">取消</a></div>
        </form>
    </div>
    <script>
    document.getElementById('statusToggle') && document.getElementById('statusToggle').addEventListener('change', function() {
        var sw = document.getElementById('statusSwitch');
        var lb = document.getElementById('statusLabel');
        if (this.checked) { sw.style.background = '#10b981'; sw.querySelector('div').style.left = '23px'; lb.textContent = '正常'; lb.style.color = '#10b981'; }
        else { sw.style.background = '#cbd5e1'; sw.querySelector('div').style.left = '3px'; lb.textContent = '禁用'; lb.style.color = '#64748b'; }
    });
    
    function toggleCheckAll(cb) { document.querySelectorAll('.row-check').forEach(function(c){c.checked=cb.checked;}); }
    function getSelectedIds() { var ids=[]; document.querySelectorAll('.row-check:checked').forEach(function(c){ids.push(c.value);}); return ids; }
    function batchAction(action) {
        var ids = getSelectedIds();
        if (ids.length === 0) { alert('请先勾选要操作的项'); return; }
        if (action === 'delete') {
            if (!confirm('确定删除选中的 ' + ids.length + ' 项？')) return;
        }
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '?act=member&action=batch', true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4 && xhr.status === 200) {
                try { var d = JSON.parse(xhr.responseText); alert(d.msg||'操作完成'); if(d.code==200) location.reload(); }
                catch(e) { alert('JSON解析失败'); }
            }
        };
        xhr.send('ajax_action=' + action + '&ids=' + encodeURIComponent(JSON.stringify(ids)));
    }

</script>
    <?php
}

if ($action === 'toggle') {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        http_response_code(405);
        echo json_encode(['code' => 405, 'msg' => '仅允许 POST 请求'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    requireAdminCsrfToken(true);
    header('Content-Type: application/json');
    $id = intval($_POST['id'] ?? 0);
    $newVal = intval($_POST['is_enabled'] ?? 0);
    $db->update('member', ['is_enabled' => $newVal, 'update_time' => time()], 'id = ?', [$id]);
    echo json_encode(['code' => 200, 'msg' => '更新成功']);
    exit;
}
?>
