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

class PaymentReceiptController extends GetxController {
  var payment = {}.obs;
  var isUploading = false.obs;
  final referenceController = TextEditingController();

  @override
  void onInit() {
    super.onInit();
    if (Get.arguments != null) {
      payment.value = Get.arguments;
    }
  }

  @override
  void onClose() {
    referenceController.dispose();
    super.onClose();
  }

  Future<void> submitReference() async {
    final ref = referenceController.text.trim();
    if (ref.isEmpty) {
      AppSnackbar.showWarning('تنبيه', 'الرجاء إدخال رقم المرجع أولاً');
      return;
    }

    try {
      isUploading.value = true;
      String paymentId = payment['id'];

      final res = await DioClient().client.post(
        'payments/verify-reference',
        data: {
          'payment_id': paymentId,
          'bank_reference': ref,
        },
      );

      if (res.data['success'] == true) {
        final data = res.data['data'];
        
        // Refresh subscription info
        if (Get.isRegistered<SubscriptionController>()) {
          Get.find<SubscriptionController>().loadAll();
        }

        Get.back(); // close the screen

        if (data['status'] == 'approved') {
          AppSnackbar.showSuccess('مبروك!', data['message']);
        } else {
          AppSnackbar.showInfo('تم الحفظ', data['message']);
        }
      }
    } catch (e) {
      AppLogger.error('Failed to submit reference', e);
      AppSnackbar.showError('خطأ', 'فشل التحقق من رقم المرجع. تأكد من صحته أو حاول لاحقاً.');
    } finally {
      isUploading.value = false;
    }
  }
}
