// lib/services/api_service.dart import 'dart:io'; import 'dart:convert'; import 'package:flutter/foundation.dart'; import 'package:http/http.dart' as http; import 'package:path/path.dart' as p; import 'package:sqflite/sqflite.dart'; import 'package:path_provider/path_provider.dart'; import 'package:intl/intl.dart'; import 'package:environment_monitoring_app/services/base_api_service.dart'; import 'package:environment_monitoring_app/services/telegram_service.dart'; import 'package:environment_monitoring_app/models/in_situ_sampling_data.dart'; import 'package:environment_monitoring_app/models/tarball_data.dart'; import 'package:environment_monitoring_app/models/air_collection_data.dart'; import 'package:environment_monitoring_app/models/air_installation_data.dart'; import 'package:environment_monitoring_app/models/river_in_situ_sampling_data.dart'; // START CHANGE: Added import for ServerConfigService to get the base URL import 'package:environment_monitoring_app/services/server_config_service.dart'; // END CHANGE // ======================================================================= // Part 1: Unified API Service // ======================================================================= /// A unified service that consolidates all API interactions for the application. // ... (ApiService class definition remains the same) class ApiService { final BaseApiService _baseService = BaseApiService(); final DatabaseHelper dbHelper = DatabaseHelper(); // START CHANGE: Added ServerConfigService to provide the base URL for API calls final ServerConfigService _serverConfigService = ServerConfigService(); // END CHANGE late final MarineApiService marine; late final RiverApiService river; late final AirApiService air; static const String imageBaseUrl = 'https://dev14.pstw.com.my/'; ApiService({required TelegramService telegramService}) { // START CHANGE: Pass the ServerConfigService to the sub-services marine = MarineApiService(_baseService, telegramService, _serverConfigService); river = RiverApiService(_baseService, telegramService, _serverConfigService); air = AirApiService(_baseService, telegramService, _serverConfigService); // END CHANGE } // --- Core API Methods (Unchanged) --- // START CHANGE: Update all calls to _baseService to pass the required baseUrl Future> login(String email, String password) async { final baseUrl = await _serverConfigService.getActiveApiUrl(); return _baseService.post(baseUrl, 'auth/login', {'email': email, 'password': password}); } Future> register({ required String username, String? firstName, String? lastName, required String email, required String password, String? phoneNumber, int? departmentId, int? companyId, int? positionId, }) async { final baseUrl = await _serverConfigService.getActiveApiUrl(); final Map body = { 'username': username, 'email': email, 'password': password, 'first_name': firstName ?? '', 'last_name': lastName ?? '', 'phone_number': phoneNumber ?? '', 'department_id': departmentId, 'company_id': companyId, 'position_id': positionId, }; body.removeWhere((key, value) => value == null); return _baseService.post(baseUrl, 'auth/register', body); } Future> post(String endpoint, Map data) async { final baseUrl = await _serverConfigService.getActiveApiUrl(); return _baseService.post(baseUrl, endpoint, data); } Future> getProfile() async { final baseUrl = await _serverConfigService.getActiveApiUrl(); return _baseService.get(baseUrl, 'profile'); } Future> getAllUsers() async { final baseUrl = await _serverConfigService.getActiveApiUrl(); return _baseService.get(baseUrl, 'users'); } Future> getAllDepartments() async { final baseUrl = await _serverConfigService.getActiveApiUrl(); return _baseService.get(baseUrl, 'departments'); } Future> getAllCompanies() async { final baseUrl = await _serverConfigService.getActiveApiUrl(); return _baseService.get(baseUrl, 'companies'); } Future> getAllPositions() async { final baseUrl = await _serverConfigService.getActiveApiUrl(); return _baseService.get(baseUrl, 'positions'); } Future> getAllStates() async { final baseUrl = await _serverConfigService.getActiveApiUrl(); return _baseService.get(baseUrl, 'states'); } Future> sendTelegramAlert({ required String chatId, required String message, }) async { final baseUrl = await _serverConfigService.getActiveApiUrl(); return _baseService.post(baseUrl, 'marine/telegram-alert', { 'chat_id': chatId, 'message': message, }); } Future downloadProfilePicture(String imageUrl, String localPath) async { try { final response = await http.get(Uri.parse(imageUrl)); if (response.statusCode == 200) { final File file = File(localPath); await file.parent.create(recursive: true); await file.writeAsBytes(response.bodyBytes); return file; } } catch (e) { debugPrint('Error downloading profile picture: $e'); } return null; } Future> uploadProfilePicture(File imageFile) async { final baseUrl = await _serverConfigService.getActiveApiUrl(); return _baseService.postMultipart( baseUrl: baseUrl, endpoint: 'profile/upload-picture', fields: {}, files: {'profile_picture': imageFile} ); } // END CHANGE Future> refreshProfile() async { debugPrint('ApiService: Refreshing profile data from server...'); final result = await getProfile(); if (result['success'] == true && result['data'] != null) { await dbHelper.saveProfile(result['data']); debugPrint('ApiService: Profile data refreshed and saved to local DB.'); } return result; } // --- REWRITTEN FOR DELTA SYNC --- /// Helper method to make a delta-sync API call. Future> _fetchDelta(String endpoint, String? lastSyncTimestamp) async { // START CHANGE: Get baseUrl and pass it to the get method final baseUrl = await _serverConfigService.getActiveApiUrl(); String url = endpoint; if (lastSyncTimestamp != null) { // Append the 'since' parameter to the URL for delta requests url += '?since=$lastSyncTimestamp'; } return _baseService.get(baseUrl, url); // END CHANGE } /// Orchestrates a full DELTA sync from the server to the local database. Future> syncAllData({String? lastSyncTimestamp}) async { debugPrint('ApiService: Starting DELTA data sync. Since: $lastSyncTimestamp'); try { // Defines all data types to sync, their endpoints, and their DB handlers. final syncTasks = { 'profile': {'endpoint': 'profile', 'handler': (d, id) async { if (d.isNotEmpty) await dbHelper.saveProfile(d.first); }}, 'allUsers': {'endpoint': 'users', 'handler': (d, id) async { await dbHelper.upsertUsers(d); await dbHelper.deleteUsers(id); }}, 'tarballStations': {'endpoint': 'marine/tarball/stations', 'handler': (d, id) async { await dbHelper.upsertTarballStations(d); await dbHelper.deleteTarballStations(id); }}, 'manualStations': {'endpoint': 'marine/manual/stations', 'handler': (d, id) async { await dbHelper.upsertManualStations(d); await dbHelper.deleteManualStations(id); }}, 'tarballClassifications': {'endpoint': 'marine/tarball/classifications', 'handler': (d, id) async { await dbHelper.upsertTarballClassifications(d); await dbHelper.deleteTarballClassifications(id); }}, 'riverManualStations': {'endpoint': 'river/manual-stations', 'handler': (d, id) async { await dbHelper.upsertRiverManualStations(d); await dbHelper.deleteRiverManualStations(id); }}, 'riverTriennialStations': {'endpoint': 'river/triennial-stations', 'handler': (d, id) async { await dbHelper.upsertRiverTriennialStations(d); await dbHelper.deleteRiverTriennialStations(id); }}, 'departments': {'endpoint': 'departments', 'handler': (d, id) async { await dbHelper.upsertDepartments(d); await dbHelper.deleteDepartments(id); }}, 'companies': {'endpoint': 'companies', 'handler': (d, id) async { await dbHelper.upsertCompanies(d); await dbHelper.deleteCompanies(id); }}, 'positions': {'endpoint': 'positions', 'handler': (d, id) async { await dbHelper.upsertPositions(d); await dbHelper.deletePositions(id); }}, 'airManualStations': {'endpoint': 'air/manual-stations', 'handler': (d, id) async { await dbHelper.upsertAirManualStations(d); await dbHelper.deleteAirManualStations(id); }}, 'airClients': {'endpoint': 'air/clients', 'handler': (d, id) async { await dbHelper.upsertAirClients(d); await dbHelper.deleteAirClients(id); }}, 'states': {'endpoint': 'states', 'handler': (d, id) async { await dbHelper.upsertStates(d); await dbHelper.deleteStates(id); }}, 'appSettings': {'endpoint': 'settings', 'handler': (d, id) async { await dbHelper.upsertAppSettings(d); await dbHelper.deleteAppSettings(id); }}, 'parameterLimits': {'endpoint': 'parameter-limits', 'handler': (d, id) async { await dbHelper.upsertParameterLimits(d); await dbHelper.deleteParameterLimits(id); }}, 'apiConfigs': {'endpoint': 'api-configs', 'handler': (d, id) async { await dbHelper.upsertApiConfigs(d); await dbHelper.deleteApiConfigs(id); }}, 'ftpConfigs': {'endpoint': 'ftp-configs', 'handler': (d, id) async { await dbHelper.upsertFtpConfigs(d); await dbHelper.deleteFtpConfigs(id); }}, }; // Fetch all deltas in parallel final fetchFutures = syncTasks.map((key, value) => MapEntry(key, _fetchDelta(value['endpoint'] as String, lastSyncTimestamp))); final results = await Future.wait(fetchFutures.values); final resultData = Map.fromIterables(fetchFutures.keys, results); // Process and save all changes for (var entry in resultData.entries) { final key = entry.key; final result = entry.value; if (result['success'] == true && result['data'] != null) { // The profile endpoint has a different structure, handle it separately. if (key == 'profile') { await (syncTasks[key]!['handler'] as Function)([result['data']], []); } else { final updated = List>.from(result['data']['updated'] ?? []); final deleted = List.from(result['data']['deleted'] ?? []); await (syncTasks[key]!['handler'] as Function)(updated, deleted); } } else { debugPrint('ApiService: Failed to sync $key. Message: ${result['message']}'); } } debugPrint('ApiService: Delta sync complete.'); return {'success': true, 'message': 'Delta sync successful.'}; } catch (e) { debugPrint('ApiService: Delta data sync failed: $e'); return {'success': false, 'message': 'Data sync failed: $e'}; } } } // ======================================================================= // Part 2: Feature-Specific API Services (Refactored to include Telegram) // ======================================================================= class AirApiService { final BaseApiService _baseService; final TelegramService? _telegramService; // START CHANGE: Add ServerConfigService dependency final ServerConfigService _serverConfigService; AirApiService(this._baseService, this._telegramService, this._serverConfigService); // END CHANGE // START CHANGE: Update all calls to _baseService to pass the required baseUrl Future> getManualStations() async { final baseUrl = await _serverConfigService.getActiveApiUrl(); return _baseService.get(baseUrl, 'air/manual-stations'); } Future> getClients() async { final baseUrl = await _serverConfigService.getActiveApiUrl(); return _baseService.get(baseUrl, 'air/clients'); } Future> submitInstallation(AirInstallationData data) async { final baseUrl = await _serverConfigService.getActiveApiUrl(); return _baseService.post(baseUrl, 'air/manual/installation', data.toJsonForApi()); } Future> submitCollection(AirCollectionData data) async { final baseUrl = await _serverConfigService.getActiveApiUrl(); return _baseService.post(baseUrl, 'air/manual/collection', data.toJson()); } Future> uploadInstallationImages({ required String airManId, required Map files, }) async { final baseUrl = await _serverConfigService.getActiveApiUrl(); return _baseService.postMultipart( baseUrl: baseUrl, endpoint: 'air/manual/installation-images', fields: {'air_man_id': airManId}, files: files, ); } Future> uploadCollectionImages({ required String airManId, required Map files, }) async { final baseUrl = await _serverConfigService.getActiveApiUrl(); return _baseService.postMultipart( baseUrl: baseUrl, endpoint: 'air/manual/collection-images', fields: {'air_man_id': airManId}, files: files, ); } // END CHANGE } class MarineApiService { final BaseApiService _baseService; final TelegramService _telegramService; // START CHANGE: Add ServerConfigService dependency final ServerConfigService _serverConfigService; MarineApiService(this._baseService, this._telegramService, this._serverConfigService); // END CHANGE // START CHANGE: Update all calls to _baseService to pass the required baseUrl Future> getTarballStations() async { final baseUrl = await _serverConfigService.getActiveApiUrl(); return _baseService.get(baseUrl, 'marine/tarball/stations'); } Future> getManualStations() async { final baseUrl = await _serverConfigService.getActiveApiUrl(); return _baseService.get(baseUrl, 'marine/manual/stations'); } Future> getTarballClassifications() async { final baseUrl = await _serverConfigService.getActiveApiUrl(); return _baseService.get(baseUrl, 'marine/tarball/classifications'); } Future> submitInSituSample({ required Map formData, required Map imageFiles, required InSituSamplingData inSituData, required List>? appSettings, }) async { debugPrint("Step 1: Submitting in-situ form data to the server..."); final baseUrl = await _serverConfigService.getActiveApiUrl(); final dataResult = await _baseService.post(baseUrl, 'marine/manual/sample', formData); if (dataResult['success'] != true) { debugPrint("API submission failed for In-Situ. Message: ${dataResult['message']}"); return { 'status': 'L1', 'success': false, 'message': 'Failed to submit in-situ data: ${dataResult['message']}', 'reportId': null, }; } debugPrint("Step 1 successful. In-situ data submitted. Report ID: ${dataResult['data']?['man_id']}"); final recordId = dataResult['data']?['man_id']; if (recordId == null) { debugPrint("API submitted, but no record ID returned."); return { 'status': 'L2', 'success': false, 'message': 'In-situ data submitted, but failed to get a record ID for images.', 'reportId': null, }; } final filesToUpload = {}; imageFiles.forEach((key, value) { if (value != null) filesToUpload[key] = value; }); if (filesToUpload.isEmpty) { debugPrint("No images to upload. Finalizing submission."); _handleInSituSuccessAlert(inSituData, appSettings, isDataOnly: true); // Uses the inSituData object return { 'status': 'L3', 'success': true, 'message': 'In-situ data submitted successfully. No images were attached.', 'reportId': recordId.toString(), }; } debugPrint("Step 2: Uploading ${filesToUpload.length} in-situ images for record ID: $recordId"); final imageResult = await _baseService.postMultipart( baseUrl: baseUrl, endpoint: 'marine/manual/images', fields: {'man_id': recordId.toString()}, files: filesToUpload, ); if (imageResult['success'] != true) { debugPrint("Image upload failed for In-Situ. Message: ${imageResult['message']}"); return { 'status': 'L2', 'success': false, 'message': 'In-situ data submitted, but image upload failed: ${imageResult['message']}', 'reportId': recordId.toString(), }; } debugPrint("Step 2 successful. All images uploaded."); _handleInSituSuccessAlert(inSituData, appSettings, isDataOnly: false); return { 'status': 'L3', 'success': true, 'message': 'Data and images submitted to server successfully.', 'reportId': recordId.toString(), }; } Future _handleInSituSuccessAlert(InSituSamplingData data, List>? appSettings, {required bool isDataOnly}) async { try { final message = data.generateTelegramAlertMessage(isDataOnly: isDataOnly); final bool wasSent = await _telegramService.sendAlertImmediately('marine_in_situ', message, appSettings); if (!wasSent) { await _telegramService.queueMessage('marine_in_situ', message, appSettings); } } catch (e) { debugPrint("Failed to handle In-Situ Telegram alert: $e"); } } Future> submitTarballSample({ required Map formData, required Map imageFiles, required List>? appSettings, }) async { final baseUrl = await _serverConfigService.getActiveApiUrl(); final dataResult = await _baseService.post(baseUrl, 'marine/tarball/sample', formData); if (dataResult['success'] != true) return {'status': 'L1', 'success': false, 'message': 'Failed to submit data: ${dataResult['message']}'}; final recordId = dataResult['data']?['autoid']; if (recordId == null) return {'status': 'L2', 'success': false, 'message': 'Data submitted, but failed to get a record ID.'}; final filesToUpload = {}; imageFiles.forEach((key, value) { if (value != null) filesToUpload[key] = value; }); if (filesToUpload.isEmpty) { _handleTarballSuccessAlert(formData, appSettings, isDataOnly: true); return {'status': 'L3', 'success': true, 'message': 'Data submitted successfully.', 'reportId': recordId}; } final imageResult = await _baseService.postMultipart(baseUrl: baseUrl, endpoint: 'marine/tarball/images', fields: {'autoid': recordId.toString()}, files: filesToUpload); if (imageResult['success'] != true) { _handleTarballSuccessAlert(formData, appSettings, isDataOnly: true); return {'status': 'L2', 'success': false, 'message': 'Data submitted, but image upload failed: ${imageResult['message']}', 'reportId': recordId}; } _handleTarballSuccessAlert(formData, appSettings, isDataOnly: false); return {'status': 'L3', 'success': true, 'message': 'Data and images submitted successfully.', 'reportId': recordId}; } // END CHANGE Future _handleTarballSuccessAlert(Map formData, List>? appSettings, {required bool isDataOnly}) async { debugPrint("Triggering Telegram alert logic..."); try { final message = _generateTarballAlertMessage(formData, isDataOnly: isDataOnly); final bool wasSent = await _telegramService.sendAlertImmediately('marine_tarball', message, appSettings); if (!wasSent) { await _telegramService.queueMessage('marine_tarball', message, appSettings); } } catch (e) { debugPrint("Failed to handle Tarball Telegram alert: $e"); } } String _generateTarballAlertMessage(Map formData, {required bool isDataOnly}) { final submissionType = isDataOnly ? "(Data Only)" : "(Data & Images)"; final stationName = formData['tbl_station_name'] ?? 'N/A'; final stationCode = formData['tbl_station_code'] ?? 'N/A'; final classification = formData['classification_name'] ?? formData['classification_id'] ?? 'N/A'; final buffer = StringBuffer() ..writeln('✅ *Tarball Sample $submissionType Submitted:*') ..writeln() ..writeln('*Station Name & Code:* $stationName ($stationCode)') ..writeln('*Date of Submission:* ${formData['sampling_date']}') ..writeln('*Submitted by User:* ${formData['first_sampler_name'] ?? 'N/A'}') ..writeln('*Classification:* $classification') ..writeln('*Status of Submission:* Successful'); if (formData['distance_difference'] != null && double.tryParse(formData['distance_difference']!) != null && double.parse(formData['distance_difference']!) > 0) { buffer ..writeln() ..writeln('🔔 *Alert:*') ..writeln('*Distance from station:* ${(double.parse(formData['distance_difference']!) * 1000).toStringAsFixed(0)} meters'); if (formData['distance_difference_remarks'] != null && formData['distance_difference_remarks']!.isNotEmpty) { buffer.writeln('*Remarks for distance:* ${formData['distance_difference_remarks']}'); } } return buffer.toString(); } } class RiverApiService { final BaseApiService _baseService; final TelegramService _telegramService; // START CHANGE: Add ServerConfigService dependency final ServerConfigService _serverConfigService; RiverApiService(this._baseService, this._telegramService, this._serverConfigService); // END CHANGE // START CHANGE: Update all calls to _baseService to pass the required baseUrl Future> getManualStations() async { final baseUrl = await _serverConfigService.getActiveApiUrl(); return _baseService.get(baseUrl, 'river/manual-stations'); } Future> getTriennialStations() async { final baseUrl = await _serverConfigService.getActiveApiUrl(); return _baseService.get(baseUrl, 'river/triennial-stations'); } Future> submitInSituSample({ required Map formData, required Map imageFiles, required List>? appSettings, }) async { final baseUrl = await _serverConfigService.getActiveApiUrl(); final dataResult = await _baseService.post(baseUrl, 'river/manual/sample', formData); if (dataResult['success'] != true) { return { 'status': 'L1', 'success': false, 'message': 'Failed to submit river in-situ data: ${dataResult['message']}', 'reportId': null }; } final recordId = dataResult['data']?['r_man_id']; if (recordId == null) { return { 'status': 'L2', 'success': false, 'message': 'Data submitted, but failed to get a record ID for images.', 'reportId': null }; } final filesToUpload = {}; imageFiles.forEach((key, value) { if (value != null) filesToUpload[key] = value; }); if (filesToUpload.isEmpty) { _handleInSituSuccessAlert(formData, appSettings, isDataOnly: true); return { 'status': 'L3', 'success': true, 'message': 'Data submitted successfully. No images were attached.', 'reportId': recordId.toString() }; } final imageResult = await _baseService.postMultipart( baseUrl: baseUrl, endpoint: 'river/manual/images', // Separate endpoint for images fields: {'r_man_id': recordId.toString()}, // Link images to the submitted record ID files: filesToUpload, ); if (imageResult['success'] != true) { return { 'status': 'L2', 'success': false, 'message': 'Data submitted, but image upload failed: ${imageResult['message']}', 'reportId': recordId.toString() }; } _handleInSituSuccessAlert(formData, appSettings, isDataOnly: false); return { 'status': 'L3', 'success': true, 'message': 'Data and images submitted successfully.', 'reportId': recordId.toString() }; } // END CHANGE Future _handleInSituSuccessAlert(Map formData, List>? appSettings, {required bool isDataOnly}) async { try { final submissionType = isDataOnly ? "(Data Only)" : "(Data & Images)"; final stationName = formData['r_man_station_name'] ?? 'N/A'; final stationCode = formData['r_man_station_code'] ?? 'N/A'; final submissionDate = formData['r_man_date'] ?? DateFormat('yyyy-MM-dd').format(DateTime.now()); final submitter = formData['first_sampler_name'] ?? 'N/A'; final sondeID = formData['r_man_sondeID'] ?? 'N/A'; final distanceKm = double.tryParse(formData['r_man_distance_difference'] ?? '0') ?? 0; final distanceMeters = (distanceKm * 1000).toStringAsFixed(0); final distanceRemarks = formData['r_man_distance_difference_remarks'] ?? 'N/A'; final buffer = StringBuffer() ..writeln('✅ *River In-Situ Sample ${submissionType} Submitted:*') ..writeln() ..writeln('*Station Name & Code:* $stationName ($stationCode)') ..writeln('*Date of Submitted:* $submissionDate') ..writeln('*Submitted by User:* $submitter') ..writeln('*Sonde ID:* $sondeID') ..writeln('*Status of Submission:* Successful'); if (distanceKm > 0 || (distanceRemarks.isNotEmpty && distanceRemarks != 'N/A')) { buffer ..writeln() ..writeln('🔔 *Alert:*') ..writeln('*Distance from station:* $distanceMeters meters'); if (distanceRemarks.isNotEmpty && distanceRemarks != 'N/A') { buffer.writeln('*Remarks for distance:* $distanceRemarks'); } } final String message = buffer.toString(); final bool wasSent = await _telegramService.sendAlertImmediately('river_in_situ', message, appSettings); if (!wasSent) { await _telegramService.queueMessage('river_in_situ', message, appSettings); } } catch (e) { debugPrint("Failed to handle River Telegram alert: $e"); } } } // ======================================================================= // Part 3: Local Database Helper (Refactored for Delta Sync) // ======================================================================= class DatabaseHelper { static Database? _database; static const String _dbName = 'app_data.db'; static const int _dbVersion = 19; static const String _profileTable = 'user_profile'; static const String _usersTable = 'all_users'; static const String _tarballStationsTable = 'marine_tarball_stations'; static const String _manualStationsTable = 'marine_manual_stations'; static const String _riverManualStationsTable = 'river_manual_stations'; static const String _riverTriennialStationsTable = 'river_triennial_stations'; static const String _tarballClassificationsTable = 'marine_tarball_classifications'; static const String _departmentsTable = 'departments'; static const String _companiesTable = 'companies'; static const String _positionsTable = 'positions'; static const String _alertQueueTable = 'alert_queue'; static const String _airManualStationsTable = 'air_manual_stations'; static const String _airClientsTable = 'air_clients'; static const String _statesTable = 'states'; static const String _appSettingsTable = 'app_settings'; static const String _parameterLimitsTable = 'manual_parameter_limits'; static const String _apiConfigsTable = 'api_configurations'; static const String _ftpConfigsTable = 'ftp_configurations'; static const String _retryQueueTable = 'retry_queue'; static const String _submissionLogTable = 'submission_log'; static const String _modulePreferencesTable = 'module_preferences'; static const String _moduleApiLinksTable = 'module_api_links'; static const String _moduleFtpLinksTable = 'module_ftp_links'; Future get database async { if (_database != null) return _database!; _database = await _initDB(); return _database!; } Future _initDB() async { String dbPath = p.join(await getDatabasesPath(), _dbName); return await openDatabase(dbPath, version: _dbVersion, onCreate: _onCreate, onUpgrade: _onUpgrade); } Future _onCreate(Database db, int version) async { await db.execute('CREATE TABLE $_profileTable(user_id INTEGER PRIMARY KEY, profile_json TEXT)'); await db.execute('CREATE TABLE $_usersTable(user_id INTEGER PRIMARY KEY, user_json TEXT)'); await db.execute('CREATE TABLE $_tarballStationsTable(station_id INTEGER PRIMARY KEY, station_json TEXT)'); await db.execute('CREATE TABLE $_manualStationsTable(station_id INTEGER PRIMARY KEY, station_json TEXT)'); await db.execute('CREATE TABLE $_riverManualStationsTable(station_id INTEGER PRIMARY KEY, station_json TEXT)'); await db.execute('CREATE TABLE $_riverTriennialStationsTable(station_id INTEGER PRIMARY KEY, station_json TEXT)'); await db.execute('CREATE TABLE $_tarballClassificationsTable(classification_id INTEGER PRIMARY KEY, classification_json TEXT)'); await db.execute('CREATE TABLE $_departmentsTable(department_id INTEGER PRIMARY KEY, department_json TEXT)'); await db.execute('CREATE TABLE $_companiesTable(company_id INTEGER PRIMARY KEY, company_json TEXT)'); await db.execute('CREATE TABLE $_positionsTable(position_id INTEGER PRIMARY KEY, position_json TEXT)'); await db.execute('''CREATE TABLE $_alertQueueTable (id INTEGER PRIMARY KEY AUTOINCREMENT, chat_id TEXT NOT NULL, message TEXT NOT NULL, created_at TEXT NOT NULL)'''); await db.execute('CREATE TABLE $_airManualStationsTable(station_id INTEGER PRIMARY KEY, station_json TEXT)'); await db.execute('CREATE TABLE $_airClientsTable(client_id INTEGER PRIMARY KEY, client_json TEXT)'); await db.execute('CREATE TABLE $_statesTable(state_id INTEGER PRIMARY KEY, state_json TEXT)'); await db.execute('CREATE TABLE $_appSettingsTable(setting_id INTEGER PRIMARY KEY, setting_json TEXT)'); await db.execute('CREATE TABLE $_parameterLimitsTable(param_autoid INTEGER PRIMARY KEY, limit_json TEXT)'); await db.execute('CREATE TABLE $_apiConfigsTable(api_config_id INTEGER PRIMARY KEY, config_json TEXT)'); await db.execute('CREATE TABLE $_ftpConfigsTable(ftp_config_id INTEGER PRIMARY KEY, config_json TEXT)'); await db.execute(''' CREATE TABLE $_retryQueueTable( id INTEGER PRIMARY KEY AUTOINCREMENT, type TEXT NOT NULL, endpoint_or_path TEXT NOT NULL, payload TEXT, timestamp TEXT NOT NULL, status TEXT NOT NULL ) '''); // FIX: Updated CREATE TABLE statement for _submissionLogTable to include api_status and ftp_status await db.execute(''' CREATE TABLE $_submissionLogTable ( submission_id TEXT PRIMARY KEY, module TEXT NOT NULL, type TEXT NOT NULL, status TEXT NOT NULL, message TEXT, report_id TEXT, created_at TEXT NOT NULL, form_data TEXT, image_data TEXT, server_name TEXT, api_status TEXT, ftp_status TEXT ) '''); // START CHANGE: Added CREATE TABLE statements for the new tables. await db.execute(''' CREATE TABLE $_modulePreferencesTable ( module_name TEXT PRIMARY KEY, is_api_enabled INTEGER NOT NULL DEFAULT 1, is_ftp_enabled INTEGER NOT NULL DEFAULT 1 ) '''); await db.execute(''' CREATE TABLE $_moduleApiLinksTable ( id INTEGER PRIMARY KEY AUTOINCREMENT, module_name TEXT NOT NULL, api_config_id INTEGER NOT NULL, is_enabled INTEGER NOT NULL DEFAULT 1 ) '''); await db.execute(''' CREATE TABLE $_moduleFtpLinksTable ( id INTEGER PRIMARY KEY AUTOINCREMENT, module_name TEXT NOT NULL, ftp_config_id INTEGER NOT NULL, is_enabled INTEGER NOT NULL DEFAULT 1 ) '''); // END CHANGE } Future _onUpgrade(Database db, int oldVersion, int newVersion) async { if (oldVersion < 11) { await db.execute('CREATE TABLE IF NOT EXISTS $_airManualStationsTable(station_id INTEGER PRIMARY KEY, station_json TEXT)'); await db.execute('CREATE TABLE IF NOT EXISTS $_airClientsTable(client_id INTEGER PRIMARY KEY, client_json TEXT)'); } if (oldVersion < 12) { await db.execute('CREATE TABLE IF NOT EXISTS $_statesTable(state_id INTEGER PRIMARY KEY, state_json TEXT)'); } if (oldVersion < 13) { await db.execute('CREATE TABLE IF NOT EXISTS $_appSettingsTable(setting_id INTEGER PRIMARY KEY, setting_json TEXT)'); await db.execute('CREATE TABLE IF NOT EXISTS $_parameterLimitsTable(param_autoid INTEGER PRIMARY KEY, limit_json TEXT)'); } if (oldVersion < 16) { await db.execute('CREATE TABLE IF NOT EXISTS $_apiConfigsTable(api_config_id INTEGER PRIMARY KEY, config_json TEXT)'); await db.execute('CREATE TABLE IF NOT EXISTS $_ftpConfigsTable(ftp_config_id INTEGER PRIMARY KEY, config_json TEXT)'); } if (oldVersion < 17) { await db.execute(''' CREATE TABLE IF NOT EXISTS $_retryQueueTable( id INTEGER PRIMARY KEY AUTOINCREMENT, type TEXT NOT NULL, endpoint_or_path TEXT NOT NULL, payload TEXT, timestamp TEXT NOT NULL, status TEXT NOT NULL ) '''); } if (oldVersion < 18) { // FIX: Updated UPGRADE TABLE statement for _submissionLogTable to include api_status and ftp_status await db.execute(''' CREATE TABLE IF NOT EXISTS $_submissionLogTable ( submission_id TEXT PRIMARY KEY, module TEXT NOT NULL, type TEXT NOT NULL, status TEXT NOT NULL, message TEXT, report_id TEXT, created_at TEXT NOT NULL, form_data TEXT, image_data TEXT, server_name TEXT ) '''); } // Add columns if upgrading from < 18 or if columns were manually dropped (for testing) // NOTE: In a real migration, you'd check if the columns exist first. if (oldVersion < 19) { try { await db.execute("ALTER TABLE $_submissionLogTable ADD COLUMN api_status TEXT"); await db.execute("ALTER TABLE $_submissionLogTable ADD COLUMN ftp_status TEXT"); } catch (_) { // Ignore if columns already exist during a complex migration path } // START CHANGE: Add upgrade path for the new preference tables. await db.execute(''' CREATE TABLE IF NOT EXISTS $_modulePreferencesTable ( module_name TEXT PRIMARY KEY, is_api_enabled INTEGER NOT NULL DEFAULT 1, is_ftp_enabled INTEGER NOT NULL DEFAULT 1 ) '''); await db.execute(''' CREATE TABLE IF NOT EXISTS $_moduleApiLinksTable ( id INTEGER PRIMARY KEY AUTOINCREMENT, module_name TEXT NOT NULL, api_config_id INTEGER NOT NULL, is_enabled INTEGER NOT NULL DEFAULT 1 ) '''); await db.execute(''' CREATE TABLE IF NOT EXISTS $_moduleFtpLinksTable ( id INTEGER PRIMARY KEY AUTOINCREMENT, module_name TEXT NOT NULL, ftp_config_id INTEGER NOT NULL, is_enabled INTEGER NOT NULL DEFAULT 1 ) '''); // END CHANGE } } /// Performs an "upsert": inserts new records or replaces existing ones. Future _upsertData(String table, String idKeyName, List> data, String jsonKeyName) async { if (data.isEmpty) return; final db = await database; final batch = db.batch(); for (var item in data) { batch.insert( table, {idKeyName: item[idKeyName], '${jsonKeyName}_json': jsonEncode(item)}, conflictAlgorithm: ConflictAlgorithm.replace, ); } await batch.commit(noResult: true); debugPrint("Upserted ${data.length} items into $table"); } /// Deletes a list of records from a table by their primary keys. Future _deleteData(String table, String idKeyName, List ids) async { if (ids.isEmpty) return; final db = await database; final placeholders = List.filled(ids.length, '?').join(', '); await db.delete( table, where: '$idKeyName IN ($placeholders)', whereArgs: ids, ); debugPrint("Deleted ${ids.length} items from $table"); } Future>?> _loadData(String table, String jsonKey) async { final db = await database; final List> maps = await db.query(table); if (maps.isNotEmpty) { return maps.map((map) => jsonDecode(map['${jsonKey}_json']) as Map).toList(); } return null; } Future saveProfile(Map profile) async { final db = await database; await db.insert(_profileTable, {'user_id': profile['user_id'], 'profile_json': jsonEncode(profile)}, conflictAlgorithm: ConflictAlgorithm.replace); } Future?> loadProfile() async { final db = await database; final List> maps = await db.query(_profileTable); if(maps.isNotEmpty) return jsonDecode(maps.first['profile_json']); return null; } // --- Upsert/Delete/Load methods for all data types --- Future upsertUsers(List> data) => _upsertData(_usersTable, 'user_id', data, 'user'); Future deleteUsers(List ids) => _deleteData(_usersTable, 'user_id', ids); Future>?> loadUsers() => _loadData(_usersTable, 'user'); Future upsertTarballStations(List> data) => _upsertData(_tarballStationsTable, 'station_id', data, 'station'); Future deleteTarballStations(List ids) => _deleteData(_tarballStationsTable, 'station_id', ids); Future>?> loadTarballStations() => _loadData(_tarballStationsTable, 'station'); Future upsertManualStations(List> data) => _upsertData(_manualStationsTable, 'station_id', data, 'station'); Future deleteManualStations(List ids) => _deleteData(_manualStationsTable, 'station_id', ids); Future>?> loadManualStations() => _loadData(_manualStationsTable, 'station'); Future upsertRiverManualStations(List> data) => _upsertData(_riverManualStationsTable, 'station_id', data, 'station'); Future deleteRiverManualStations(List ids) => _deleteData(_riverManualStationsTable, 'station_id', ids); Future>?> loadRiverManualStations() => _loadData(_riverManualStationsTable, 'station'); Future upsertRiverTriennialStations(List> data) => _upsertData(_riverTriennialStationsTable, 'station_id', data, 'station'); Future deleteRiverTriennialStations(List ids) => _deleteData(_riverTriennialStationsTable, 'station_id', ids); Future>?> loadRiverTriennialStations() => _loadData(_riverTriennialStationsTable, 'station'); Future upsertTarballClassifications(List> data) => _upsertData(_tarballClassificationsTable, 'classification_id', data, 'classification'); Future deleteTarballClassifications(List ids) => _deleteData(_tarballClassificationsTable, 'classification_id', ids); Future>?> loadTarballClassifications() => _loadData(_tarballClassificationsTable, 'classification'); Future upsertDepartments(List> data) => _upsertData(_departmentsTable, 'department_id', data, 'department'); Future deleteDepartments(List ids) => _deleteData(_departmentsTable, 'department_id', ids); Future>?> loadDepartments() => _loadData(_departmentsTable, 'department'); Future upsertCompanies(List> data) => _upsertData(_companiesTable, 'company_id', data, 'company'); Future deleteCompanies(List ids) => _deleteData(_companiesTable, 'company_id', ids); Future>?> loadCompanies() => _loadData(_companiesTable, 'company'); Future upsertPositions(List> data) => _upsertData(_positionsTable, 'position_id', data, 'position'); Future deletePositions(List ids) => _deleteData(_positionsTable, 'position_id', ids); Future>?> loadPositions() => _loadData(_positionsTable, 'position'); Future upsertAirManualStations(List> data) => _upsertData(_airManualStationsTable, 'station_id', data, 'station'); Future deleteAirManualStations(List ids) => _deleteData(_airManualStationsTable, 'station_id', ids); Future>?> loadAirManualStations() => _loadData(_airManualStationsTable, 'station'); Future upsertAirClients(List> data) => _upsertData(_airClientsTable, 'client_id', data, 'client'); Future deleteAirClients(List ids) => _deleteData(_airClientsTable, 'client_id', ids); Future>?> loadAirClients() => _loadData(_airClientsTable, 'client'); Future upsertStates(List> data) => _upsertData(_statesTable, 'state_id', data, 'state'); Future deleteStates(List ids) => _deleteData(_statesTable, 'state_id', ids); Future>?> loadStates() => _loadData(_statesTable, 'state'); Future upsertAppSettings(List> data) => _upsertData(_appSettingsTable, 'setting_id', data, 'setting'); Future deleteAppSettings(List ids) => _deleteData(_appSettingsTable, 'setting_id', ids); Future>?> loadAppSettings() => _loadData(_appSettingsTable, 'setting'); Future upsertParameterLimits(List> data) => _upsertData(_parameterLimitsTable, 'param_autoid', data, 'limit'); Future deleteParameterLimits(List ids) => _deleteData(_parameterLimitsTable, 'param_autoid', ids); Future>?> loadParameterLimits() => _loadData(_parameterLimitsTable, 'limit'); // --- ADDED: Methods for independent API and FTP configurations --- Future upsertApiConfigs(List> data) => _upsertData(_apiConfigsTable, 'api_config_id', data, 'config'); Future deleteApiConfigs(List ids) => _deleteData(_apiConfigsTable, 'api_config_id', ids); Future>?> loadApiConfigs() => _loadData(_apiConfigsTable, 'config'); Future upsertFtpConfigs(List> data) => _upsertData(_ftpConfigsTable, 'ftp_config_id', data, 'config'); Future deleteFtpConfigs(List ids) => _deleteData(_ftpConfigsTable, 'ftp_config_id', ids); Future>?> loadFtpConfigs() => _loadData(_ftpConfigsTable, 'config'); // --- ADDED: Methods for the new retry queue --- Future queueFailedRequest(Map data) async { final db = await database; return await db.insert(_retryQueueTable, data, conflictAlgorithm: ConflictAlgorithm.replace); } Future>> getPendingRequests() async { final db = await database; return await db.query(_retryQueueTable, where: 'status = ?', whereArgs: ['pending']); } Future?> getRequestById(int id) async { final db = await database; final results = await db.query(_retryQueueTable, where: 'id = ?', whereArgs: [id]); return results.isNotEmpty ? results.first : null; } Future deleteRequestFromQueue(int id) async { final db = await database; await db.delete(_retryQueueTable, where: 'id = ?', whereArgs: [id]); } // --- ADDED: Methods for the centralized submission log --- /// Saves a new submission log entry to the central database table. // FIX: Updated signature to accept api_status and ftp_status Future saveSubmissionLog(Map data) async { final db = await database; await db.insert( _submissionLogTable, data, conflictAlgorithm: ConflictAlgorithm.replace, ); } /// Retrieves all submission log entries, optionally filtered by module. Future>?> loadSubmissionLogs({String? module}) async { final db = await database; List> maps; if (module != null && module.isNotEmpty) { maps = await db.query( _submissionLogTable, where: 'module = ?', whereArgs: [module], orderBy: 'created_at DESC', ); } else { maps = await db.query( _submissionLogTable, orderBy: 'created_at DESC', ); } if (maps.isNotEmpty) return maps; return null; } // START CHANGE: Added helper methods for the new preference tables. /// Saves or updates a module's master submission preferences. Future saveModulePreference({ required String moduleName, required bool isApiEnabled, required bool isFtpEnabled, }) async { final db = await database; await db.insert( _modulePreferencesTable, { 'module_name': moduleName, 'is_api_enabled': isApiEnabled ? 1 : 0, 'is_ftp_enabled': isFtpEnabled ? 1 : 0, }, conflictAlgorithm: ConflictAlgorithm.replace, ); } /// Retrieves a module's master submission preferences. Future?> getModulePreference(String moduleName) async { final db = await database; final result = await db.query( _modulePreferencesTable, where: 'module_name = ?', whereArgs: [moduleName], ); if (result.isNotEmpty) { final row = result.first; return { 'module_name': row['module_name'], 'is_api_enabled': (row['is_api_enabled'] as int) == 1, 'is_ftp_enabled': (row['is_ftp_enabled'] as int) == 1, }; } return null; // Return null if no specific preference is set } /// Saves the complete set of API links for a specific module, replacing any old ones. Future saveApiLinksForModule(String moduleName, List> links) async { final db = await database; await db.transaction((txn) async { // First, delete all existing links for this module await txn.delete(_moduleApiLinksTable, where: 'module_name = ?', whereArgs: [moduleName]); // Then, insert all the new links for (final link in links) { await txn.insert(_moduleApiLinksTable, { 'module_name': moduleName, 'api_config_id': link['api_config_id'], 'is_enabled': (link['is_enabled'] as bool? ?? true) ? 1 : 0, }); } }); } /// Saves the complete set of FTP links for a specific module, replacing any old ones. Future saveFtpLinksForModule(String moduleName, List> links) async { final db = await database; await db.transaction((txn) async { await txn.delete(_moduleFtpLinksTable, where: 'module_name = ?', whereArgs: [moduleName]); for (final link in links) { await txn.insert(_moduleFtpLinksTable, { 'module_name': moduleName, 'ftp_config_id': link['ftp_config_id'], 'is_enabled': (link['is_enabled'] as bool? ?? true) ? 1 : 0, }); } }); } /// Retrieves all API links for a specific module, regardless of enabled status. Future>> getAllApiLinksForModule(String moduleName) async { final db = await database; final result = await db.query(_moduleApiLinksTable, where: 'module_name = ?', whereArgs: [moduleName]); return result.map((row) => { 'api_config_id': row['api_config_id'], 'is_enabled': (row['is_enabled'] as int) == 1, }).toList(); } /// Retrieves all FTP links for a specific module, regardless of enabled status. Future>> getAllFtpLinksForModule(String moduleName) async { final db = await database; final result = await db.query(_moduleFtpLinksTable, where: 'module_name = ?', whereArgs: [moduleName]); return result.map((row) => { 'ftp_config_id': row['ftp_config_id'], 'is_enabled': (row['is_enabled'] as int) == 1, }).toList(); } // END CHANGE }