import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'package:nhancepolicy/service/token_storage_service.dart'; import 'dart:convert'; import '../config/environment.dart'; import '../customAppBar/toastHelper.dart'; import 'package:nhancepolicy/logger.dart'; class ApiService { final BuildContext context; final tokenService = TokenStorageService(); String? _token; String? _hrtoken; bool _isSessionOutToastShown = false; // Flag to track toast message bool isTpaDashboardEnabled = false; bool isTpaSelected = false; // track which dashboard is active ApiService(this.context) { _initializeToken(); } Future _initializeToken() async { _token = tokenService.getCurrentToken() ?? ''; } Future getTokenLoadAPI(token) async { _token = token; } Future> getClientLogoAndDetailsToApi( String clientId, String empCode, String branchID) async { logDebug(_token); if (_token == null) { await _initializeToken(); } final empClientId = await tokenService.readValue('empClientId'); final empClientBranchId = await tokenService.readValue('empClientBranchId'); final url = Uri.parse( '${Environment.apiUrl}getClientDetails?post_client_id=$empClientId&post_branch_id=$empClientBranchId&pre_client_id=$clientId&pre_branch_id=$branchID'); final headers = { 'Authorization': 'Bearer $_token' ?? '', }; final response = await _makeGetRequest(url, headers); return response; } Future> getActiveAndInactivePolicyDetails( String? clientId, String? empCode, String? status, String? branchID, String? mobileNo, String? emailId) async { if (_token == null) { await _initializeToken(); } final url = Uri.parse( '${Environment.apiUrl}getEmployeeActiveOrInactivePolicy?client_id=${clientId ?? ''}&emp_code=${empCode ?? ''}&type=${status ?? ''}&client_branch_id=${branchID ?? ''}&mobile_no=${mobileNo ?? ''}&email_id=${emailId ?? ''}'); final headers = { 'Authorization': 'Bearer $_token' ?? '', }; final response = await _makeGetRequest(url, headers); return response; } Future> getSelfEmployeeProfileToApi( token, String clientId, String empCode, String branchID, String client_policy_id) async { logDebug(_token); _token = await token; if (_token == null) { await _initializeToken(); } final url = Uri.parse( '${Environment.apiUrl}getEmployeeProfile?emp_code=$empCode&client_id=$clientId&client_branch_id=$branchID&client_policy_id=$client_policy_id'); final headers = { 'Authorization': 'Bearer $_token' ?? '', }; final response = await _makeGetRequest(url, headers); return response; } Future> fetchRelationshipListToApi() async { logDebug(_token); if (_token == null) { await _initializeToken(); } final url = Uri.parse('${Environment.apiUrl}relationshipList'); final headers = { 'Authorization': 'Bearer $_token' ?? '', }; final response = await _makeGetRequest(url, headers); return response; } Future> getGpaEmpPolicyDetailsToApi( String empPrimaryId, String empCode, String clientId, String policy, String branchID, login_by_hr) async { logDebug(_token); if (_token == null) { await _initializeToken(); } final url = Uri.parse( '${Environment.apiUrl}getEmployeePolicy?id=$empPrimaryId&emp_code=$empCode&client_id=$clientId&policy=$policy&client_branch_id=$branchID&login_by_hr=$login_by_hr'); final headers = { 'Authorization': 'Bearer $_token' ?? '', }; final response = await _makeGetRequest(url, headers); return response; } Future> getGmcEmpPolicyDetailsToApi( String empPrimaryId, String empCode, String clientId, String policy, String branchID, login_by_hr) async { logDebug(_token); if (_token == null) { await _initializeToken(); } final url = Uri.parse( '${Environment.apiUrl}getEmployeePolicy?id=$empPrimaryId&emp_code=$empCode&client_id=$clientId&policy=$policy&client_branch_id=$branchID&login_by_hr=$login_by_hr'); final headers = { 'Authorization': 'Bearer $_token' ?? '', }; final response = await _makeGetRequest(url, headers); return response; } Future> getGmcSiTopUpToApi( String client_id, String emp_code, String policy, String branchID) async { logDebug(_token); if (_token == null) { await _initializeToken(); } final url = Uri.parse( '${Environment.apiUrl}getAddOnPolicy?client_id=$client_id&emp_code=$emp_code&policy=$policy&client_branch_id=$branchID'); final headers = { 'Authorization': 'Bearer $_token' ?? '', }; final response = await _makeGetRequest(url, headers); return response; } Future> getGmcSiParentTopUpToApi( String client_id, String emp_code, String policy, String branchID) async { logDebug(_token); if (_token == null) { await _initializeToken(); } final url = Uri.parse( '${Environment.apiUrl}getAddOnPolicy?client_id=$client_id&emp_code=$emp_code&policy=$policy&client_branch_id=$branchID'); final headers = { 'Authorization': 'Bearer $_token' ?? '', }; final response = await _makeGetRequest(url, headers); return response; } Future> getGmcDependentAddOnsToApi( String client_id, String emp_code, String policy, String branchID) async { logDebug(_token); if (_token == null) { await _initializeToken(); } final url = Uri.parse( '${Environment.apiUrl}getAddOnPolicy?client_id=$client_id&emp_code=$emp_code&policy=$policy&client_branch_id=$branchID'); final headers = { 'Authorization': 'Bearer $_token' ?? '', }; final response = await _makeGetRequest(url, headers); return response; } Future> getExcelFileErrorsApi(id, type) async { logDebug(_token); if (_token == null) { await _initializeToken(); } final apiURL; if (type == 'post') { apiURL = Environment.apiUrlPost; } else { apiURL = Environment.apiUrl; } final url = Uri.parse('${apiURL}getExcelFileErrors/${id}/api'); final headers = { 'Authorization': 'Bearer $_token' ?? '', }; final response = await _makeGetRequest(url, headers); return response; } Future> removeAddonsGmcDependentToAPI( String empCodeString, String addOnsDependentClientPolicyId) async { logDebug(_token); if (_token == null) { await _initializeToken(); } final url = Uri.parse( '${Environment.apiUrl}removeEmpAndEmpPolicyData?emp_code=$empCodeString&client_policy_id=$addOnsDependentClientPolicyId'); final headers = { 'Authorization': 'Bearer $_token' ?? '', }; final response = await _makeGetRequest(url, headers); return response; } Future> removeAddonsGmcSiToAPI( String empCodeString, String topUpClientPolicyId) async { logDebug(_token); if (_token == null) { await _initializeToken(); } final url = Uri.parse( '${Environment.apiUrl}removeEmpAndEmpPolicyData?emp_code=$empCodeString&client_policy_id=$topUpClientPolicyId'); final headers = { 'Authorization': 'Bearer $_token' ?? '', }; final response = await _makeGetRequest(url, headers); return response; } Future> removeAddonsGmcParentSiToAPI( String empCodeString, String topUpParentClientPolicyId) async { logDebug(_token); if (_token == null) { await _initializeToken(); } final url = Uri.parse( '${Environment.apiUrl}removeEmpAndEmpPolicyData?emp_code=$empCodeString&client_policy_id=$topUpParentClientPolicyId'); final headers = { 'Authorization': 'Bearer $_token' ?? '', }; final response = await _makeGetRequest(url, headers); return response; } Future> deleteItemToApi(id) async { logDebug(_token); if (_token == null) { await _initializeToken(); } final url = Uri.parse('${Environment.apiUrl}deleteDependence?id=$id'); final headers = { 'Authorization': 'Bearer $_token' ?? '', }; final response = await _makeGetRequest(url, headers); return response; } Future> saveFamilyMemberDetailsToApi( List> formDataList) async { logDebug('saveFamilyMemberDetailsToApi API SERVICE'); if (_token == null) { await _initializeToken(); } final url = Uri.parse('${Environment.apiUrl}addEmployeeAndDependence'); final headers = { 'Authorization': 'Bearer $_token' ?? '', 'Content-Type': 'application/json', // Ensure content type is JSON }; // Convert formDataList to JSON string final formDataJson = jsonEncode(formDataList); // Send formDataJson as the body final response = await _makePostRequest(url, formDataJson, headers); return response; } Future> saveAddOnsDetailsToApi( List> formDataList) async { logDebug('saveAddOnsDetailsToApi API SERVICE'); if (_token == null) { await _initializeToken(); } final url = Uri.parse('${Environment.apiUrl}addEmployeeAndDependence'); final headers = { 'Authorization': 'Bearer $_token' ?? '', 'Content-Type': 'application/json', // Ensure content type is JSON }; // Convert formDataList to JSON string final formDataJson = jsonEncode(formDataList); // Send formDataJson as the body final response = await _makePostRequest(url, formDataJson, headers); return response; } Future> sendAddonsGmcDependentToAPI( List> formDataList) async { logDebug('saveAddOnsDetailsToApi API SERVICE'); if (_token == null) { await _initializeToken(); } final url = Uri.parse('${Environment.apiUrl}createOrUpdateEmployeePolicySiAmount'); final headers = { 'Authorization': 'Bearer $_token' ?? '', 'Content-Type': 'application/json', // Ensure content type is JSON }; // Convert formDataList to JSON string final formDataJson = jsonEncode(formDataList); // Send formDataJson as the body final response = await _makePostRequest(url, formDataJson, headers); return response; } Future> sendAddonsGmcSiToAPI( List> formDataList) async { logDebug('saveAddOnsDetailsToApi API SERVICE'); if (_token == null) { await _initializeToken(); } final url = Uri.parse('${Environment.apiUrl}createOrUpdateEmployeePolicySiAmount'); final headers = { 'Authorization': 'Bearer $_token' ?? '', 'Content-Type': 'application/json', // Ensure content type is JSON }; // Convert formDataList to JSON string final formDataJson = jsonEncode(formDataList); // Send formDataJson as the body final response = await _makePostRequest(url, formDataJson, headers); return response; } Future> sendAddonsGmcParentSiToAPI( List> formDataList) async { logDebug('saveAddOnsDetailsToApi API SERVICE'); if (_token == null) { await _initializeToken(); } final url = Uri.parse('${Environment.apiUrl}createOrUpdateEmployeePolicySiAmount'); final headers = { 'Authorization': 'Bearer $_token' ?? '', 'Content-Type': 'application/json', // Ensure content type is JSON }; // Convert formDataList to JSON string final formDataJson = jsonEncode(formDataList); // Send formDataJson as the body final response = await _makePostRequest(url, formDataJson, headers); return response; } Future> sendAddOnToAPI( Map formData) async { logDebug('sendAddOnToAPI API SERVICE'); if (_token == null) { await _initializeToken(); } final url = Uri.parse('${Environment.apiUrl}iAgreeForAddOn'); final headers = { 'Authorization': 'Bearer $_token' ?? '', 'Content-Type': 'application/json', // Ensure content type is JSON }; // Convert formDataList to JSON string final formDataJson = jsonEncode(formData); // Send formDataJson as the body final response = await _makePostRequest(url, formDataJson, headers); return response; } Future> topUpSiCalculationToAPI(formDataList) async { logDebug('saveAddOnsDetailsToApi API SERVICE'); if (_token == null) { await _initializeToken(); } final url = Uri.parse('${Environment.apiUrl}calculatePremium'); final headers = { 'Authorization': 'Bearer $_token' ?? '', 'Content-Type': 'application/json', // Ensure content type is JSON }; // Convert formDataList to JSON string final formDataJson = jsonEncode(formDataList); // Send formDataJson as the body final response = await _makePostRequest(url, formDataJson, headers); return response; } Future> topUpParentSiCalculationToAPI( formDataList) async { logDebug('saveAddOnsDetailsToApi API SERVICE'); if (_token == null) { await _initializeToken(); } final url = Uri.parse('${Environment.apiUrl}calculatePremium'); final headers = { 'Authorization': 'Bearer $_token' ?? '', 'Content-Type': 'application/json', // Ensure content type is JSON }; // Convert formDataList to JSON string final formDataJson = jsonEncode(formDataList); // Send formDataJson as the body final response = await _makePostRequest(url, formDataJson, headers); return response; } Future> addOnsDependentCalculationToAPI( formDataList) async { logDebug('saveAddOnsDetailsToApi API SERVICE'); if (_token == null) { await _initializeToken(); } final url = Uri.parse('${Environment.apiUrl}calculatePremium'); final headers = { 'Authorization': 'Bearer $_token' ?? '', 'Content-Type': 'application/json', // Ensure content type is JSON }; // Convert formDataList to JSON string final formDataJson = jsonEncode(formDataList); // Send formDataJson as the body final response = await _makePostRequest(url, formDataJson, headers); return response; } //HR API STARTS Future> getCashDepositDetailsToApi( String clintID, String empRefId, String hr_id, String token) async { logDebug("getCashDepositDetailsToApi1"); logDebug("HRID- $hr_id"); if (token == null) { await _initializeToken(); } final url = Uri.parse( '${Environment.apiUrl}getPolicyLevelEmployeeSummaryData?client_id=$clintID&client_branch_id=$empRefId&hr_id=$hr_id'); final headers = { 'Authorization': 'Bearer $token' ?? '', }; final response = await _makeGetRequest(url, headers); return response; } Future> getActiveCashDepositDetailsToApi(String clintID, String empRefId, String hr_id, String token, int emp_status) async { logDebug("getCashDepositDetailsToApi1"); if (token == null) { await _initializeToken(); } // final url = Uri.parse( // '${Environment.apiUrl}getPolicyLevelEmployeeSummaryData?client_id=$clintID&client_branch_id=$empRefId&hr_id=470'); final url = Uri.parse( '${Environment.apiUrlPost}getPolicyLevelEmployeeSummaryData?client_id=$clintID&client_branch_id=$empRefId&policy_status=$emp_status&hr_id=$hr_id'); final headers = { 'Authorization': 'Bearer $token' ?? '', }; final response = await _makeGetRequest(url, headers); return response; } Future> getCDPoliciesToApi( String clintID, String hr_id, String token) async { logDebug("getCashDepositDetailsToApi1"); final url = Uri.parse( '${Environment.apiUrlPost}cdSummaryData?client_id=$clintID&hr_id=$hr_id'); final headers = { 'Authorization': 'Bearer $token' ?? '', }; final response = await _makeGetRequest(url, headers); return response; } Future> getImportLogHrActivity( String? postId, String? preId, String token, String activity) async { logDebug("getCashDepositDetailsToApi1"); logDebug('postId1 - $postId'); logDebug('preId1 - $preId'); logDebug('activity1 - $activity'); // final url = Uri.parse( // '${Environment.apiUrlPost}logHrActivity?user_id=$postId&pre_hr_id=$preId&user_type=hr&activity=$activity'); final url = Uri.parse('${Environment.apiUrlPost}logHrActivity'); final headers = { 'Authorization': 'Bearer ${token ?? ''}', 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', }; final body = { 'user_id': postId, 'pre_hr_id': preId, 'user_type': 'hr', 'activity': activity, }; final response = await http.post( url, headers: headers, body: jsonEncode(body), ); // final response = await _makeGetRequest(url, headers); if (response.statusCode == 200) { return jsonDecode(response.body); } else { throw Exception( 'Failed to log HR activity: ${response.statusCode} ${response.body}'); } } Future> getEcardBulkDownloadApi( client_policy_id, empHrId, emp_policy_ids, String token) async { // final url = Uri.parse( // '${Environment.apiUrlPost}logHrActivity?user_id=$postId&pre_hr_id=$preId&user_type=hr&activity=$activity'); final url = Uri.parse('${Environment.apiUrlPost}bulkEcardDownloadAsZip'); final headers = { 'Authorization': 'Bearer ${token ?? ''}', 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', }; final body = { 'client_policy_id': client_policy_id, 'hr_id': empHrId, 'emp_policy_ids': emp_policy_ids, }; final response = await http.post( url, headers: headers, body: jsonEncode(body), ); // final response = await _makeGetRequest(url, headers); if (response.statusCode == 200) { return jsonDecode(response.body); } else { throw Exception( 'Failed to log HR activity: ${response.statusCode} ${response.body}'); } } Future> getPostLogHrActivity( String? postId, String? preId, String token, String activity) async { logDebug("getCashDepositDetailsToApi1"); logDebug('postId1 - $postId'); logDebug('preId1 - $preId'); logDebug('activity1 - $activity'); // final url = Uri.parse( // '${Environment.apiUrlPost}logHrActivity?user_id=$postId&pre_hr_id=$preId&user_type=hr&activity=$activity'); final url = Uri.parse('${Environment.apiUrlPost}logHrActivity'); final headers = { 'Authorization': 'Bearer ${token ?? ''}', 'Content-Type': 'application/json', 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', }; final body = { 'user_id': postId, 'pre_hr_id': preId, 'user_type': 'hr', 'activity': activity, }; final response = await http.post( url, headers: headers, body: jsonEncode(body), ); // final response = await _makeGetRequest(url, headers); if (response.statusCode == 200) { return jsonDecode(response.body); } else { throw Exception( 'Failed to log HR activity: ${response.statusCode} ${response.body}'); } } Future> getPreLogHrActivity( String? postId, String? preId, String token, String activity) async { logDebug("getCashDepositDetailsToApi1"); logDebug('postId1 - $postId'); logDebug('preId1 - $preId'); logDebug('activity1 - $activity'); final url = Uri.parse('${Environment.apiUrl}logHrActivity'); final headers = { 'Authorization': 'Bearer ${token ?? ''}', 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', }; final body = { 'user_id': postId, 'pre_hr_id': preId, 'user_type': 'hr', 'activity': activity, }; final response = await http.post( url, headers: headers, body: jsonEncode(body), ); // final response = await _makeGetRequest(url, headers); if (response.statusCode == 200) { return jsonDecode(response.body); } else { throw Exception( 'Failed to log HR activity: ${response.statusCode} ${response.body}'); } } Future> postHrDashboard(params, token) async { final url = Uri.parse('${Environment.apiUrlPost}getHrDashboad'); final headers = { 'Authorization': 'Bearer ${token ?? ''}', 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', }; final body = params; final response = await http.post( url, headers: headers, body: jsonEncode(body), ); // final response = await _makeGetRequest(url, headers); if (response.statusCode == 200) { return jsonDecode(response.body); } else { throw Exception( 'Failed to log HR activity: ${response.statusCode} ${response.body}'); } } /// All 31 claims-collection KPIs in one response. Future> getClaimsCollectionV2All({ required String clientPolicyId, }) async { if (_token == null) await _initializeToken(); final url = Uri.parse('${Environment.apiUrlPost}claims-collection-v2/all') .replace( queryParameters: {'client_policy': clientPolicyId}, ); final headers = {'Authorization': 'Bearer ${_token ?? ''}'}; return _makeGetRequest(url, headers); } /// Single KPI by Metabase slug or numeric id. Future> getClaimsCollectionV2Kpi( String slugOrId, { required String clientPolicyId, }) async { if (_token == null) await _initializeToken(); final encoded = Uri.encodeComponent(slugOrId); final url = Uri.parse( '${Environment.apiUrlPost}claims-collection-v2/kpi/$encoded', ).replace( queryParameters: {'client_policy': clientPolicyId}, ); final headers = {'Authorization': 'Bearer ${_token ?? ''}'}; return _makeGetRequest(url, headers); } /// All enrollment-collection KPIs in one response (`enrollment-collection-v1`). Future> getEnrollmentCollectionV1All({ required String clientPolicyId, }) async { if (_token == null) await _initializeToken(); final url = Uri.parse('${Environment.apiUrlPost}enrollment-collection-v1/all') .replace( queryParameters: {'client_policy': clientPolicyId}, ); final headers = {'Authorization': 'Bearer ${_token ?? ''}'}; return _makeGetRequest(url, headers); } /// Single enrollment KPI by slug or numeric id (`enrollment-collection-v1`). Future> getEnrollmentCollectionV1Kpi( String slugOrId, { required String clientPolicyId, }) async { if (_token == null) await _initializeToken(); final encoded = Uri.encodeComponent(slugOrId); final url = Uri.parse( '${Environment.apiUrlPost}enrollment-collection-v1/kpi/$encoded', ).replace( queryParameters: {'client_policy': clientPolicyId}, ); final headers = {'Authorization': 'Bearer ${_token ?? ''}'}; return _makeGetRequest(url, headers); } /// Pending approval dependents list /// (`GET getPendingApprovalDependents`) — post API only. Future> getPendingApprovalDependents({ String? clientId, String? branchId, String? search, String? token, }) async { final authToken = token ?? _token; if (authToken == null || authToken.isEmpty) { await _initializeToken(); } final query = {}; if (clientId != null && clientId.toString().trim().isNotEmpty) { query['client_id'] = clientId.toString(); } if (branchId != null && branchId.toString().trim().isNotEmpty) { query['client_branch_id'] = branchId.toString(); query['branch_id'] = branchId.toString(); } if (search != null && search.trim().isNotEmpty) { query['search'] = search.trim(); } final url = Uri.parse( '${Environment.apiUrlPost}getPendingApprovalDependents', ).replace( queryParameters: query.isEmpty ? null : query, ); final headers = { 'Authorization': 'Bearer ${token ?? _token ?? ''}', 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', }; final response = await http.get(url, headers: headers); if (response.statusCode == 200) { return _parseJsonBody(response); } // API returns 404 when there are no pending dependents. if (response.statusCode == 404) { final body = _parseJsonBody(response); return { 'status': 'success', 'code': 404, 'message': body['message'] ?? 'No pending approval dependents found', 'data': [], }; } return _handleResponse(response); } /// Approve or reject a pending dependent /// (`POST processDependentAdd`). Future> processDependentAdd({ required bool isPost, required dynamic employeeId, required dynamic clientPolicyId, required String status, dynamic hrId, String? rejectReason, String? token, }) async { final authToken = token ?? _token; if (authToken == null || authToken.isEmpty) { await _initializeToken(); } final baseUrl = isPost ? Environment.apiUrlPost : Environment.apiUrl; final url = Uri.parse('${baseUrl}processDependentAdd'); final headers = { 'Authorization': 'Bearer ${token ?? _token ?? ''}', 'Content-Type': 'application/json', 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', }; final body = { 'employee_id': employeeId, 'client_policy_id': clientPolicyId, 'status': status, }; if (hrId != null && hrId.toString().trim().isNotEmpty) { body['hr_id'] = hrId is num ? hrId : int.tryParse(hrId.toString()) ?? hrId; } if (status == 'rejected' && rejectReason != null && rejectReason.trim().isNotEmpty) { body['reject_reason'] = rejectReason.trim(); } final response = await http.post( url, headers: headers, body: jsonEncode(body), ); if (response.statusCode == 200) { return _parseJsonBody(response); } // Surface API validation messages (400/404) without session redirect. if (response.statusCode == 400 || response.statusCode == 404) { final parsed = _parseJsonBody(response); return { 'status': parsed['status'] ?? 'error', 'code': response.statusCode, 'message': parsed['message'] ?? parsed['data']?.toString() ?? 'Request failed', 'data': parsed['data'], }; } return _handleResponse(response); } /// Excel export for employee list /// (`downloadEmployeeListExcel?client_id=&policy_id=&branch_id=`). Future downloadEmployeeListExcel({ required String clientId, required String policyId, required String branchId, required bool isPost, String? token, }) async { final authToken = token ?? _token; if (authToken == null || authToken.isEmpty) { await _initializeToken(); } final baseUrl = isPost ? Environment.apiUrlPost : Environment.apiUrl; final url = Uri.parse('${baseUrl}downloadEmployeeListExcel').replace( queryParameters: { 'client_id': clientId, 'policy_id': policyId, 'branch_id': branchId, }, ); final headers = { 'Authorization': 'Bearer ${token ?? _token ?? ''}', 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', }; return http.get(url, headers: headers); } /// Excel export for claims collection report (`claims-collection-report/download-excel`). Future downloadClaimsCollectionReportExcel({ required String clientPolicyId, }) async { if (_token == null) await _initializeToken(); final url = Uri.parse( '${Environment.apiUrlPost}claims-collection-report/download-excel', ).replace( queryParameters: {'client_policy_id': clientPolicyId}, ); final headers = { 'Authorization': 'Bearer ${_token ?? ''}', 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', }; return http.get(url, headers: headers); } Future> postHrTpaDashboard(params, token) async { final url = Uri.parse('${Environment.apiUrlPost}getHrTpaDashboard'); final headers = { 'Authorization': 'Bearer ${token ?? ''}', 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', }; final response = await http.post( url, headers: headers, body: jsonEncode(params), ); if (response.statusCode == 200) { return jsonDecode(response.body); } else { throw Exception( 'Failed to load HR TPA dashboard: ${response.statusCode}'); } } Future> getClaimPoliciesToApi( String token, empClientId) async { logDebug("getgetClaimPoliciesToApii1"); final url = Uri.parse( '${Environment.apiUrlPost}claimsSearch?client_id=$empClientId'); final headers = { 'Authorization': 'Bearer $token' ?? '', }; final response = await _makeGetRequest(url, headers); return response; } Future> getNonEBStatusToApi( String token, empClientId) async { logDebug("getgetClaimPoliciesToApii1"); final url = Uri.parse( '${Environment.apiUrlPost}api/v1/non-eb-claim/statuses'); final headers = { 'Authorization': 'Bearer $token' ?? '', }; final response = await _makeGetRequest(url, headers); return response; } Future> getClaimPoliciesFileDownload( id, String token) async { final url = Uri.parse('${Environment.apiUrlPost}hrFileDownload?id=$id'); final headers = { 'Authorization': 'Bearer $token' ?? '', }; final response = await _makeGetRequest(url, headers); return response; } Future> getClaimPoliciesListDataToApi( String token, Map body) async { logDebug("getgetClaimPoliciesToApii1"); final url = Uri.parse('${Environment.apiUrlPost}claimsSearch'); final headers = { 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', 'Authorization': 'Bearer $token', 'Content-Type': 'application/json', }; final response = await http.post( url, headers: headers, body: jsonEncode(body), ); if (response.statusCode == 200) { return jsonDecode(response.body); } else { throw Exception( 'Failed to load claims list: ${response.statusCode} ${response.body}'); } } Future> getNonEBClaimsListDataToApi( String token, Map body) async { logDebug("getgetClaimPoliciesToApii1"); final url = Uri.parse('${Environment.apiUrlPost}api/v1/non-eb-claim/list'); final headers = { 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', 'Authorization': 'Bearer $token', 'Content-Type': 'application/json', }; final response = await http.post( url, headers: headers, body: jsonEncode(body), ); if (response.statusCode == 200) { return jsonDecode(response.body); } else { throw Exception( 'Failed to load claims list: ${response.statusCode} ${response.body}'); } } Future> getEcardRequest(eCardParam, String token) async { final url = Uri.parse('${Environment.apiUrlPost}ecardRequest'); final headers = { 'Authorization': 'Bearer $token' ?? '', 'Content-Type': 'application/json', // Ensure content type is JSON }; final jsonBody = jsonEncode(eCardParam); // Send formDataJson as the body final response = await _makePostRequestWithoutFormData(url, jsonBody, headers); return response; } Future> sendMailForIndividualEmployeeEcard({ required dynamic empPolicyId, required dynamic clientPolicyId, required String token, }) async { final url = Uri.parse( '${Environment.apiUrlPost}sendMailForIndividualEmployeeEcard'); final headers = { 'Authorization': 'Bearer $token', 'Content-Type': 'application/json', 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', }; final body = { 'emp_policy_id': empPolicyId, 'client_policy_id': clientPolicyId, }; final response = await http.post( url, headers: headers, body: jsonEncode(body), ); if (response.statusCode == 200) { return jsonDecode(response.body); } else { throw Exception( 'Failed to send e-card mail: ${response.statusCode} ${response.body}'); } } Future> downloadInception({ required dynamic client, required dynamic branch, required dynamic policies, required List status, required String empCode, required String empName, required String token, }) async { final url = Uri.parse('${Environment.apiUrl}download_inception'); final headers = { 'Authorization': 'Bearer $token', 'Content-Type': 'application/json', 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', }; final body = { 'client': client, 'branch': branch, 'policies': policies, 'status': status, 'empCode': empCode, 'empName': empName, }; final response = await http.post( url, headers: headers, body: jsonEncode(body), ); if (response.statusCode == 200) { return jsonDecode(response.body); } else { throw Exception( 'Failed to download inception export: ${response.statusCode} ${response.body}'); } } Future> getNonEBClaimPoliciesToApi( String token, request) async { final url = Uri.parse('${Environment.apiUrlPost}api/v1/non-eb-claim/policies'); final headers = { 'Authorization': 'Bearer $token' ?? '', 'Content-Type': 'application/json', // Ensure content type is JSON }; final jsonBody = jsonEncode(request); // Send formDataJson as the body final response = await _makePostRequestWithoutFormData(url, jsonBody, headers); return response; } Future> getCdTransactionData( String clintID, String insurerId, String cd_ac_pk, String token) async { logDebug("getCashDepositDetailsToApi1"); final url = Uri.parse( '${Environment.apiUrlPost}cdTransactionData?client_id=$clintID&insurer_id=$insurerId&cd_ac_pk=$cd_ac_pk'); final headers = { 'Authorization': 'Bearer $token' ?? '', }; final response = await _makeGetRequest(url, headers); return response; } Future> getOpenEndorsementFileData( id, String token) async { logDebug("getPolicyAndEndorsementFiles"); final url = Uri.parse('${Environment.apiUrlPost}downloadPolicyFiles?file_id=$id'); final headers = { 'Authorization': 'Bearer $token' ?? '', }; final response = await _makeGetRequest(url, headers); return response; } Future> getCdEndorsementData(id, String token) async { logDebug("getPolicyAndEndorsementFiles"); final url = Uri.parse( '${Environment.apiUrlPost}getPolicyAndEndorsementFiles?cd_ac_pk=$id'); final headers = { 'Authorization': 'Bearer $token' ?? '', }; final response = await _makeGetRequest(url, headers); return response; } Future> getClaimsHistoryToApi( String ticket_type_id, String token) async { logDebug("getCashDepositDetailsToApi1"); final url = Uri.parse( '${Environment.apiUrlPost}claimView?ticket_id=$ticket_type_id'); final headers = { 'Authorization': 'Bearer $token' ?? '', }; final response = await _makeGetRequest(url, headers); return response; } Future> getNonEBClaimsHistoryToApi( String ticket_type_id, String token) async { logDebug("getCashDepositDetailsToApi1"); final url = Uri.parse( '${Environment.apiUrlPost}api/v1/non-eb-claim/history/${ticket_type_id}'); final headers = { 'Authorization': 'Bearer $token' ?? '', }; final response = await _makeGetRequest(url, headers); return response; } Future> getSampleFileDownload(String token) async { final url = Uri.parse('${Environment.apiUrl}downloadSampleExcel/enrollment'); final headers = { 'Authorization': 'Bearer $token' ?? '', }; final response = await _makeGetRequest(url, headers); return response; } Future> getEmployeeAndDependenceToApi( String clintID, getPolicyNo, String empRefId, String token, {dynamic cardData, String? searchKey}) async { logDebug(_hrtoken); if (token == null) { await _initializeToken(); } final params = { 'client_id': clintID, 'client_policy_id': '$getPolicyNo', 'client_branch_id': empRefId, }; if (cardData != null) { params['card_data'] = cardData.toString(); } if (searchKey != null && searchKey.trim().isNotEmpty) { params['search'] = searchKey.trim(); } final url = Uri.parse( '${Environment.apiUrlPost}getEmployeeAndDependenceByClientId') .replace(queryParameters: params); final headers = { 'Authorization': 'Bearer $token' ?? '', }; final response = await _makeGetRequest(url, headers); return response; } Future> getFileUploadMastersToApi(String token,localAllocgType) async { logDebug(_hrtoken); if (token == null) { await _initializeToken(); } final url = Uri.parse('${Environment.apiUrlPost}hrFileUploadMasters?type=$localAllocgType'); final headers = { 'Authorization': 'Bearer $token' ?? '', }; final response = await _makeGetRequest(url, headers); return response; } Future> getFileListToApi(empPrimaryId, cardPolicyNo, empClientId, String token, String type) async { logDebug(_hrtoken); if (token == null) { await _initializeToken(); } final apiURL; if (type == 'post') { apiURL = Environment.apiUrlPost; } else { apiURL = Environment.apiUrl; } final url = Uri.parse( '${apiURL}hrFileList?created_by=$empPrimaryId&policy_no=$cardPolicyNo&client_id=$empClientId'); final headers = { 'Authorization': 'Bearer ${token ?? ''}', 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', }; final response = await _makeGetRequest(url, headers); return response; } // Future> getHrFileDownloadToApi(id,String token) async { // logDebug(_hrtoken); // if (token == null) { // await _initializeToken(); // } // final url = Uri.parse( // '${Environment.apiUrl}hrFileDownload?id=$id'); // final headers = { // 'Authorization': 'Bearer $token' ?? '', // }; // final response = await _makeGetRequest(url, headers); // return response; // } Future> getEnrollmentReminderEmailTemplateApi( String clientId, String clientPolicyId, String clientBranchId, String token, ) async { final url = Uri.parse( '${Environment.apiUrl}getEnrollmentReminderEmailTemplate' '?client_id=$clientId&client_policy_id=$clientPolicyId' '&client_branch_id=$clientBranchId', ); final headers = { 'Authorization': 'Bearer ${token ?? ''}', 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', }; return _makeGetRequest(url, headers); } Future> saveEnrollmentReminderEmailTemplateApi( String token, Map payload, ) async { final url = Uri.parse('${Environment.apiUrl}saveEnrollmentReminderEmailTemplate'); final headers = { 'Authorization': 'Bearer $token', 'Content-Type': 'application/json', 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', }; return _makePostRequest(url, jsonEncode(payload), headers); } Future> sendTestEnrollmentReminderEmailApi( String clientId, String clientPolicyId, String clientBranchId, String hrId, String token, { required String emailSubject, required String emailBody, }) async { final url = Uri.parse('${Environment.apiUrl}testEnrollmentReminderEmail'); final headers = { 'Authorization': 'Bearer $token', 'Content-Type': 'application/json', 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', }; final policyId = int.tryParse(clientPolicyId) ?? clientPolicyId; final body = { 'client_id': clientId, 'client_policy_id': policyId, 'client_branch_id': clientBranchId, 'hr_id': hrId, 'email_subject': emailSubject, 'email_body': emailBody, }; return _makePostRequest(url, jsonEncode(body), headers); } Future> sendEnrollmentReminderApi( String clientId, String clientPolicyId, String clientBranchId, String hrId, String token, { required String emailSubject, required String emailBody, }) async { final url = Uri.parse('${Environment.apiUrl}sendEnrollmentReminderEmail'); final headers = { 'Authorization': 'Bearer ${token ?? ''}', 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', 'Content-Type': 'application/json', }; final body = { 'client_id': clientId, 'client_policy_id': clientPolicyId, 'client_branch_id': clientBranchId, 'hr_id': hrId, 'email_subject': emailSubject, 'email_body': emailBody, }; final response = await http.post( url, headers: headers, body: jsonEncode(body), ); if (response.statusCode == 200) { return jsonDecode(response.body); } else { throw Exception( 'Failed to send enrollment reminder: ${response.statusCode} ${response.body}'); } } Future> getReminderMailConfigApi( String clientPolicyId, String token, { bool isEmailTemplate = false, }) async { final query = StringBuffer( '${Environment.apiUrl}getReminderMailConfig' '?client_policy_id=$clientPolicyId', ); if (isEmailTemplate) { query.write('&is_email_template=true'); } final url = Uri.parse(query.toString()); final headers = { 'Authorization': 'Bearer $token', }; return _makeGetRequest(url, headers); } Future> saveReminderMailConfigApi( String token, Map payload, ) async { final url = Uri.parse('${Environment.apiUrl}saveReminderMailConfig'); final headers = { 'Authorization': 'Bearer $token', 'Content-Type': 'application/json', }; return _makePostRequest(url, jsonEncode(payload), headers); } Future> sendReminderMailApi( String clientId, String clientPolicyId, String clientBranchId, String hrId, String token, { required String emailSubject, required String emailBody, }) async { final url = Uri.parse('${Environment.apiUrl}sendReminderMail'); final headers = { 'Authorization': 'Bearer $token', 'APP-SIGNATURE': 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y', 'Content-Type': 'application/json', }; final policyId = int.tryParse(clientPolicyId) ?? clientPolicyId; final body = { 'client_id': clientId, 'client_policy_id': policyId, 'client_branch_id': clientBranchId, 'hr_id': hrId, 'email_subject': emailSubject, 'email_body': emailBody, }; return _makePostRequest(url, jsonEncode(body), headers); } Future> getClientRMApi( String postClientId, String token, ) async { final url = Uri.parse( '${Environment.apiUrlPost}getClientRM?client_id=$postClientId', ); final headers = { 'Authorization': 'Bearer $token', }; return _makeGetRequest(url, headers); } Future> getEmployeeAndDependenceToApiPre( String clintID, String getPolicyNo, String empRefId, String token, {dynamic cardData, String? searchKey}) async { logDebug(_hrtoken); if (token == null) { await _initializeToken(); } final params = { 'client_id': clintID, 'client_policy_id': getPolicyNo, 'client_branch_id': empRefId, }; if (cardData != null) { params['card_data'] = cardData.toString(); } if (searchKey != null && searchKey.trim().isNotEmpty) { params['search'] = searchKey.trim(); } final url = Uri.parse('${Environment.apiUrl}getEmployeeAndDependenceByClientId') .replace(queryParameters: params); final headers = { 'Authorization': 'Bearer $token' ?? '', }; final response = await _makeGetRequest(url, headers); return response; } // Future> getTrackClaimsList( // String empMobileNo, String empCode) async { // final url = Uri.parse( // '${Environment.apiUrlTicket}/ticket/get_ticket_data?emp_code=$empCode&mobile_number=$empMobileNo'); // final response = await _makeGetRequest(url, { // 'Token': Environment.ticketToken, // }); // return response; // } // // Future> fetchDepartmentList() async { // final url = Uri.parse('${Environment.apiUrlTicket}/departments'); // final response = await _makeGetRequest(url, { // 'Token': Environment.ticketToken, // }); // return response; // } // // Future> sendFormDataToApi( // Map formData) async { // final url = Uri.parse('${Environment.apiUrlTicket}/tickets/create'); // // Convert formData to Map // Map stringFormData = // formData.map((key, value) => MapEntry(key, value.toString())); // final response = await _makePostRequest(url, stringFormData, { // 'Content-Type': 'application/x-www-form-urlencoded', // 'Token': Environment.ticketToken, // }); // return response; // } // // Future> sendClaimsMessageToApi( // Map formData) async { // final url = Uri.parse('${Environment.apiUrlTicket}/messages/create'); // // Convert formData to Map // Map stringFormData = // formData.map((key, value) => MapEntry(key, value.toString())); // final response = await _makePostRequest(url, stringFormData, { // 'Content-Type': 'application/x-www-form-urlencoded', // 'Token': Environment.ticketToken, // }); // return response; // } // Future?> getSession() async { // try { // final url = Uri.parse('${Environment.apiUrl}session'); // // // No Authorization header here // final response = await _makeGetRequest( // url, // { // 'Content-Type': 'application/json', // }, // ); // // // _makeGetRequest already handles: // // - APP-SIGNATURE // // - 401 redirect // return response; // } catch (e) { // return null; // } // } Future logout() async { try { final url = Uri.parse('${Environment.apiUrl}logout'); await _makePostRequest( url, jsonEncode({}), // empty body { 'Content-Type': 'application/json', 'Authorization': 'Bearer $_token' ?? '', }, ); } catch (_) {} // Clear only mobile storage // if (!isWeb) { await tokenService.clearAll(); logDebug('Secure Storage Cleared'); // } if (context.mounted) { logDebug('context.mounted'); Navigator.pushNamedAndRemoveUntil( context, 'hrLogin', (route) => false, // remove all previous routes ); } } Future> _makePostRequestWithoutFormData( Uri url, String body, Map headers) async { headers['APP-SIGNATURE'] = 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y'; final response = await http.post(url, headers: headers, body: body); return _handleResponse(response); } Future> _makeGetRequest( Uri url, Map headers) async { headers['APP-SIGNATURE'] = 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y'; final response = await http.get(url, headers: headers); return _handleResponse(response); } Future> _makePostRequest( Uri url, String body, Map headers) async { headers['APP-SIGNATURE'] = 'nhance-2025-signature-T8f6gV9k5fK2wf5V5c4vId3b0J8z6cAm2x8Y'; final response = await http.post(url, headers: headers, body: body); return _handleResponse(response); } Future> _handleResponse(http.Response response) async { // 'throttle' => 429, // 'soft' => 429, // 'medium' => 403, // 'hard' => 451, if (response.statusCode == 200) { return _parseJsonBody(response); } else if (response.statusCode == 401) { if (!_isSessionOutToastShown) { _isSessionOutToastShown = true; await _clearLocalStorageAndRedirect(); } return {}; } else if (response.statusCode == 403) { if (!_isSessionOutToastShown) { _isSessionOutToastShown = true; await _clearLocalStorageAndRedirect(); } return {}; } else if (response.statusCode == 451) { final body = jsonDecode(response.body); final message = body['message']; ToastHelper.showWarningToast(context, message); return {}; } else if (response.statusCode == 429) { final body = jsonDecode(response.body); final message = body['message']; ToastHelper.showWarningToast(context, message); return {}; } else { throw Exception('Failed to load data'); } } Map _parseJsonBody(http.Response response) { try { if (response.bodyBytes.isEmpty) return {}; final text = utf8.decode(response.bodyBytes); final parsed = jsonDecode(text); if (parsed is Map) return parsed; if (parsed is Map) return Map.from(parsed); return {}; } catch (_) { return {}; } } Future _clearLocalStorageAndRedirect() async { await tokenService.clearAll(); // 🔐 clears flutter_secure_storage ToastHelper.showErrorToast(context, 'Session Out'); if (!context.mounted) return; Navigator.pushNamedAndRemoveUntil( context, 'hrLogin', (route) => false, ); } }