import 'package:get/get.dart';
import '../../../core/network/dio_client.dart';
import '../../../core/utils/app_snackbar.dart';
import '../../../core/utils/logger.dart';

class TaxReportController extends GetxController {
  var isLoading = true.obs;
  var report = {}.obs;
  var selectedMonth = DateTime.now().month.obs;
  var selectedYear = DateTime.now().year.obs;
  String? companyId;

  @override
  void onInit() {
    super.onInit();
    if (Get.arguments != null) {
      companyId = Get.arguments['company_id'];
    }
    fetchReport();
  }

  Future<void> fetchReport() async {
    try {
      isLoading.value = true;
      final params = <String, dynamic>{
        'month': selectedMonth.value,
        'year': selectedYear.value,
      };
      if (companyId != null) params['company_id'] = companyId;

      final res = await DioClient().client.get('reports/tax-summary', queryParameters: params);
      if (res.data['success'] == true) {
        report.value = res.data['data'];
      }
    } catch (e) {
      AppLogger.error('Failed to fetch tax report', e);
      AppSnackbar.showError('خطأ', 'تعذر تحميل التقرير');
    } finally {
      isLoading.value = false;
    }
  }

  void changeMonth(int delta) {
    var m = selectedMonth.value + delta;
    var y = selectedYear.value;
    if (m > 12) { m = 1; y++; }
    if (m < 1) { m = 12; y--; }
    selectedMonth.value = m;
    selectedYear.value = y;
    fetchReport();
  }

  String get monthName {
    const months = ['', 'يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو',
                    'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر'];
    return '${months[selectedMonth.value]} ${selectedYear.value}';
  }
}
