<?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'); 
        exit;
    }
}

// 处理编辑/添加
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'); 
            exit;
        } 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'); 
            exit;
        }
    }
}

// 获取用户组列表
$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");
}

// 统计数据
$stats = [
    'total' => count($groups),
    'active' => count(array_filter($groups, fn($g) => $g['status'] == 1)),
    'inactive' => count(array_filter($groups, fn($g) => $g['status'] == 0)),
];
?>

<?php if ($action == 'add' || ($action == 'edit' && $edit_group)): ?>
    <!-- 添加/编辑表单 -->
    <div class="form-container">
        <div class="page-header">
            <h2>
                <img src="https://api.iconify.design/mdi:<?php echo $action == 'add' ? 'account-group' : 'account-edit'; ?>.svg?color=%23667eea" width="26" height="26" style="vertical-align: middle; margin-right: 10px;" alt="">
                <?php echo $action == 'add' ? '添加用户组' : '编辑用户组'; ?>
            </h2>
            <a href="?page=user_groups" class="btn btn-secondary">
                <img src="https://api.iconify.design/mdi:arrow-left.svg?color=currentColor" width="18" height="18" style="vertical-align: middle; margin-right: 6px;" alt="">
                返回列表
            </a>
        </div>
        
        <?php if (isset($error)): ?>
            <div class="alert alert-error">
                <img src="https://api.iconify.design/mdi:alert-circle.svg?color=%23ef4444" width="20" height="20" style="margin-right: 8px;" alt="">
                <?php echo $error; ?>
            </div>
        <?php endif; ?>
        
        <div class="form-card">
            <form method="POST">
                <div class="form-group">
                    <label>
                        <img src="https://api.iconify.design/mdi:account-group.svg?color=%23667eea" width="18" height="18" style="margin-right: 6px;" alt="">
                        用户组名称 <span class="required">*</span>
                    </label>
                    <input type="text" name="name" required value="<?php echo htmlspecialchars($edit_group['name'] ?? ''); ?>" placeholder="例如：VIP会员">
                </div>
                <div class="form-group">
                    <label>
                        <img src="https://api.iconify.design/mdi:text-box.svg?color=%23667eea" width="18" height="18" style="margin-right: 6px;" alt="">
                        描述
                    </label>
                    <textarea name="description" rows="3" placeholder="用户组描述..."><?php echo htmlspecialchars($edit_group['description'] ?? ''); ?></textarea>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label>
                            <img src="https://api.iconify.design/mdi:cash.svg?color=%2310b981" width="18" height="18" style="margin-right: 6px;" alt="">
                            价格 (元)
                        </label>
                        <div class="input-with-prefix">
                            <span class="prefix">¥</span>
                            <input type="number" name="price" step="0.01" value="<?php echo $edit_group['price'] ?? 0; ?>" placeholder="0.00">
                        </div>
                        <small>0表示免费</small>
                    </div>
                    <div class="form-group">
                        <label>
                            <img src="https://api.iconify.design/mdi:percent.svg?color=%23f59e0b" width="18" height="18" style="margin-right: 6px;" alt="">
                            折扣 (%)
                        </label>
                        <input type="number" name="discount" step="0.01" value="<?php echo $edit_group['discount'] ?? 100; ?>" placeholder="100">
                        <small>100表示无折扣</small>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label>
                            <img src="https://api.iconify.design/mdi:calendar-clock.svg?color=%238b5cf6" width="18" height="18" style="margin-right: 6px;" alt="">
                            有效期 (天)
                        </label>
                        <input type="number" name="duration_days" value="<?php echo $edit_group['duration_days'] ?? 0; ?>" placeholder="0">
                        <small>0表示永久</small>
                    </div>
                    <div class="form-group">
                        <label>
                            <img src="https://api.iconify.design/mdi:sort.svg?color=%2306b6d4" width="18" height="18" style="margin-right: 6px;" alt="">
                            排序
                        </label>
                        <input type="number" name="sort" value="<?php echo $edit_group['sort'] ?? 0; ?>" placeholder="0">
                        <small>数字越小越靠前</small>
                    </div>
                </div>
                <div class="form-group">
                    <label>
                        <img src="https://api.iconify.design/mdi:toggle-switch.svg?color=%23667eea" width="18" height="18" style="margin-right: 6px;" alt="">
                        状态
                    </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">
                        <img src="https://api.iconify.design/mdi:content-save.svg?color=white" width="18" height="18" style="margin-right: 6px;" alt="">
                        保存
                    </button>
                    <a href="?page=user_groups" class="btn btn-secondary">
                        <img src="https://api.iconify.design/mdi:close.svg?color=currentColor" width="18" height="18" style="margin-right: 6px;" alt="">
                        取消
                    </a>
                </div>
            </form>
        </div>
    </div>
    
