import 'dart:io'; import 'package:supabase_flutter/supabase_flutter.dart'; import 'package:playmaker/controllers/active_team.dart'; class TeamController { final _supabase = Supabase.instance.client; // 1. STREAM (Realtime) Stream>> 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 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 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 toggleFavorite(String teamId, bool currentStatus) async { try { final userId = _supabase.auth.currentUser?.id; if (userId == null) return; // If we're marking this team as favorite, clear other favorites for this user if (!currentStatus) { await _supabase.from('teams').update({'is_favorite': false}).eq('user_id', userId); } // Toggle the chosen team's favorite flag await _supabase.from('teams').update({'is_favorite': !currentStatus}).eq('id', teamId); // If it became favorite, load its data and set global active team if (!currentStatus) { final teamData = await _supabase.from('teams').select().eq('id', teamId).maybeSingle(); if (teamData != null) { final newTeam = ActiveTeam( id: teamData['id'].toString(), name: teamData['name'] ?? 'Desconhecido', logo: teamData['image_url'], wins: int.tryParse(teamData['wins']?.toString() ?? '0') ?? 0, losses: int.tryParse(teamData['losses']?.toString() ?? '0') ?? 0, draws: int.tryParse(teamData['draws']?.toString() ?? '0') ?? 0, ); // Update global active team so UI reflects the favorite immediately await saveGlobalTeam(newTeam); } } } catch (e) { print("❌ Erro ao favoritar: $e"); } } // 5. CONTAR JOGADORES (LEITURA ÚNICA) Future 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>> 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>.from(data); } void dispose() {} }