import 'dart:convert'; import 'package:http/http.dart' as http; import 'package:p_tits_pas/models/absence_garde.dart'; import 'package:p_tits_pas/services/api/api_config.dart'; import 'package:p_tits_pas/services/auth_service.dart'; class AbsencesGardeService { static Future> getAbsences({String? placementId}) async { final token = await AuthService.getToken(); final headers = token != null ? ApiConfig.authHeaders(token) : ApiConfig.headers; final uri = Uri.parse(ApiConfig.baseUrl + '/absences-garde' + (placementId != null ? '?placementId=$placementId' : '')); final res = await http.get(uri, headers: headers); if (res.statusCode == 200) { final json = jsonDecode(res.body); final List items = json['items'] ?? []; return items.map((e) => AbsenceGarde.fromJson(e)).toList(); } else { throw Exception('Erreur de chargement des absences : ${res.statusCode}'); } } static Future creerAbsence({ required String idPlacement, required String type, required String dateDebut, required String dateFin, String? motif, }) async { final token = await AuthService.getToken(); final headers = token != null ? ApiConfig.authHeaders(token) : ApiConfig.headers; final uri = Uri.parse('${ApiConfig.baseUrl}/absences-garde'); final res = await http.post( uri, headers: headers, body: jsonEncode({ 'id_placement': idPlacement, 'type': type, 'date_debut': dateDebut, 'date_fin': dateFin, if (motif != null) 'motif': motif, }), ); if (res.statusCode == 201) { return AbsenceGarde.fromJson(jsonDecode(res.body)); } else { throw Exception("Erreur de création d'absence : ${res.statusCode}"); } } static Future modifierAbsence( String id, { String? dateDebut, String? dateFin, String? statut, String? motif, }) async { final token = await AuthService.getToken(); final headers = token != null ? ApiConfig.authHeaders(token) : ApiConfig.headers; final uri = Uri.parse('${ApiConfig.baseUrl}/absences-garde/$id'); final Map body = {}; if (dateDebut != null) body['date_debut'] = dateDebut; if (dateFin != null) body['date_fin'] = dateFin; if (statut != null) body['statut'] = statut; if (motif != null) body['motif'] = motif; final res = await http.patch( uri, headers: headers, body: jsonEncode(body), ); if (res.statusCode == 200) { return AbsenceGarde.fromJson(jsonDecode(res.body)); } else { throw Exception("Erreur de modification d'absence : ${res.statusCode}"); } } static Future supprimerAbsence(String id) async { final token = await AuthService.getToken(); final headers = token != null ? ApiConfig.authHeaders(token) : ApiConfig.headers; final uri = Uri.parse('${ApiConfig.baseUrl}/absences-garde/$id'); final res = await http.delete(uri, headers: headers); if (res.statusCode != 204) { throw Exception("Erreur de suppression d'absence : ${res.statusCode}"); } } }