import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:marco/helpers/services/storage/local_storage.dart';

class ApiService {
  static const String baseUrl = "https://api.marcoaiot.com/api";  

  // Fetch the list of projects
  static Future<List<dynamic>?> getProjects() async {
    try {
      String? jwtToken = LocalStorage.getJwtToken();
      if (jwtToken == null) {
        print("No JWT token found. Please log in.");
        return null;
      }

      final response = await http.get(
        Uri.parse("$baseUrl/project/list"),
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer $jwtToken', // Add Authorization header
        },
      );

      if (response.statusCode == 200) {
        final json = jsonDecode(response.body);
        print("Response body: ${response.body}");
        if (json['success'] == true) {
          return json['data']; // Return the data if success is true
        } else {
          print("Error: ${json['message']}");
        }
      } else {
        print("Error fetching projects: ${response.statusCode}");
        print("Response body: ${response.body}");
      }
    } catch (e) {
      print("Exception while fetching projects: $e");
    }
    return null;
  }

  // Fetch employees by project ID
  static Future<List<dynamic>?> getEmployeesByProject(int projectId) async {
    try {
      String? jwtToken = LocalStorage.getJwtToken();
      if (jwtToken == null) {
        print("No JWT token found. Please log in.");
        return null;
      }

      final response = await http.get(
        Uri.parse("$baseUrl/attendance/project/team?projectId=$projectId"), // Ensure correct endpoint
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer $jwtToken',
        },
      );

      if (response.statusCode == 200) {
        final json = jsonDecode(response.body);
        print("Response body: ${response.body}");
        if (json['success'] == true) {
          return json['data']; // Return employee data
        } else {
          print("Error: ${json['message']}");
        }
      } else {
        print("Error fetching employees: ${response.statusCode}");
        print("Response body: ${response.body}");
      }
    } catch (e) {
      print("Exception while fetching employees: $e");
    }
    return null;
  }
}
