import 'package:file_picker/file_picker.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:http/http.dart' as http; import 'package:nhance_partner/data/services/auth_service.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'dart:convert'; import '../../data/utils/toastNotification.dart'; import '../../presentation/screens/staff/enquiry_single_page/model/dropdown_option.dart'; import '../../presentation/screens/staff/enquiry_single_page/model/enquiry_model.dart'; import '../config/env.dart'; import 'package:universal_html/html.dart' as html; import 'package:http/http.dart' as http; import '../routing/routes.dart'; class ApiService { late final BuildContext context; String? _token; Future _initializeToken() async { _token = await AuthService.getToken(); print("APISERTOKEN - $_token"); } Future clearLocalStorageAndRedirect() async { // final prefs = await SharedPreferences.getInstance(); // await prefs.clear(); // Assuming you have access to the context ToastHelper.showErrorToast(context, 'Session Out'); // Navigator.pushNamed(context, 'login'); AuthService.clearToken(); context.go(AppRoutes.login); } Future> _makeGetRequest( Uri url, Map headers, ) async { final response = await http.get(url, headers: headers); return _handleResponse(response); } // Future> _makePostRequest( // Uri url, Map body, Map headers) async { // final response = await http.post(url, headers: headers, body: body); // return _handleResponse(response); // } // // Future> _handleResponse(http.Response response) async { // if (response.statusCode == 200) { // return jsonDecode(response.body); // } else if (response.statusCode == 401) { // await clearLocalStorageAndRedirect(); // return {}; // } else { // throw Exception('Failed to load data'); // } // } Future _makeGethttpRequest( Uri url, Map headers, ) async { final response = await http.get(url, headers: headers); if (response.statusCode == 200) { return response; // return full http.Response, not Map } else if (response.statusCode == 403) { await clearLocalStorageAndRedirect(); return http.Response('Forbidden', 403); } else { ToastHelper.show('No File Found', Colors.red); throw Exception('Failed request: ${response.statusCode}'); } } Future> _makePostRequestJson( Uri url, Map body, Map headers, ) async { final response = await http.post( url, headers: headers, body: jsonEncode(body), // ✅ convert to JSON ); return _handleResponse(response); } // --------------------------- COMMON FILES __________________________________________ Future> createUserData(data, path) async { print('path - $path'); final url = Uri.parse('${Env.apiUrl}$path'); if (_token == null) { await _initializeToken(); } print("data------- $data}"); final headers = { 'Authorization': 'Bearer $_token' ?? '', 'Content-Type': 'application/json', 'app-signature': Env.App_Signature, }; final response = await _makePostRequestJson(url, data, headers); return response; } Future> fetchUploadEnquiryFiles(dynamic enqId) async { // print(_token); if (_token == null) { await _initializeToken(); } final url = Uri.parse( '${Env.apiUrl}enquiry/enquiryFiles?enquiry_id=$enqId', ); final headers = { 'Authorization': 'Bearer $_token' ?? '', 'app-signature': Env.App_Signature, }; final response = await _makeGetRequest(url, headers); return response; } Future> logoutUsingAPI(agentId) async { // print(_token); if (_token == null) { await _initializeToken(); } final url = Uri.parse('${Env.apiUrl}auth/logout'); final headers = { 'Authorization': 'Bearer $_token' ?? '', 'app-signature': Env.App_Signature, }; final response = await _makeGetRequest(url, headers); return response; } Future> _handleResponse(http.Response response) async { if (response.statusCode == 200) { return jsonDecode(response.body); } else if (response.statusCode == 401 || response.statusCode == 403) { await clearLocalStorageAndRedirect(); return {}; } else { throw Exception('Failed to load data'); } } Future> CheckDuplicate( BuildContext context, String value, ) async { if (_token == null) { await _initializeToken(); } String apiUrldata; final response = await http.get( Uri.parse('${Env.apiUrl}enquiry/checkVehicleDuplicate?reg_no=$value'), headers: { 'Authorization': 'Bearer $_token' ?? '', 'app-signature': Env.App_Signature, }, ); if (response.statusCode == 200) { try { final data = json.decode(response.body); // Updated to match actual response structure if (data['status'] == "exists") { final msg = data['message'] ?? "Already exists"; final field = data['field'] ?? ""; print("$field - $value : $msg"); print("EXIST REG"); return {"message": msg, "field": field}; } else { print("NOT EXIST REG"); // print("$value : ${data['message'] ?? "is a new value"}"); return {}; } } catch (e) { throw Exception('Error parsing response: $e'); } } else if (response.statusCode == 403) { await clearLocalStorageAndRedirect(); return {}; } else { throw Exception( 'Failed to load checkDuplicate data. Status code: ${response.statusCode}', ); } } Future getPdfDownload1(path, id) async { // final url = Uri.parse( // 'https://venbait.in/nhance/partner/dev/api/agent/downloadAgentCertificateFile?agent_id=1', // ); print('GetDownload'); final url = Uri.parse('https://venbait.in/nhance/partner/dev/$path'); print('GetDownload - $url'); await _initializeToken(); if (_token == null) { throw Exception('Token not found. Please log in.'); } final headers = { 'Authorization': 'Bearer $_token' ?? '', 'app-signature': Env.App_Signature, }; final response = await _makeGethttpRequest(url, headers); if (response.statusCode == 200) { try { print("PDf Dowloaded"); // Create a blob from the response body final blob = html.Blob([response.bodyBytes]); // Generate a download URL for the blob final url = html.Url.createObjectUrlFromBlob(blob); // Create a link element to trigger the download final anchor = html.AnchorElement(href: url) ..setAttribute('download', 'nhancePartner_$id.pdf') ..click(); // Revoke the download URL to free up resources html.Url.revokeObjectUrl(url); } catch (e) { throw Exception('Error parsing response: $e'); } } else if (response.statusCode == 404) { showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: Text('File not found.'), // content: Text('File not found.'), actions: [ TextButton( child: Text('OK'), onPressed: () { Navigator.of(context).pop(); // Close the dialog }, ), ], ); }, ); } else { throw Exception('Failed to load plans'); } } String extractFileName(String? contentDisposition, String fallback) { if (contentDisposition == null) return fallback; // Check for extended filename first (RFC 5987) final filenameStarMatch = RegExp( r'filename\*\s*=\s*([^;]+)', ).firstMatch(contentDisposition); if (filenameStarMatch != null) { String value = filenameStarMatch.group(1)!; // Remove UTF-8'' prefix if exists value = value.replaceAll(RegExp(r"UTF-8''"), ''); return Uri.decodeFull(value.replaceAll('"', '')); } // Fallback to regular filename= final filenameMatch = RegExp( r'filename\s*=\s*"?([^";]+)"?', ).firstMatch(contentDisposition); if (filenameMatch != null) { return filenameMatch.group(1)!; } // Fallback: use the provided fallback string return fallback; } Future getPdfDownload( // BuildContext context, String path, String id, ) async { print('getPdfDownload 1 - $path'); // if (path.isEmpty) { // ToastHelper.showInfoToast(context, 'No file path found.'); // return; // } final url = Uri.parse('https://venbait.in/nhance/partner/dev/$path'); print('getPdfDownload 2 - $url'); await _initializeToken(); if (_token == null) throw Exception('Token not found. Please log in.'); final headers = { 'Authorization': 'Bearer $_token', // 'App-Signature': Env.App_Signature, 'app-signature': Env.App_Signature, }; final response = await _makeGethttpRequest(url, headers); if (response.statusCode == 200) { final contentType = response.headers['content-type'] ?? ''; if (contentType.contains('application/json')) { final jsonResponse = jsonDecode(response.body); if (jsonResponse['code'] == 404 || jsonResponse['code'] == 500) { ToastHelper.show('File Not Found', Colors.red); } else { ToastHelper.show('No File Found', Colors.red); } return; } else { final blob = html.Blob([response.bodyBytes]); final blobUrl = html.Url.createObjectUrlFromBlob(blob); print('getPdfDownload $blobUrl'); // --- filename resolution --- // String fileName = 'download_$id'; // print('getPdfDownloadfileName $fileName'); // final contentDisp = response.headers['content-disposition']; // print('getPdfDownloadcontentDisp $contentDisp'); // if (contentDisp != null && contentDisp.contains('filename=')) { // print('getPdfDownloadcontentDisp..1'); // fileName = contentDisp.split('filename=')[1].replaceAll('"', ''); // print('getPdfDownloadcontentDisp..2'); // } else { // print('getPdfDownloadcontentDisp..3'); // // fallback: URL or id // fileName = path.split('/').last; // if (id != null) fileName = '${id}_$fileName'; // } final contentDisp = response.headers['content-disposition']; print('getPdfDownloadcontentDisp $contentDisp'); String fileName = extractFileName(contentDisp, path.split('/').last); print('Resolved fileName: $fileName'); final anchor = html.AnchorElement(href: blobUrl) ..setAttribute('download', fileName) ..click(); html.Url.revokeObjectUrl(blobUrl); } } else if (response.statusCode == 404) { showDialog( context: context, builder: (context) => AlertDialog( title: const Text('File not found.'), actions: [ TextButton( child: const Text('OK'), onPressed: () => Navigator.of(context).pop(), ), ], ), ); } else if (response.statusCode == 403) { await clearLocalStorageAndRedirect(); } else if (response.statusCode == 500) { ToastHelper.show('No File Found', Colors.red); } else if (response.statusCode == 302) { print('getPdfDownload 3-PP-302'); ToastHelper.show('No File Found', Colors.red); } else { ToastHelper.show('No File Found', Colors.red); throw Exception('Failed to download file'); } } Future downloadFile({ required String? apiUrl, required PlatformFile? localFile, required String? fileName, String? apiId, // optional if your API needs it }) async { try { if (localFile != null) { if (kIsWeb) { final blob = html.Blob([localFile.bytes!]); final url = html.Url.createObjectUrlFromBlob(blob); final anchor = html.AnchorElement(href: url) ..setAttribute('download', localFile.name) ..click(); html.Url.revokeObjectUrl(url); print("Download triggered successfully (web)!"); } else { print("Local file path: ${localFile.path}"); // await OpenFilex.open(localFile.path!); } } else if (apiUrl != null) { print("Download from API: $apiUrl"); print("Download from API: $apiId!"); await getPdfDownload(apiUrl, apiId!); } else { print("⚠️ No file available to download"); } } catch (e) { print("Error during download: $e"); } } Future> updateStatus(id, status, role) async { print('updateStatusupdateStatus'); final Map data = { "id": int.parse(id), "is_active": int.parse(status), }; final url; if (role == 'staff') { url = Uri.parse('${Env.apiUrl}staff/changeStaffStatus'); } else { url = Uri.parse('${Env.apiUrl}/api/agent/changeAgentStatus'); } // final token = await getToken(); // Fetch token if (_token == null) { throw Exception('Token not found. Please log in.'); } print("data------- $data}"); final headers = { 'Authorization': 'Bearer $_token', 'Content-Type': 'application/json', 'app-signature': Env.App_Signature, // 'app-signature': 'nhance-partner-2025-signature-35468846JRhH551HK', }; final response = await _makePostRequestJson(url, data, headers); return response; } Future> updateStatusMasters( id, status, masterName, userId, ) async { print('updateStatusMaster $id $status $masterName $userId'); final Map data = { "is_active": int.parse(status), "updated_by": userId, }; final url; if (masterName == 'Broker') { url = Uri.parse('${Env.apiUrl}master/updateBrokerStatus/$id'); } else { url = Uri.parse('${Env.apiUrl}master/updatePaymentModeStatus/$id'); } // final token = await getToken(); // Fetch token if (_token == null) { throw Exception('Token not found. Please log in.'); } print("data------- $data}"); final headers = { 'Authorization': 'Bearer $_token', 'Content-Type': 'application/json', 'app-signature': Env.App_Signature, // 'app-signature': 'nhance-partner-2025-signature-35468846JRhH551HK', }; final response = await _makePostRequestJson(url, data, headers); return response; } // ----------------------------------- Dashboard ------------------------------------------------- Future> fetchDashboard(int id, role, userId) async { // print(_token); if (_token == null) { await _initializeToken(); } final url; if (role == 'manager') { url = Uri.parse('${Env.apiUrl}dashboard/managerDashboard?manager_id=$id'); } else if (role == 'handler') { url = Uri.parse( '${Env.apiUrl}dashboard/handlerDashboard?manager_id=$id&handler_id=$userId', ); } else if (role == 'staff') { url = Uri.parse('${Env.apiUrl}dashboard/staffDashboard?staff_id=$userId'); } else { url = Uri.parse('${Env.apiUrl}dashboard/agentDashboard?agent_id=$userId'); } // final url = Uri.parse( // 'https://venbait.in/nhance/partner/dev/api/agent/agentList?manager_id=${managerId}', // ); final headers = { 'Authorization': 'Bearer $_token' ?? '', 'app-signature': Env.App_Signature, }; final response = await _makeGetRequest(url, headers); return response; } Future> findBusinessDashboardData(id, broker) async { // print(_token); if (_token == null) { await _initializeToken(); } final url = Uri.parse( '${Env.apiUrl}dashboard/businessDashboard?manager_id=$id', ); final headers = { 'Authorization': 'Bearer $_token' ?? '', 'app-signature': Env.App_Signature, }; final response = await _makeGetRequest(url, headers); return response; } Future> findPartnerDashboardData(id, broker) async { // print(_token); if (_token == null) { await _initializeToken(); } final url = Uri.parse( '${Env.apiUrl}dashboard/partnerDashboard?manager_id=$id', ); final headers = { 'Authorization': 'Bearer $_token' ?? '', 'app-signature': Env.App_Signature, }; final response = await _makeGetRequest(url, headers); return response; } // -------------------------------- AGENT ---------------------------------------------- Future> fetchAgentIncentiveList(agentId) async { // print(_token); if (_token == null) { await _initializeToken(); } final url = Uri.parse( '${Env.apiUrl}agent/agentIncentiveFileList?agent_id=${agentId}', ); // final url = Uri.parse( // 'https://venbait.in/nhance/partner/dev/api/agent/agentIncentiveFileList?agent_id=${agentId}', // ); final headers = { 'Authorization': 'Bearer $_token' ?? '', 'app-signature': Env.App_Signature, }; final response = await _makeGetRequest(url, headers); return response; } Future> fetchManagerIncentiveList(mangerId) async { // print(_token); if (_token == null) { await _initializeToken(); } final url = Uri.parse( '${Env.apiUrl}staff/managerIncentiveFileList?manager_id=$mangerId', ); final headers = { 'Authorization': 'Bearer $_token' ?? '', 'app-signature': Env.App_Signature, }; final response = await _makeGetRequest(url, headers); return response; } Future> fetchAgentUserList(int managerId) async { // print(_token); if (_token == null) { await _initializeToken(); } final userId = '1'; final url = Uri.parse( '${Env.apiUrl}agent/agentList?manager_id=${managerId}', ); final headers = { 'Authorization': 'Bearer $_token' ?? '', 'app-signature': Env.App_Signature, }; final response = await _makeGetRequest(url, headers); return response; } Future> findSingleAgentData(id) async { // print(_token); if (_token == null) { await _initializeToken(); } // final url = Uri.parse('${Env.apiUrl}/api/agent/agentList'); // final url = Uri.parse( // 'https://venbait.in/nhance/partner/dev/api/agent/findAgent?id=$id', // ); final url = Uri.parse('${Env.apiUrl}agent/findAgent?id=$id'); final headers = { 'Authorization': 'Bearer $_token' ?? '', 'app-signature': Env.App_Signature, }; final response = await _makeGetRequest(url, headers); return response; } Future> deleteAgentIncentiveFile(id) async { // print(_token); if (_token == null) { await _initializeToken(); } // final url = Uri.parse('${Env.apiUrl}/api/agent/agentList'); // final url = Uri.parse( // 'https://venbait.in/nhance/partner/dev/api/agent/deleteAgentIncentiveFile?id=$id', // ); final url = Uri.parse('${Env.apiUrl}agent/deleteAgentIncentiveFile?id=$id'); final headers = { 'Authorization': 'Bearer $_token' ?? '', 'app-signature': Env.App_Signature, }; final response = await _makeGetRequest(url, headers); return response; } // ------------------------------------ STAFF ----------------------------------------------------- Future> fetchStaffUserList(int managerId, role) async { // print(_token); print('rolemanagerId - $managerId'); if (_token == null) { await _initializeToken(); } // final url = Uri.parse( // 'https://venbait.in/nhance/partner/dev/api/staff/staffList?manager_id=${managerId}', // ); dynamic url; if (role == 'manager') { print('manager'); // url = Uri.parse('${Env.apiUrl}staff/staffList'); url = Uri.parse('${Env.apiUrl}staff/staffList?manager_id=${managerId}'); } else { print('handler'); url = Uri.parse('${Env.apiUrl}staff/staffList?handler_id=${managerId}'); } final headers = { 'Authorization': 'Bearer $_token' ?? '', 'app-signature': Env.App_Signature, }; final response = await _makeGetRequest(url, headers); return response; } Future> findSingleStaffData(id) async { // print(_token); if (_token == null) { await _initializeToken(); } // final url = Uri.parse('${Env.apiUrl}/api/staff/findStaff?id=$id'); // final url = Uri.parse( // 'https://venbait.in/nhance/partner/dev/api/staff/findStaff?id=$id', // ); final url = Uri.parse('${Env.apiUrl}staff/findStaff?id=$id'); final headers = { 'Authorization': 'Bearer $_token' ?? '', 'app-signature': Env.App_Signature, }; final response = await _makeGetRequest(url, headers); return response; } // ----------------------------------- ENQUIRY ------------------------------------------------- Future> fetchEnquiryList1(int id, role) async { // print(_token); if (_token == null) { await _initializeToken(); } final url; if (role == 'manager') { url = Uri.parse( '${Env.apiUrl}enquiry/enquiryList?manager_id=$id&from_date=&to_date=', ); } else if (role == 'staff') { url = Uri.parse( '${Env.apiUrl}enquiry/enquiryList?staff_id=$id&from_date=&to_date=', ); } else { url = Uri.parse( '${Env.apiUrl}enquiry/enquiryList?agent_id=$id&from_date=&to_date=', ); } // final url = Uri.parse( // 'https://venbait.in/nhance/partner/dev/api/agent/agentList?manager_id=${managerId}', // ); final headers = { 'Authorization': 'Bearer $_token' ?? '', 'app-signature': Env.App_Signature, }; final response = await _makeGetRequest(url, headers); return response; } Future> fetchEnquiryList( int managerid, int id, String role, { String? fromDate, String? toDate, String? selectedStatus, String? selectedStaffId, }) async { print("selectedStatusselectedStatus - $selectedStatus"); if (_token == null) { await _initializeToken(); } final String query; // if (role == 'manager' || role == 'handler') { // query = 'manager_id=$id'; // } if (role == 'manager') { query = 'manager_id=$id'; } else if (role == 'handler') { query = 'handler_id=$id'; } else if (role == 'staff') { query = 'staff_id=$id'; } else { query = 'agent_id=$id'; } // final url = Uri.parse( // '${Env.apiUrl}enquiry/enquiryList?$query&from_date=${fromDate ?? ''}&to_date=${toDate ?? ''}', // ); final url; if (role == 'staff') { url = Uri.parse( '${Env.apiUrl}enquiry/enquiryList?$query&from_date=${fromDate ?? ''}&to_date=${toDate ?? ''}&enquiry_status=$selectedStatus', // '${Env.apiUrl}enquiry/enquiryList?$query&from_date=${fromDate ?? ''}&to_date=${toDate ?? ''}&status=$selectedStatus', ); } else { url = Uri.parse( '${Env.apiUrl}enquiry/enquiryList?$query&from_date=${fromDate ?? ''}&to_date=${toDate ?? ''}&enquiry_status=$selectedStatus&staff_id=$selectedStaffId', // '${Env.apiUrl}enquiry/enquiryList?$query&from_date=${fromDate ?? ''}&to_date=${toDate ?? ''}&status=$selectedStatus&staff_id=$selectedStaffId', ); } final headers = { 'Authorization': 'Bearer $_token' ?? '', 'app-signature': Env.App_Signature, }; final response = await _makeGetRequest(url, headers); return response; } Future> fetchAttndanceOFAllStaffList({ required String month, required dynamic mangerId, }) async { if (_token == null) { await _initializeToken(); } final String query; // if (role == 'manager') { // query = 'manager_id=$id'; // } final url = Uri.parse( '${Env.apiUrl}staff/monthlyLoginCount?month=${month ?? ''}&manager_id=$mangerId', ); final headers = { 'Authorization': 'Bearer $_token' ?? '', 'app-signature': Env.App_Signature, }; final response = await _makeGetRequest(url, headers); return response; } Future> fetchAttndanceOfIndiviualStaffList({ String? month, id, }) async { if (_token == null) { await _initializeToken(); } final String query; final url = Uri.parse( '${Env.apiUrl}staff/staffLoggedDays?month=${month ?? ''}&staff_id=$id', ); final headers = { 'Authorization': 'Bearer $_token' ?? '', 'app-signature': Env.App_Signature, }; final response = await _makeGetRequest(url, headers); return response; } Future> findSingleEnquiryData(id) async { // print(_token); if (_token == null) { await _initializeToken(); } final url = Uri.parse('${Env.apiUrl}enquiry/enquiryList?enquiry_id=$id'); final headers = { 'Authorization': 'Bearer $_token' ?? '', 'app-signature': Env.App_Signature, }; final response = await _makeGetRequest(url, headers); return response; } Future> updateEnquiryInProgress(id) async { // print(_token); if (_token == null) { await _initializeToken(); } final url = Uri.parse( '${Env.apiUrl}enquiry/updateEnquiryInProgress?enquiry_id=$id', ); final headers = { 'Authorization': 'Bearer $_token' ?? '', 'app-signature': Env.App_Signature, }; final response = await _makeGetRequest(url, headers); return response; } Future> findEnqQuotePolicyView(id) async { print('findEnqQuotePolicyVie2w - $id'); if (_token == null) { print('findEnqQuotePolicyVie2w 1'); await _initializeToken(); print('findEnqQuotePolicyVie2w 2'); } final url = Uri.parse( '${Env.apiUrl}enquiry/enquiryQuotePolicyView?enquiry_id=$id', ); final headers = { 'Authorization': 'Bearer $_token' ?? '', 'app-signature': Env.App_Signature, }; print('findEnqQuotePolicyVie2w 3'); final response = await _makeGetRequest(url, headers); if (response.containsKey('error')) { print( '❌ API returned invalid JSON or HTML. Raw response: ${response['raw']}', ); return {}; // return empty map on error } print('findEnqQuotePolicyView 1'); print('findEnqQuotePolicyView 1 - $response'); return response; } Future> deleteEnquiy(id, val) async { final url = Uri.parse( '${Env.apiUrl}/enquiry/updateEnquiryStatus?enquiry_id=$id&is_active=$val', ); // final token = await getToken(); // Fetch token if (_token == null) { throw Exception('Token not found. Please log in.'); } final headers = { 'Authorization': 'Bearer $_token', 'Content-Type': 'application/json', 'app-signature': Env.App_Signature, // 'app-signature': 'nhance-partner-2025-signature-35468846JRhH551HK', }; // final response = await _makePostRequestJson(url, data, headers); final response = await _makeGetRequest(url, headers); return response; } //------------------------------------ Quotation ------------------------------------------------ Future> fetchQuickQuotationList(int managerId) async { // print(_token); if (_token == null) { await _initializeToken(); } final url = Uri.parse( '${Env.apiUrl}enquiry/getQuickQuoteEnquiryList?manager_id=${managerId}', ); final headers = { 'Authorization': 'Bearer $_token' ?? '', 'app-signature': Env.App_Signature, }; final response = await _makeGetRequest(url, headers); return response; } Future> fetchQuotationList(int managerId) async { // print(_token); if (_token == null) { await _initializeToken(); } // final url = Uri.parse( // 'https://venbait.in/nhance/partner/dev/api/staff/staffList?manager_id=${managerId}', // ); final url = Uri.parse( '${Env.apiUrl}quotation/quotationList?manager_id=${managerId}', ); final headers = { 'Authorization': 'Bearer $_token' ?? '', 'app-signature': Env.App_Signature, }; final response = await _makeGetRequest(url, headers); return response; } Future> findSingleQuotationData(id) async { // print(_token); if (_token == null) { await _initializeToken(); } final url = Uri.parse('${Env.apiUrl}quotation/findQuotation?id=$id'); final headers = { 'Authorization': 'Bearer $_token' ?? '', 'app-signature': Env.App_Signature, }; final response = await _makeGetRequest(url, headers); return response; } // ----------------------------------- POLICY ------------------------------------------------- Future> fetchPolicyList( int id, role, { String? fromDate, String? toDate, String? selectedStatus, String? selectedStaffId, }) async { // print(_token); if (_token == null) { await _initializeToken(); } final url; final String query; final String val = 'Proposal Created'; if (role == 'manager') { query = 'manager_id=$id'; } else if (role == 'staff') { query = 'staff_id=$id'; } else { query = 'agent_id=$id'; } // url = Uri.parse( // '${Env.apiUrl}enquiry/enquiryList?$query&from_date=${fromDate ?? ''}&to_date=${toDate ?? ''}', // ); if (role == 'staff') { url = Uri.parse( '${Env.apiUrl}enquiry/enquiryList?$query&from_date=${fromDate ?? ''}&to_date=${toDate ?? ''}&status=$selectedStatus', ); } else { url = Uri.parse( '${Env.apiUrl}enquiry/enquiryList?$query&from_date=${fromDate ?? ''}&to_date=${toDate ?? ''}&status=$selectedStatus&staff_id=$selectedStaffId', ); } // if (role == 'manager') { // url = Uri.parse('${Env.apiUrl}enquiry/enquiryList?manager_id=$id'); // } else { // url = Uri.parse('${Env.apiUrl}enquiry/enquiryList?staff_id=$id'); // } // else { // url = Uri.parse('${Env.apiUrl}endorsement/endorsementList?agent_id=$id'); // } // final url = Uri.parse( // 'https://venbait.in/nhance/partner/dev/api/agent/agentList?manager_id=${managerId}', // ); final headers = { 'Authorization': 'Bearer $_token' ?? '', 'app-signature': Env.App_Signature, }; final response = await _makeGetRequest(url, headers); return response; } Future> fetchPolicyDataOnlyList( dynamic id, role, { String? fromDate, String? toDate, String? selectedStaffId, }) async { // print(_token); if (_token == null) { await _initializeToken(); } final userId = '1'; final String query; if (role == 'manager') { query = 'manager_id=$id'; } else if (role == 'staff') { query = 'staff_id=$id'; } else if (role == 'handler') { query = 'handler_id=$id'; } else { query = 'agent_id=$id'; } final url = Uri.parse( '${Env.apiUrl}enquiry/enquiryList?$query&only_policy_data=true&from_date=${fromDate ?? ''}&to_date=${toDate ?? ''}&staff_id=$selectedStaffId', ); // if (role == 'manager') { // url = Uri.parse( // '${Env.apiUrl}enquiry/enquiryList?manager_id=$id&only_policy_data=true', // ); // } else if (role == 'staff') { // url = Uri.parse( // '${Env.apiUrl}enquiry/enquiryList?staff_id=$id&only_policy_data=true', // ); // } else { // url = Uri.parse( // '${Env.apiUrl}enquiry/enquiryList?agent_id=$id&only_policy_data=true', // ); // } // final url = Uri.parse( // 'https://venbait.in/nhance/partner/dev/api/agent/agentList?manager_id=${managerId}', // ); final headers = { 'Authorization': 'Bearer $_token' ?? '', 'app-signature': Env.App_Signature, }; final response = await _makeGetRequest(url, headers); return response; } // ----------------------------------- CLAIMS ------------------------------------------------- Future> fetchClaimList(int id, role) async { // print(_token); if (_token == null) { await _initializeToken(); } final userId = '1'; final url; if (role == 'manager') { url = Uri.parse('${Env.apiUrl}claim/ClaimList?manager_id=$id'); } else if (role == 'agent') { url = Uri.parse('${Env.apiUrl}claim/ClaimList?agent_id=$id'); } else if (role == 'handler') { url = Uri.parse('${Env.apiUrl}claim/ClaimList?handler_id=$id'); } else { url = Uri.parse('${Env.apiUrl}claim/ClaimList?staff_id=$id'); } // final url = Uri.parse( // 'https://venbait.in/nhance/partner/dev/api/agent/agentList?manager_id=${managerId}', // ); final headers = { 'Authorization': 'Bearer $_token' ?? '', 'app-signature': Env.App_Signature, }; final response = await _makeGetRequest(url, headers); return response; } Future> findSingleClaimData(id) async { // print(_token); if (_token == null) { await _initializeToken(); } final url = Uri.parse('${Env.apiUrl}claim/ClaimList?policy_number=$id'); final headers = { 'Authorization': 'Bearer $_token' ?? '', 'app-signature': Env.App_Signature, }; final response = await _makeGetRequest(url, headers); return response; } // ----------------------------------- ENDORSEMENT ------------------------------------------------- Future> fetchEndorsementList(int id, role) async { // print(_token); if (_token == null) { await _initializeToken(); } final userId = '1'; final url; if (role == 'manager') { url = Uri.parse( '${Env.apiUrl}endorsement/endorsementList?manager_id=$id', ); } else if (role == 'agent') { url = Uri.parse('${Env.apiUrl}endorsement/endorsementList?agent_id=$id'); } else if (role == 'handler') { url = Uri.parse('${Env.apiUrl}enquiry/enquiryList?handler_id=$id'); } else { url = Uri.parse('${Env.apiUrl}endorsement/endorsementList?staff_id=$id'); } // final url = Uri.parse( // 'https://venbait.in/nhance/partner/dev/api/agent/agentList?manager_id=${managerId}', // ); final headers = { 'Authorization': 'Bearer $_token' ?? '', 'app-signature': Env.App_Signature, }; final response = await _makeGetRequest(url, headers); return response; } Future> findSingleEnrosmentData(id) async { // print(_token); if (_token == null) { await _initializeToken(); } final url = Uri.parse( '${Env.apiUrl}endorsement/endorsementList?policy_number=$id', ); final headers = { 'Authorization': 'Bearer $_token' ?? '', 'app-signature': Env.App_Signature, }; final response = await _makeGetRequest(url, headers); return response; } // --------------------------------- MASTER DATA DROPDOWN---------------------------------------------- Future> fetchMasterDropDown(String val) async { // print(_token); if (_token == null) { await _initializeToken(); } print('VAl - $val'); dynamic url; if (val == 'staffRole') { url = Uri.parse('${Env.apiUrl}master/getRoleMaster'); } else if (val == 'vehicleType') { url = Uri.parse('${Env.apiUrl}master/getVehicleTypeMaster'); } else if (val == 'InsuranceType') { url = Uri.parse('${Env.apiUrl}master/getInsurancePlanTypeMaster'); } else if (val == 'Insurers') { url = Uri.parse('${Env.apiUrl}master/getInsurersMaster'); } else if (val == 'Staffs') { url = Uri.parse('${Env.apiUrl}master/getStaffMaster'); } else if (val == 'Claim') { url = Uri.parse('${Env.apiUrl}master/getClaimMaster'); } else if (val == 'Endorsement') { url = Uri.parse('${Env.apiUrl}master/getEndorsementMaster'); } else if (val == 'Broker') { url = Uri.parse('${Env.apiUrl}master/getAllBrokers'); } else if (val == 'PaymentMode') { url = Uri.parse('${Env.apiUrl}master/getAllPaymentModelist'); } final headers = { 'Authorization': 'Bearer $_token' ?? '', 'app-signature': Env.App_Signature, }; final response = await _makeGetRequest(url, headers); return response; } Future> fetchHandlerNameDropDown(id) async { print('fetchHandlerNameDropDown'); if (_token == null) { await _initializeToken(); } dynamic url; print('fetchHandlerNameDropDown 1'); url = Uri.parse( '${Env.apiUrl}staff/handlerListForStaffCreationDropdown?manager_id=$id', ); print('fetchHandlerNameDropDown 2'); final headers = { 'Authorization': 'Bearer $_token' ?? '', 'app-signature': Env.App_Signature, }; print('fetchHandlerNameDropDown 3'); final response = await _makeGetRequest(url, headers); print('fetchHandlerNameDropDown 4 - $response'); return response; } Future> fetchStaffListForEnquiryAssignDropDown( id, role, ) async { print('fetchHandlerNameDropDown'); if (_token == null) { await _initializeToken(); } dynamic url; print('fetchHandlerNameDropDown 1'); if (role == 'manager') { url = Uri.parse( '${Env.apiUrl}staff/staffListForEnquiryAssignDropdown?manager_id=$id', ); } else { url = Uri.parse( '${Env.apiUrl}staff/staffListForEnquiryAssignDropdown?handler_id=$id', ); } print('fetchHandlerNameDropDown 2'); final headers = { 'Authorization': 'Bearer $_token' ?? '', 'app-signature': Env.App_Signature, }; print('fetchHandlerNameDropDown 3'); final response = await _makeGetRequest(url, headers); print('fetchHandlerNameDropDown 4 - $response'); return response; } Future> fetchAgentNameDropDown(id) async { print('fetchAGENTNameDropDown'); if (_token == null) { await _initializeToken(); } dynamic url; print('fetchAGENTNameDropDown 1'); url = Uri.parse( '${Env.apiUrl}agent/agentListForEnquiryCreationDropdown?manager_id=$id', ); print('fetchAGENTNameDropDown 2'); final headers = { 'Authorization': 'Bearer $_token' ?? '', 'app-signature': Env.App_Signature, }; print('fetchAGENTNameDropDown 3'); final response = await _makeGetRequest(url, headers); print('fetchAGENTNameDropDown 4 - $response'); return response; } static late String _baseUrl; static void initialize(String baseUrl) { _baseUrl = Env.apiUrl; } // Fetch all enquiries static Future> fetchEnquiries() async { try { final response = await http.get( Uri.parse('$_baseUrl/api/enquiries'), headers: {'Content-Type': 'application/json'}, ); if (response.statusCode == 200) { final List data = json.decode(response.body); return data.map((json) => EnquiryModel.fromJson(json)).toList(); } else { throw Exception('Failed to load enquiries'); } } catch (e) { throw Exception('Error fetching enquiries: $e'); } } // Create new enquiry static Future createEnquiry(EnquiryModel enquiry) async { try { final response = await http.post( Uri.parse('$_baseUrl/api/enquiries'), headers: {'Content-Type': 'application/json'}, body: json.encode(enquiry.toJson()), ); if (response.statusCode == 200 || response.statusCode == 201) { return EnquiryModel.fromJson(json.decode(response.body)); } else { throw Exception('Failed to create enquiry'); } } catch (e) { throw Exception('Error creating enquiry: $e'); } } // Update enquiry static Future updateEnquiry( String id, EnquiryModel enquiry, ) async { try { final response = await http.put( Uri.parse('$_baseUrl/api/enquiries/$id'), headers: {'Content-Type': 'application/json'}, body: json.encode(enquiry.toJson()), ); if (response.statusCode == 200) { return EnquiryModel.fromJson(json.decode(response.body)); } else { throw Exception('Failed to update enquiry'); } } catch (e) { throw Exception('Error updating enquiry: $e'); } } // Fetch dropdown options static Future> fetchDropdownOptions(String type) async { try { final response = await http.get( Uri.parse('$_baseUrl/api/options/$type'), headers: {'Content-Type': 'application/json'}, ); if (response.statusCode == 200) { final List data = json.decode(response.body); return data.map((json) => DropdownOption.fromJson(json)).toList(); } else { throw Exception('Failed to load options'); } } catch (e) { throw Exception('Error fetching options: $e'); } } // --------------------------------- PayOut Module---------------------------------------------- Future> getCommissionRateList(data) async { final url = Uri.parse('${Env.apiUrl}/invoice/commission-rate-list'); // final token = await getToken(); // Fetch token if (_token == null) { throw Exception('Token not found. Please log in.'); } print("data------- $data}"); final headers = { 'Authorization': 'Bearer $_token', 'Content-Type': 'application/json', 'app-signature': Env.App_Signature, // 'app-signature': 'nhance-partner-2025-signature-35468846JRhH551HK', }; final response = await _makePostRequestJson(url, data, headers); return response; } Future> getCreateOrUpdate(data) async { final url = Uri.parse('${Env.apiUrl}/invoice/create-or-update'); // final token = await getToken(); // Fetch token if (_token == null) { throw Exception('Token not found. Please log in.'); } print("data------- $data}"); final headers = { 'Authorization': 'Bearer $_token', 'Content-Type': 'application/json', 'app-signature': Env.App_Signature, // 'app-signature': 'nhance-partner-2025-signature-35468846JRhH551HK', }; final response = await _makePostRequestJson(url, data, headers); return response; } Future> getInvoiceList() async { // print(_token); if (_token == null) { await _initializeToken(); } final url = Uri.parse('${Env.apiUrl}invoice/list'); final headers = { 'Authorization': 'Bearer $_token' ?? '', 'app-signature': Env.App_Signature, }; final response = await _makeGetRequest(url, headers); return response; } Future> deleteInvoice(ID) async { // print(_token); if (_token == null) { await _initializeToken(); } final url = Uri.parse('${Env.apiUrl}invoice/delete?id=$ID'); final headers = { 'Authorization': 'Bearer $_token' ?? '', 'app-signature': Env.App_Signature, }; final response = await _makeGetRequest(url, headers); return response; } Future> delete(ID, path) async { // print(_token); if (_token == null) { await _initializeToken(); } final url = Uri.parse('${Env.apiUrl}$path'); final headers = { 'Authorization': 'Bearer $_token' ?? '', 'app-signature': Env.App_Signature, }; final response = await _makeGetRequest(url, headers); return response; } Future> getInvoiceDetails(ID) async { // print(_token); if (_token == null) { await _initializeToken(); } final url = Uri.parse('${Env.apiUrl}invoice/details?id=$ID'); final headers = { 'Authorization': 'Bearer $_token' ?? '', 'app-signature': Env.App_Signature, }; final response = await _makeGetRequest(url, headers); return response; } }