102 lines
3.1 KiB
Dart
102 lines
3.1 KiB
Dart
import 'dart:io';
|
|
import 'package:supabase_flutter/supabase_flutter.dart';
|
|
|
|
class TeamController {
|
|
final _supabase = Supabase.instance.client;
|
|
|
|
// 1. STREAM (Realtime)
|
|
Stream<List<Map<String, dynamic>>> get teamsStream {
|
|
final userId = _supabase.auth.currentUser?.id;
|
|
|
|
if (userId == null) return const Stream.empty();
|
|
|
|
return _supabase
|
|
.from('teams')
|
|
.stream(primaryKey: ['id'])
|
|
.eq('user_id', userId); // ✅ Bem feito, este já estava certo!
|
|
}
|
|
|
|
// 2. CRIAR (Agora guarda o dono da equipa!)
|
|
Future<void> createTeam(String name, String season, File? imageFile) async {
|
|
try {
|
|
final userId = _supabase.auth.currentUser?.id;
|
|
if (userId == null) throw Exception("Utilizador não autenticado.");
|
|
|
|
String? uploadedImageUrl;
|
|
|
|
// Se o utilizador escolheu uma imagem, fazemos o upload primeiro
|
|
if (imageFile != null) {
|
|
final fileName = '${userId}_${DateTime.now().millisecondsSinceEpoch}.png';
|
|
final storagePath = 'teams/$fileName';
|
|
|
|
await _supabase.storage.from('avatars').upload(
|
|
storagePath,
|
|
imageFile,
|
|
fileOptions: const FileOptions(cacheControl: '3600', upsert: true)
|
|
);
|
|
|
|
uploadedImageUrl = _supabase.storage.from('avatars').getPublicUrl(storagePath);
|
|
}
|
|
|
|
// Agora insere a equipa na base de dados com o ID DO DONO!
|
|
await _supabase.from('teams').insert({
|
|
'user_id': userId, // 👈 CRUCIAL: Diz à base de dados de quem é esta equipa!
|
|
'name': name,
|
|
'season': season,
|
|
'image_url': uploadedImageUrl ?? '',
|
|
'is_favorite': false,
|
|
});
|
|
print("✅ Equipa guardada no Supabase com dono associado!");
|
|
} catch (e) {
|
|
print("❌ Erro ao criar equipa: $e");
|
|
}
|
|
}
|
|
|
|
// 3. ELIMINAR
|
|
Future<void> deleteTeam(String id) async {
|
|
try {
|
|
// Como segurança extra, podemos garantir que só apaga se for o dono (opcional se tiveres RLS no Supabase)
|
|
await _supabase.from('teams').delete().eq('id', id);
|
|
} catch (e) {
|
|
print("❌ Erro ao eliminar: $e");
|
|
}
|
|
}
|
|
|
|
// 4. FAVORITAR
|
|
Future<void> toggleFavorite(String teamId, bool currentStatus) async {
|
|
try {
|
|
await _supabase
|
|
.from('teams')
|
|
.update({'is_favorite': !currentStatus})
|
|
.eq('id', teamId);
|
|
} catch (e) {
|
|
print("❌ Erro ao favoritar: $e");
|
|
}
|
|
}
|
|
|
|
// 5. CONTAR JOGADORES (LEITURA ÚNICA)
|
|
Future<int> getPlayerCount(String teamId) async {
|
|
try {
|
|
final count = await _supabase.from('members').count().eq('team_id', teamId);
|
|
return count;
|
|
} catch (e) {
|
|
return 0;
|
|
}
|
|
}
|
|
|
|
// 6. VIEW DAS EQUIPAS (AQUI ESTAVA O TEU ERRO DE LISTAGEM!)
|
|
Future<List<Map<String, dynamic>>> getTeamsWithStats() async {
|
|
final userId = _supabase.auth.currentUser?.id;
|
|
if (userId == null) return []; // Retorna lista vazia se não houver login
|
|
|
|
final data = await _supabase
|
|
.from('teams_with_stats')
|
|
.select('*')
|
|
.eq('user_id', userId) // 👈 CRUCIAL: Só puxa as estatísticas das tuas equipas!
|
|
.order('name', ascending: true);
|
|
|
|
return List<Map<String, dynamic>>.from(data);
|
|
}
|
|
|
|
void dispose() {}
|
|
} |