<?php else: ?>
    <!-- 用户组列表 -->
    <div class="groups-manager">
        <div class="page-header">
            <h2>
                <img src="https://api.iconify.design/mdi:account-group.svg?color=%23667eea" width="26" height="26" style="vertical-align: middle; margin-right: 10px;" alt="">
                用户组管理
            </h2>
            <a href="?page=user_groups&action=add" class="btn btn-primary">
                <img src="https://api.iconify.design/mdi:plus.svg?color=white" width="18" height="18" style="vertical-align: middle; margin-right: 6px;" alt="">
                添加用户组
            </a>
        </div>
        
        <!-- 统计卡片 -->
        <div class="stats-mini">
            <div class="stat-mini-item">
                <img src="https://api.iconify.design/mdi:account-group.svg?color=%23667eea" width="20" height="20" alt="">
                <span class="stat-label">总用户组</span>
                <span class="stat-value"><?php echo $stats['total']; ?></span>
            </div>
            <div class="stat-mini-item">
                <img src="https://api.iconify.design/mdi:check-circle.svg?color=%2310b981" width="20" height="20" alt="">
                <span class="stat-label">已启用</span>
                <span class="stat-value"><?php echo $stats['active']; ?></span>
            </div>
            <div class="stat-mini-item">
                <img src="https://api.iconify.design/mdi:close-circle.svg?color=%23ef4444" width="20" height="20" alt="">
                <span class="stat-label">已禁用</span>
                <span class="stat-value"><?php echo $stats['inactive']; ?></span>
            </div>
        </div>
        
        <?php if (empty($groups)): ?>
            <div class="empty-state">
                <img src="https://api.iconify.design/mdi:account-group-outline.svg?color=%239ca3af" width="64" height="64" alt="">
                <p>暂无用户组</p>
                <span>点击上方按钮添加用户组</span>
            </div>
        <?php else: ?>
            <div class="groups-grid">
                <?php foreach ($groups as $group): ?>
                    <div class="group-card <?php echo $group['status'] == 0 ? 'disabled' : ''; ?>">
                        <div class="group-card-header">
                            <div class="group-icon">
                                <img src="https://api.iconify.design/mdi:account-group.svg?color=%23667eea" width="32" height="32" alt="">
                            </div>
                            <div class="group-info">
                                <h3><?php echo htmlspecialchars($group['name']); ?></h3>
                                <span class="group-badge <?php echo $group['status'] ? 'active' : 'inactive'; ?>">
                                    <?php echo $group['status'] ? '启用' : '禁用'; ?>
                                </span>
                            </div>
                        </div>
                        <div class="group-card-body">
                            <?php if (!empty($group['description'])): ?>
                                <p class="group-description"><?php echo htmlspecialchars($group['description']); ?></p>
                            <?php else: ?>
                                <p class="group-description text-muted">暂无描述</p>
                            <?php endif; ?>
                            <div class="group-meta">
                                <div class="meta-item">
                                    <img src="https://api.iconify.design/mdi:cash.svg?color=%2310b981" width="16" height="16" alt="">
                                    <span><?php echo $group['price'] > 0 ? '¥' . number_format($group['price'], 2) : '免费'; ?></span>
                                </div>
                                <div class="meta-item">
                                    <img src="https://api.iconify.design/mdi:percent.svg?color=%23f59e0b" width="16" height="16" alt="">
                                    <span><?php echo $group['discount']; ?>折</span>
                                </div>
                                <div class="meta-item">
                                    <img src="https://api.iconify.design/mdi:calendar-clock.svg?color=%238b5cf6" width="16" height="16" alt="">
                                    <span><?php echo $group['duration_days'] ? $group['duration_days'] . '天' : '永久'; ?></span>
                                </div>
                                <div class="meta-item">
                                    <img src="https://api.iconify.design/mdi:sort.svg?color=%236b7280" width="16" height="16" alt="">
                                    <span>排序 <?php echo $group['sort']; ?></span>
                                </div>
                            </div>
                        </div>
                        <div class="group-card-footer">
                            <a href="?page=user_groups&action=edit&id=<?php echo $group['id']; ?>" class="btn-icon" title="编辑">
                                <img src="https://api.iconify.design/mdi:pencil.svg?color=%23667eea" width="20" height="20" alt="">
                            </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="删除">
                                    <img src="https://api.iconify.design/mdi:delete.svg?color=%23ef4444" width="20" height="20" alt="">
                                </a>
                            <?php else: ?>
                                <span class="btn-icon disabled" title="默认用户组不可删除">
                                    <img src="https://api.iconify.design/mdi:lock.svg?color=%239ca3af" width="20" height="20" alt="">
                                </span>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
        
        <div class="info-note">
            <img src="https://api.iconify.design/mdi:information.svg?color=%23667eea" width="18" height="18" style="vertical-align: middle; margin-right: 6px;" alt="">
            <span>价格 > 0 的用户组可以删除；价格为0的为默认用户组，不可删除。</span>
        </div>
    </div>
