<?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'])) {
        while (ob_get_level() > 0) { ob_end_clean(); }
        header('Content-Type: application/json; charset=utf-8');
        $ajaxAct = $_POST['ajax_action'];

        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 status=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 status=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') {
    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'] = md5(trim($_POST['password']));
        }
        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="stats-grid">
        <div class="stat-card">
            <div class="stat-icon" style="background:#eff6ff;color:#2563eb;"><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>
            <div class="stat-info"><div class="stat-value"><?php echo $totalMembers; ?></div><div class="stat-label">会员总数</div></div>
        </div>
        <div class="stat-card">
            <div class="stat-icon" style="background:#ecfdf5;color:#10b981;"><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"/><polyline points="17 11 19 13 23 9"/></svg></div>
            <div class="stat-info"><div class="stat-value"><?php echo $activeMembers; ?></div><div class="stat-label">正常会员</div></div>
        </div>
    </div>
    <div class="filter-bar">
        <a href="?act=member&action=add" class="btn btn-primary"><svg style="width:14px;height:14px;" 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> 添加会员</a>
    </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: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): ?>
                <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><tr>
                    <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">
                            <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>
    <script>
    function delMember(id) { if (confirm('确定删除?')) { fetch('?act=member&action=delete', {method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:'id='+id}).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)));
    }

</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="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') {
    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;
}
?>

