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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($action === 'save') {
        $id = intval($_POST['id']);
        $data = [
            'group_name' => trim($_POST['group_name']),
            'group_desc' => trim($_POST['group_desc']),
            'points_rate' => intval($_POST['points_rate']),
            'discount_rate' => floatval($_POST['discount_rate']),
            'is_default' => isset($_POST['is_default']) ? 1 : 0,
            'sort_order' => intval($_POST['sort_order']),
            'create_time' => time()
        ];
        if (empty($data['group_name'])) {
            echo '<script>alert("组名称不能为空");history.back();</script>';
            exit;
        }
        if ($id > 0) {
            $db->update('member_group', $data, 'id = ?', [$id]);
            addLog('修改', '会员组管理', '修改会员组 ' . $data['group_name']);
            echo '<script>alert("保存成功");location.href="?act=member_group";</script>';
        } else {
            $db->insert('member_group', $data);
            addLog('添加', '会员组管理', '添加会员组 ' . $data['group_name']);
            echo '<script>alert("添加成功");location.href="?act=member_group";</script>';
        }
        exit;
    }
    if ($action === 'delete') {
        $id = intval($_POST['id']);
        $g = $db->fetch("SELECT group_name FROM {$db->table('member_group')} WHERE id = ?", [$id]);
        $db->delete('member_group', 'id = ?', [$id]);
        addLog('删除', '会员组管理', '删除会员组 ' . ($g['group_name'] ?? $id));
        echo json_encode(['code' => 200, 'msg' => '删除成功']);
        exit;
    }
}

if ($action === 'list') {
    $lists = $db->fetchAll("SELECT * FROM {$db->table('member_group')} ORDER BY sort_order ASC, id DESC");
    $totalGroups = $db->fetch("SELECT COUNT(*) as cnt FROM {$db->table('member_group')}")['cnt'];
    $defaultGroup = $db->fetch("SELECT COUNT(*) as cnt FROM {$db->table('member_group')} WHERE is_default = 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 $totalGroups; ?></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="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg></div>
            <div class="stat-info"><div class="stat-value"><?php echo $defaultGroup; ?></div><div class="stat-label">默认组</div></div>
        </div>
    </div>
    <div class="filter-bar">
        <a href="?act=member_group&action=add" class="btn btn-primary"><svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg></i> 添加会员组</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_group&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 style="width:70px;">积分倍率</th><th style="width:70px;">折扣率</th><th style="width:70px;">默认</th><th style="width:60px;">排序</th><th style="width:200px;">操作</th></tr>
            </thead>
            <tbody>
                <?php foreach ($lists as $item): ?>
                <tr>
                    <td class="id-cell"><?php echo $item['id']; ?></td>
                    <td style="font-weight:600;"><?php echo htmlspecialchars($item['group_name']); ?></td>
                    <td style="color:#64748b;font-size:12px;"><?php echo htmlspecialchars($item['group_desc'] ?: '-'); ?></td>
                    <td style="font-family:monospace;"><?php echo $item['points_rate']; ?>%</td>
                    <td style="font-family:monospace;"><?php echo floatval($item['discount_rate']) * 10; ?>折</td>
                    <td>
                        <?php if ($item['is_default']): ?>
                        <span class="badge badge-success">默认</span>
                        <?php else: ?>
                        <span style="color:#cbd5e1;font-size:12px;">-</span>
                        <?php endif; ?>
                    </td>
                    <td style="font-family:monospace;"><?php echo $item['sort_order']; ?></td>
                    <td>
                        <div class="btn-group">
                            <a href="?act=member_group&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:delGroup(<?php echo $item['id']; ?>);" class="btn btn-sm btn-danger"><svg style="width:12px;height:12px;" 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 endif; ?>
    </div>
    <script>
    function delGroup(id) { if (confirm('确定删除?')) { fetch('?act=member_group&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();}); } }
    </script>
    <?php
}

if ($action === 'add' || $action === 'edit') {
    $editData = ['id'=>'','group_name'=>'','group_desc'=>'','points_rate'=>100,'discount_rate'=>10.0,'is_default'=>0,'sort_order'=>100];
    if ($action === 'edit' && isset($_GET['id'])) {
        $editData = $db->fetch("SELECT * FROM {$db->table('member_group')} WHERE id = ?", [intval($_GET['id'])]);
    }
    $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="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></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_group" class="btn btn-secondary">&larr; 返回</a></div>
        </div>
        <form method="post" action="?act=member_group&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-group">
                        <label>组名称 <span class="required">*</span></label>
                        <input type="text" name="group_name" class="form-control" value="<?php echo htmlspecialchars($editData['group_name']); ?>" placeholder="如：VIP会员" required>
                    </div>
                    <div class="form-group">
                        <label>描述</label>
                        <input type="text" name="group_desc" class="form-control" value="<?php echo htmlspecialchars($editData['group_desc']); ?>" placeholder="简要描述">
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label>积分倍率</label>
                            <input type="number" name="points_rate" class="form-control" value="<?php echo $editData['points_rate']; ?>" min="0" style="width:120px;">
                            <small style="color:#94a3b8;">消费1元获取多少积分，默认100</small>
                        </div>
                        <div class="form-group">
                            <label>折扣率</label>
                            <input type="number" name="discount_rate" class="form-control" value="<?php echo floatval($editData['discount_rate']); ?>" min="0" max="10" step="0.1" style="width:120px;">
                            <small style="color:#94a3b8;">1.0=原价，0.8=8折，范围0-10</small>
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label>排序</label>
                            <input type="number" name="sort_order" class="form-control" value="<?php echo $editData['sort_order']; ?>" min="0" style="width:120px;">
                        </div>
                        <div class="form-group">
                            <label>&nbsp;</label>
                            <label style="display:flex;align-items:center;gap:12px;cursor:pointer;padding-top:8px;">
                                <input type="checkbox" name="is_default" value="1" <?php echo $editData['is_default']?'checked':''; ?> id="defaultToggle" style="display:none;">
                                <div id="defaultSwitch" style="width:44px;height:24px;background:<?php echo $editData['is_default']?'#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_default']?'23px':'3px'; ?>;transition:all 0.2s;"></div></div>
                                <span id="defaultLabel" style="font-weight:500;color:<?php echo $editData['is_default']?'#10b981':'#64748b'; ?>;"><?php echo $editData['is_default']?'默认组':'非默认'; ?></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_group" class="btn btn-secondary btn-lg">取消</a></div>
        </form>
    </div>
    <script>
    document.getElementById('defaultToggle') && document.getElementById('defaultToggle').addEventListener('change', function() {
        var sw = document.getElementById('defaultSwitch');
        var lb = document.getElementById('defaultLabel');
        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'; }
    });
    </script>
    <?php
}
?>