<?php endif; ?>

<style>
/* 基础变量 */
:root {
    --primary-color: #667eea;
    --primary-hover: #5a67d8;
    --danger-color: #ef4444;
    --success-color: #10b981;
    --warning-color: #f59e0b;
    --bg-primary: #ffffff;
    --bg-secondary: #f9fafb;
    --text-primary: #1f2937;
    --text-secondary: #6b7280;
    --text-muted: #9ca3af;
    --border-color: #e5e7eb;
    --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
    --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    --radius-sm: 8px;
    --radius-md: 12px;
    --radius-lg: 16px;
}

/* 表单容器 */
.form-container {
    max-width: 600px;
}
.form-card {
    background: var(--bg-primary);
    border-radius: var(--radius-lg);
    padding: 30px;
    border: 1px solid var(--border-color);
    box-shadow: var(--shadow-sm);
}
.form-group {
    margin-bottom: 20px;
}
.form-group label {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
    font-weight: 500;
    color: var(--text-primary);
    font-size: 14px;
}
.form-group label img {
    display: inline-block;
}
.required {
    color: var(--danger-color);
    margin-left: 2px;
}
.form-group input,
.form-group textarea,
.form-group select {
    width: 100%;
    padding: 12px 16px;
    border: 1.5px solid var(--border-color);
    border-radius: var(--radius-md);
    font-size: 14px;
    background: var(--bg-primary);
    color: var(--text-primary);
    transition: all 0.2s;
}
.form-group input:focus,
.form-group textarea:focus,
.form-group select:focus {
    outline: none;
    border-color: var(--primary-color);
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
.form-group small {
    display: block;
    margin-top: 6px;
    font-size: 12px;
    color: var(--text-muted);
}
.form-row {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
}
.input-with-prefix {
    display: flex;
    align-items: center;
    border: 1.5px solid var(--border-color);
    border-radius: var(--radius-md);
    overflow: hidden;
    transition: all 0.2s;
    background: var(--bg-primary);
}
.input-with-prefix:focus-within {
    border-color: var(--primary-color);
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
.input-with-prefix .prefix {
    padding: 12px 16px;
    background: var(--bg-secondary);
    color: var(--text-secondary);
    font-weight: 500;
    border-right: 1px solid var(--border-color);
}
.input-with-prefix input {
    flex: 1;
    border: none !important;
    border-radius: 0 !important;
    padding: 12px 16px;
}
.input-with-prefix input:focus {
    outline: none;
    box-shadow: none;
}
.form-actions {
    margin-top: 30px;
    display: flex;
    gap: 12px;
}

/* 按钮 */
.btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: 10px 20px;
    border-radius: var(--radius-md);
    font-size: 14px;
    font-weight: 500;
    text-decoration: none;
    cursor: pointer;
    transition: all 0.2s;
    border: 1px solid transparent;
    gap: 6px;
}
.btn img {
    display: inline-block;
}
.btn-primary {
    background: var(--primary-color);
    color: white;
    box-shadow: 0 2px 4px rgba(102, 126, 234, 0.2);
}
.btn-primary:hover {
    background: var(--primary-hover);
    transform: translateY(-1px);
    box-shadow: 0 4px 8px rgba(102, 126, 234, 0.3);
}
.btn-secondary {
    background: var(--bg-primary);
    color: var(--text-primary);
    border-color: var(--border-color);
}
.btn-secondary:hover {
    background: var(--bg-secondary);
    border-color: var(--text-muted);
}
.btn-icon {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 36px;
    height: 36px;
    border-radius: var(--radius-sm);
    background: var(--bg-secondary);
    transition: all 0.2s;
}
.btn-icon:hover {
    background: var(--border-color);
    transform: translateY(-1px);
}
.btn-icon.disabled {
    opacity: 0.5;
    cursor: not-allowed;
}
.btn-icon.disabled:hover {
    background: var(--bg-secondary);
    transform: none;
}

/* 提示消息 */
.alert {
    display: flex;
    align-items: center;
    padding: 14px 20px;
    border-radius: var(--radius-md);
    margin-bottom: 24px;
    font-size: 14px;
}
.alert-error {
    background: #fef2f2;
    border: 1px solid #fecaca;
    color: #991b1b;
}
.alert img {
    display: inline-block;
}

/* 页面头部 */
.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
}
.page-header h2 {
    display: flex;
    align-items: center;
    font-size: 24px;
    font-weight: 600;
    color: var(--text-primary);
    margin: 0;
}
.page-header h2 img {
    display: inline-block;
}

