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

class ReferralController extends GetxController {
  var isLoading = true.obs;
  var hasError = false.obs;
  var errorMessage = ''.obs;
  var referralData = Rxn<Map<String, dynamic>>();

  @override
  void onInit() {
    super.onInit();
    fetchReferralCode();
  }

  String get code => referralData.value?['code'] ?? '';
  String get link => referralData.value?['link'] ?? '';
  Map<String, dynamic> get stats => Map<String, dynamic>.from(referralData.value?['stats'] ?? {});
  List get recent => referralData.value?['recent'] ?? [];
  Map<String, dynamic> get rewardRules => Map<String, dynamic>.from(referralData.value?['reward_rules'] ?? {});

  Future<void> fetchReferralCode() async {
    try {
      isLoading.value = true;
      hasError.value = false;
      final res = await DioClient().client.get('referral/my-code');
      if (res.data['success'] == true) {
        referralData.value = Map<String, dynamic>.from(res.data['data']);
      } else {
        hasError.value = true;
        errorMessage.value = res.data['message'] ?? 'خطأ غير معروف';
        debugPrint('Referral API error: ${res.data}');
      }
    } catch (e) {
      hasError.value = true;
      errorMessage.value = 'تعذّر الاتصال بالخادم';
      AppLogger.error('Failed to fetch referral code', e);
    } finally {
      isLoading.value = false;
    }
  }
}
