// lib/services/saved_report_service.dart import 'dart:convert'; import 'dart:io'; import 'package:path_provider/path_provider.dart'; import 'package:cashumit/models/saved_report.dart'; class SavedReportService { static const String _folderName = 'saved_reports'; /// Mendapatkan direktori penyimpanan berkas draft laporan static Future _getReportsDirectory() async { final appDir = await getApplicationDocumentsDirectory(); final reportsDir = Directory('${appDir.path}/$_folderName'); if (!await reportsDir.exists()) { await reportsDir.create(recursive: true); } return reportsDir; } /// Menyimpan atau memperbarui draft laporan ke dalam file JSON lokal static Future saveReport(SavedReport report) async { final dir = await _getReportsDirectory(); report.updatedAt = DateTime.now(); final file = File('${dir.path}/report_${report.id}.json'); final jsonString = jsonEncode(report.toJson()); await file.writeAsString(jsonString); } /// Mengambil seluruh daftar draft laporan tersimpan, diurutkan dari yang terbaru static Future> getAllReports() async { try { final dir = await _getReportsDirectory(); final entities = await dir.list().toList(); final List reports = []; for (final entity in entities) { if (entity is File && entity.path.endsWith('.json')) { try { final content = await entity.readAsString(); final Map jsonMap = jsonDecode(content); reports.add(SavedReport.fromJson(jsonMap)); } catch (e) { // Lewati berkas rusak } } } // Urutkan dari yang paling baru diupdate reports.sort((a, b) => b.updatedAt.compareTo(a.updatedAt)); return reports; } catch (e) { return []; } } /// Mengambil satu draft laporan berdasarkan ID static Future getReport(String id) async { try { final dir = await _getReportsDirectory(); final file = File('${dir.path}/report_$id.json'); if (await file.exists()) { final content = await file.readAsString(); final Map jsonMap = jsonDecode(content); return SavedReport.fromJson(jsonMap); } return null; } catch (e) { return null; } } /// Menghapus draft laporan berdasarkan ID static Future deleteReport(String id) async { try { final dir = await _getReportsDirectory(); final file = File('${dir.path}/report_$id.json'); if (await file.exists()) { await file.delete(); return true; } return false; } catch (e) { return false; } } }