/* 统计卡片 */
.stats-mini {
    display: flex;
    gap: 16px;
    margin-bottom: 24px;
    flex-wrap: wrap;
}
.stat-mini-item {
    display: flex;
    align-items: center;
    gap: 10px;
    background: linear-gradient(135deg, rgba(102, 126, 234, 0.08) 0%, rgba(102, 126, 234, 0.02) 100%);
    padding: 12px 20px;
    border-radius: var(--radius-md);
    border: 1px solid rgba(102, 126, 234, 0.15);
}
.stat-mini-item .stat-label {
    font-size: 14px;
    color: var(--text-secondary);
}
.stat-mini-item .stat-value {
    font-size: 20px;
    font-weight: 700;
    color: var(--primary-color);
    margin-left: 4px;
}

/* 用户组卡片网格 */
.groups-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
    gap: 20px;
}
.group-card {
    background: var(--bg-primary);
    border-radius: var(--radius-lg);
    border: 1px solid var(--border-color);
    overflow: hidden;
    transition: all 0.2s;
    display: flex;
    flex-direction: column;
}
.group-card:hover {
    box-shadow: var(--shadow-md);
    transform: translateY(-2px);
}
.group-card.disabled {
    opacity: 0.7;
}
.group-card-header {
    display: flex;
    align-items: flex-start;
    padding: 20px 20px 16px;
    border-bottom: 1px solid var(--border-color);
}
.group-icon {
    width: 48px;
    height: 48px;
    background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(102, 126, 234, 0.05) 100%);
    border-radius: var(--radius-md);
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 12px;
}
.group-info {
    flex: 1;
    min-width: 0;
}
.group-info h3 {
    font-size: 16px;
    font-weight: 600;
    margin: 0 0 6px;
    color: var(--text-primary);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
.group-badge {
    display: inline-block;
    padding: 3px 10px;
    border-radius: 20px;
    font-size: 11px;
    font-weight: 500;
}
.group-badge.active {
    background: #d1fae5;
    color: #065f46;
}
.group-badge.inactive {
    background: #fee2e2;
    color: #991b1b;
}
.group-card-body {
    padding: 16px 20px;
    flex: 1;
}
.group-description {
    font-size: 14px;
    color: var(--text-secondary);
    margin: 0 0 16px;
    line-height: 1.5;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    min-height: 42px;
}
.text-muted {
    color: var(--text-muted);
    font-style: italic;
}
.group-meta {
    display: flex;
    flex-wrap: wrap;
    gap: 12px 16px;
}
.meta-item {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 13px;
    color: var(--text-secondary);
}
.meta-item img {
    opacity: 0.7;
}
.group-card-footer {
    display: flex;
    justify-content: flex-end;
    gap: 8px;
    padding: 12px 20px 20px;
    border-top: 1px solid var(--border-color);
}

/* 空状态 */
.empty-state {
    text-align: center;
    padding: 60px 20px;
    background: var(--bg-primary);
    border-radius: var(--radius-lg);
    border: 1px solid var(--border-color);
}
.empty-state img {
    opacity: 0.5;
    margin-bottom: 16px;
}
.empty-state p {
    color: var(--text-secondary);
    font-size: 16px;
    font-weight: 500;
    margin: 0 0 4px;
}
.empty-state span {
    color: var(--text-muted);
    font-size: 14px;
}

/* 提示信息 */
.info-note {
    margin-top: 24px;
    padding: 14px 20px;
    background: rgba(102, 126, 234, 0.06);
    border-radius: var(--radius-md);
    border: 1px solid rgba(102, 126, 234, 0.15);
    display: flex;
    align-items: center;
    color: var(--text-secondary);
    font-size: 14px;
}
.info-note img {
    display: inline-block;
}

/* 响应式 */
@media (max-width: 768px) {
    .form-row {
        grid-template-columns: 1fr;
        gap: 0;
    }
    .groups-grid {
        grid-template-columns: 1fr;
    }
    .page-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 12px;
    }
    .stats-mini {
        flex-direction: column;
    }
}
</style>