84 lines
2.9 KiB
Dart
84 lines
2.9 KiB
Dart
import 'package:supabase_flutter/supabase_flutter.dart';
|
|
import '../models/game_model.dart';
|
|
|
|
class GameController {
|
|
final _supabase = Supabase.instance.client;
|
|
|
|
// 👇 Atalho para apanhar o ID do utilizador logado
|
|
String get myUserId => _supabase.auth.currentUser?.id ?? '';
|
|
|
|
// 1. LER JOGOS (Stream em Tempo Real da tabela original)
|
|
Stream<List<Game>> get gamesStream {
|
|
return _supabase
|
|
.from('games')
|
|
.stream(primaryKey: ['id'])
|
|
.eq('user_id', myUserId) // 🔒 SEGURANÇA: Ouve apenas os jogos deste utilizador
|
|
.asyncMap((event) async {
|
|
// Lê diretamente da tabela "games" e já não da "games_with_logos"
|
|
final data = await _supabase
|
|
.from('games')
|
|
.select()
|
|
.eq('user_id', myUserId) // 🔒 SEGURANÇA
|
|
.order('game_date', ascending: false);
|
|
|
|
return data.map((json) => Game.fromMap(json)).toList();
|
|
});
|
|
}
|
|
|
|
// =========================================================================
|
|
// 👇 LER JOGOS COM FILTROS DE EQUIPA E TEMPORADA
|
|
// =========================================================================
|
|
Stream<List<Game>> getFilteredGames({required String teamFilter, required String seasonFilter}) {
|
|
return _supabase
|
|
.from('games')
|
|
.stream(primaryKey: ['id'])
|
|
.eq('user_id', myUserId) // 🔒 SEGURANÇA
|
|
.asyncMap((event) async {
|
|
|
|
// 1. Começamos a query na tabela principal "games"
|
|
var query = _supabase.from('games').select().eq('user_id', myUserId); // 🔒 SEGURANÇA
|
|
|
|
// 2. Se a temporada não for "Todas", aplicamos o filtro AQUI
|
|
if (seasonFilter != 'Todas') {
|
|
query = query.eq('season', seasonFilter);
|
|
}
|
|
|
|
// 3. Executamos a query e ordenamos pela data
|
|
final data = await query.order('game_date', ascending: false);
|
|
|
|
List<Game> games = data.map((json) => Game.fromMap(json)).toList();
|
|
|
|
// 4. Filtramos a equipa em memória
|
|
if (teamFilter != 'Todas') {
|
|
games = games.where((g) => g.myTeam == teamFilter || g.opponentTeam == teamFilter).toList();
|
|
}
|
|
|
|
return games;
|
|
});
|
|
}
|
|
|
|
// 2. CRIAR JOGO
|
|
Future<String?> createGame(String myTeam, String opponent, String season) async {
|
|
try {
|
|
final response = await _supabase.from('games').insert({
|
|
'user_id': myUserId, // 🔒 CARIMBA O JOGO COM O ID DO TREINADOR
|
|
'my_team': myTeam,
|
|
'opponent_team': opponent,
|
|
'season': season,
|
|
'my_score': 0,
|
|
'opponent_score': 0,
|
|
'status': 'Decorrer',
|
|
'game_date': DateTime.now().toIso8601String(),
|
|
}).select().single();
|
|
|
|
return response['id'];
|
|
} catch (e) {
|
|
print("Erro ao criar jogo: $e");
|
|
return null;
|
|
}
|
|
}
|
|
|
|
void dispose() {
|
|
// Não é necessário fechar streams do Supabase manualmente aqui
|
|
}
|
|
} |