<?php
requireAdmin();

$action = $_GET['action'] ?? 'list';
$group_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

// 处理删除
if ($action == 'delete' && $group_id > 0) {
    // 检查是否有关联用户
    $check = $db->fetchOne("SELECT id FROM users WHERE group_id = $group_id LIMIT 1");
    if ($check) {
        $error = '该用户组还有关联用户，无法删除';
    } else {
        $db->query("DELETE FROM user_groups WHERE id = $group_id");
        redirect('?page=user_groups');
    }
}

// 处理编辑/添加
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $price = floatval($_POST['price'] ?? 0);
    $discount = floatval($_POST['discount'] ?? 100);
    $duration_days = intval($_POST['duration_days'] ?? 0);
    $sort = intval($_POST['sort'] ?? 0);
    $status = intval($_POST['status'] ?? 1);
    
    if (empty($name)) {
        $error = '用户组名称不能为空';
    } else {
        if ($action == 'edit' && $group_id > 0) {
            $db->query("UPDATE user_groups SET name='$name', description='$description', price=$price, discount=$discount, duration_days=$duration_days, sort=$sort, status=$status WHERE id=$group_id");
            redirect('?page=user_groups');
        } elseif ($action == 'add') {
            $db->query("INSERT INTO user_groups (name, description, price, discount, duration_days, sort, status) VALUES ('$name', '$description', $price, $discount, $duration_days, $sort, $status)");
            redirect('?page=user_groups');
        }
    }
}

// 获取用户组列表
$groups = $db->fetchAll("SELECT * FROM user_groups ORDER BY sort ASC, id ASC");

// 编辑模式获取数据
$edit_group = null;
if ($action == 'edit' && $group_id > 0) {
    $edit_group = $db->fetchOne("SELECT * FROM user_groups WHERE id = $group_id");
}
?>

<?php if ($action == 'add' || ($action == 'edit' && $edit_group)): ?>
    <!-- 添加/编辑表单 -->
    <div class="form-container">
        <div class="page-header">
            <h2><?php echo $action == 'add' ? '添加用户组' : '编辑用户组'; ?></h2>
            <a href="?page=user_groups" class="btn btn-secondary">返回列表</a>
        </div>
        
        <?php if (isset($error)): ?>
            <div class="alert alert-error"><?php echo $error; ?></div>
        <?php endif; ?>
        
        <div class="form-card">
            <form method="POST">
                <div class="form-group">
                    <label>用户组名称 *</label>
                    <input type="text" name="name" required value="<?php echo htmlspecialchars($edit_group['name'] ?? ''); ?>">
                </div>
                <div class="form-group">
                    <label>描述</label>
                    <textarea name="description" rows="3"><?php echo htmlspecialchars($edit_group['description'] ?? ''); ?></textarea>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label>价格 (元)</label>
                        <input type="number" name="price" step="0.01" value="<?php echo $edit_group['price'] ?? 0; ?>">
                        <small>0表示免费</small>
                    </div>
                    <div class="form-group">
                        <label>折扣 (%)</label>
                        <input type="number" name="discount" step="0.01" value="<?php echo $edit_group['discount'] ?? 100; ?>">
                        <small>100表示无折扣</small>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label>有效期 (天)</label>
                        <input type="number" name="duration_days" value="<?php echo $edit_group['duration_days'] ?? 0; ?>">
                        <small>0表示永久</small>
                    </div>
                    <div class="form-group">
                        <label>排序</label>
                        <input type="number" name="sort" value="<?php echo $edit_group['sort'] ?? 0; ?>">
                    </div>
                </div>
                <div class="form-group">
                    <label>状态</label>
                    <select name="status">
                        <option value="1" <?php echo (isset($edit_group['status']) && $edit_group['status'] == 1) ? 'selected' : ''; ?>>启用</option>
                        <option value="0" <?php echo (isset($edit_group['status']) && $edit_group['status'] == 0) ? 'selected' : ''; ?>>禁用</option>
                    </select>
                </div>
                <div class="form-actions">
                    <button type="submit" class="btn btn-primary">保存</button>
                    <a href="?page=user_groups" class="btn btn-secondary">取消</a>
                </div>
            </form>
        </div>
    </div>
    
<?php else: ?>
    <!-- 用户组列表 -->
    <div class="groups-manager">
        <div class="page-header">
            <h2>用户组管理</h2>
            <a href="?page=user_groups&action=add" class="btn btn-primary">+ 添加用户组</a>
        </div>
        
        <div class="table-container">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>名称</th>
                        <th>描述</th>
                        <th>价格</th>
                        <th>折扣</th>
                        <th>有效期</th>
                        <th>排序</th>
                        <th>状态</th>
                        <th>操作</th>
                    </thead>
                <tbody>
                    <?php if (empty($groups)): ?>
                        <tr><td colspan="9" style="text-align: center;">暂无用户组</td></tr>
                    <?php else: ?>
                        <?php foreach ($groups as $group): ?>
                            <tr>
                                <td><?php echo $group['id']; ?></td>
                                <td><strong><?php echo htmlspecialchars($group['name']); ?></strong></td>
                                <td><?php echo htmlspecialchars(mb_substr($group['description'] ?? '', 0, 30)); ?></td>
                                <td>¥<?php echo number_format($group['price'], 2); ?></td>
                                <td><?php echo $group['discount']; ?>折</td>
                                <td><?php echo $group['duration_days'] ? $group['duration_days'] . '天' : '永久'; ?></td>
                                <td><?php echo $group['sort']; ?></td>
                                <td>
                                    <span class="status-badge status-<?php echo $group['status'] ? 'active' : 'inactive'; ?>">
                                        <?php echo $group['status'] ? '启用' : '禁用'; ?>
                                    </span>
                                </td>
                                <td>
                                    <a href="?page=user_groups&action=edit&id=<?php echo $group['id']; ?>" class="btn-icon" title="编辑">✏️</a>
                                    <?php if ($group['price'] > 0): ?>
                                        <a href="?page=user_groups&action=delete&id=<?php echo $group['id']; ?>" class="btn-icon" onclick="return confirm('确定删除此用户组吗？')" title="删除">🗑️</a>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        <div class="info-note">
            <small>💡 提示：价格 > 0 的用户组可以删除；价格为0的为默认用户组，不可删除。</small>
        </div>
    </div>
<?php endif; ?>

<style>
.form-container {
    max-width: 600px;
}
.form-card {
    background: var(--bg-primary);
    border-radius: var(--radius-md);
    padding: 30px;
    border: 1px solid var(--border-color);
}
.form-row {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
}
.form-actions {
    margin-top: 20px;
    display: flex;
    gap: 10px;
}
.btn-icon {
    background: none;
    border: none;
    cursor: pointer;
    font-size: 18px;
    padding: 4px 8px;
    border-radius: 4px;
}
.btn-icon:hover {
    background: var(--bg-secondary);
}
.status-badge {
    padding: 3px 8px;
    border-radius: 20px;
    font-size: 12px;
}
.status-active {
    background: #d1fae5;
    color: #065f46;
}
.status-inactive {
    background: #fee2e2;
    color: #991b1b;
}
.info-note {
    margin-top: 15px;
    padding: 10px;
    background: var(--bg-secondary);
    border-radius: var(--radius-sm);
}
</style>