import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:get/get.dart';
import 'package:http/http.dart' as http;

class RewardsController extends GetxController {
  final RxInt totalPoints = 0.obs;
  final RxBool isLoading = true.obs;
  final RxString error = ''.obs;

  Future<void> fetchBonusSummary(int userId) async {
    try {
      isLoading.value = true;
      // Using dynamic userid passed from ProfilePage
      final url = Uri.parse(
        'https://jupiter.nearle.app/live/api/v1/utils/getuserbonussummary/?userid=$userId',
      );

      final response = await http.get(
        url,
        headers: {'Accept': 'application/json'},
      );

      if (response.statusCode == 200) {
        final data = json.decode(response.body);
        if (data is Map<String, dynamic> && data['status'] == true) {
          // Check 'details' first, then 'data'
          final dynamic content = data['details'] ?? data['data'];

          if (content is Map<String, dynamic>) {
            // "bonuspts": 40
            totalPoints.value =
                int.tryParse((content['bonuspts'] ?? '0').toString()) ?? 0;
            debugPrint('[REWARDS] Fetched bonuspts: ${totalPoints.value}');
          } else if (content is List && content.isNotEmpty) {
             final first = content.first;
             if(first is Map<String, dynamic>) {
                totalPoints.value = int.tryParse((first['bonuspts'] ?? '0').toString()) ?? 0;
             }
          }
        }
      } else {
        error.value = 'Failed to load rewards';
      }
    } catch (e) {
      error.value = e.toString();
      debugPrint('[REWARDS] Error: $e');
    } finally {
      isLoading.value = false;
    }
  }
}
