import 'package:get/get.dart';
import 'package:marco/helpers/services/api_service.dart';
import 'package:marco/model/attendance_model.dart';
import 'package:marco/model/project_model.dart';  // Assuming you have a ProjectModel for the projects.
import 'package:marco/model/employee_model.dart';  // Assuming you have an EmployeeModel for the employees.

class AttendanceController extends GetxController {
  List<AttendanceModel> attendances = [];
  List<ProjectModel> projects = []; // List of projects
  String? selectedProjectId; // Currently selected project ID
  List<EmployeeModel> employees = []; // Employees of the selected project

  @override
  void onInit() {
    super.onInit();
    fetchProjects(); // Fetch projects when initializing
  }

  // Fetch projects from API
Future<void> fetchProjects() async {
  var response = await ApiService.getProjects(); // Call the project API

  if (response != null) {
    projects = response
        .map<ProjectModel>((json) => ProjectModel.fromJson(json))
        .toList();

    // Set default to the first project if available
    if (projects.isNotEmpty) {
      selectedProjectId = projects.first.id.toString();
      await fetchEmployeesByProject(selectedProjectId);  // Fetch employees for the first project
    }

    update(['attendance_dashboard_controller']); // Notify GetBuilder with your tag
  } else {
    print("No projects data found or failed to fetch data.");
  }
}


  // Fetch employees by project ID
  Future<void> fetchEmployeesByProject(String? projectId) async {
    if (projectId == null) return;

    var response = await ApiService.getEmployeesByProject(int.parse(projectId));

    if (response != null) {
      employees = response
          .map<EmployeeModel>((json) => EmployeeModel.fromJson(json))
          .toList();
      update(); // Trigger UI rebuild
    } else {
      print("Failed to fetch employees for project $projectId.");
    }
  }
}
