import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import '../models/Announcements_Response.dart';
import '../services/api_client.dart';
import '../services/api_urls.dart';

class AnnouncementProvider extends ChangeNotifier {
  AnnouncementProvider() {
    getAnnouncements(); // Fetch announcements when the provider is initialized
  }

  final _apiClient = ApiClient(); // Use the API client to fetch data
  List<AnnouncementResponse> announcementList = []; // List to hold announcement data

  bool _isLoading = false; // Loading state

  bool get isLoading => _isLoading; // Getter for loading state

  void setLoading(bool loading) {
    _isLoading = loading;
    notifyListeners(); // Notify listeners when loading state changes
  }

  Future<void> getAnnouncements() async {
    setLoading(true); // Set loading to true before the request
    try {
      Response response = await _apiClient.get(ApiUrls.announcementUrl); // Fetch announcements
      setLoading(false); // Set loading to false after the request completes
      if (response.statusCode == 200) {
        final List<dynamic> data = response.data['announcements']; // Extract data from response
        announcementList = data
            .map((item) => AnnouncementResponse.fromJson(item))
            .toList(); // Map JSON data to the announcement model
        notifyListeners(); // Notify listeners after data is updated
      }
    } catch (e) {
      setLoading(false); // Handle errors and stop loading state
      // Optionally handle errors here (e.g., log error, show message)
    }
  }
}
