import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:dio/dio.dart'; import '../../../core/network/dio_client.dart'; import '../../../core/utils/app_snackbar.dart'; import '../../../core/utils/logger.dart'; class InvoiceDetailController extends GetxController { var invoice = {}.obs; var isLoading = true.obs; var isSaving = false.obs; String? invoiceId; @override void onInit() { super.onInit(); if (Get.arguments != null) { invoiceId = Get.arguments['id']; if (invoiceId != null) { fetchInvoiceDetails(); } } } Future fetchInvoiceDetails() async { try { isLoading.value = true; final res = await DioClient() .client .get('invoices/view', queryParameters: {'id': invoiceId}); if (res.data['success'] == true && res.data['data'] != null) { invoice.value = res.data['data']; } else { AppSnackbar.showError('خطأ', 'لم يتم العثور على الفاتورة'); Get.back(); } } catch (e) { AppLogger.error('Failed to fetch invoice details', e); AppSnackbar.showError('خطأ', 'فشل تحميل بيانات الفاتورة'); Get.back(); } finally { isLoading.value = false; } } Future updateInvoice(Map data) async { try { isSaving.value = true; data['id'] = invoiceId; final res = await DioClient().client.post('invoices/update', data: data); if (res.data['success'] == true) { AppSnackbar.showSuccess('تم الحفظ', 'تم تحديث بيانات الفاتورة'); await fetchInvoiceDetails(); } else { AppSnackbar.showError('خطأ', res.data['message'] ?? 'فشل التحديث'); } } catch (e) { AppLogger.error('Failed to update invoice', e); AppSnackbar.showError('خطأ', 'حدث خطأ أثناء التحديث'); } finally { isSaving.value = false; } } Future approveInvoice() async { try { final res = await DioClient() .client .post('invoices/approve', data: {'id': invoiceId}); if (res.data['success'] == true) { AppSnackbar.showSuccess('تم الاعتماد', 'تم اعتماد الفاتورة بنجاح'); fetchInvoiceDetails(); } else { AppSnackbar.showError('خطأ', 'فشل اعتماد الفاتورة'); } } catch (e) { AppLogger.error('Failed to approve invoice', e); AppSnackbar.showError('خطأ', 'حدث خطأ غير متوقع'); } } void viewOriginalImage() { final fileUrl = invoice['file_url']; if (fileUrl != null && fileUrl.isNotEmpty) { final fullUrl = 'https://musadaq.intaleqapp.com/api$fileUrl'; Get.to(() => Scaffold( appBar: AppBar( title: const Text('صورة الفاتورة'), backgroundColor: const Color(0xFF0F4C81)), body: Center( child: InteractiveViewer( child: Image.network( fullUrl, loadingBuilder: (context, child, loadingProgress) { if (loadingProgress == null) return child; return const CircularProgressIndicator(); }, errorBuilder: (context, error, stackTrace) { return const Text( 'فشل تحميل الصورة. قد يكون الملف مفقوداً على الخادم.'); }, ), ), ), )); } else { AppSnackbar.showWarning('عذراً', 'لا توجد صورة مرتبطة بهذه الفاتورة'); } } Future exportInvoices({String? companyId}) async { try { final cId = companyId ?? invoice['company_id']; AppSnackbar.showInfo('جاري التصدير', 'يتم تحميل ملف الفواتير...'); final res = await DioClient().client.get( 'invoices/export', queryParameters: {'company_id': cId}, options: Options(responseType: ResponseType.bytes), ); // For now, just confirm download was successful AppSnackbar.showSuccess('تم التصدير', 'تم تحميل ملف CSV بنجاح (${res.data.length} bytes)'); } catch (e) { AppLogger.error('Failed to export', e); AppSnackbar.showError('خطأ', 'فشل تصدير الفواتير'); } } Future submitToJoFotara() async { final confirmed = await Get.dialog( AlertDialog( title: const Text('تأكيد الإرسال'), content: const Text( 'هل أنت متأكد من إرسال هذه الفاتورة لمنظومة جوفتورة؟\nلا يمكن التراجع عن هذا الإجراء.'), actions: [ TextButton( onPressed: () => Get.back(result: false), child: const Text('إلغاء'), ), ElevatedButton( onPressed: () => Get.back(result: true), style: ElevatedButton.styleFrom( backgroundColor: const Color(0xFF6366F1), ), child: const Text('إرسال', style: TextStyle(color: Colors.white)), ), ], ), ); if (confirmed != true) return; try { AppSnackbar.showInfo('جاري الإرسال', 'يتم إرسال الفاتورة لمنظومة جوفتورة...'); final res = await DioClient().client.post( 'invoices/submit-jofotara', data: {'invoice_id': invoiceId}, ); if (res.data['success'] == true) { AppSnackbar.showSuccess('تم الإرسال', 'تم تقديم الفاتورة لجوفتورة بنجاح'); fetchInvoiceDetails(); } else { AppSnackbar.showError('خطأ', res.data['message'] ?? 'فشل الإرسال'); } } catch (e) { AppLogger.error('Failed to submit to JoFotara', e); AppSnackbar.showError('خطأ', 'فشل إرسال الفاتورة لجوفتورة'); } } }