import 'dart:convert';
import 'package:get/get.dart';
import 'package:siro_admin/constant/links.dart';
import 'package:siro_admin/controller/functions/crud.dart';
import '../../print.dart';

class AnalyticsV2Controller extends GetxController {
  bool isLoading = true;
  
  Map<String, dynamic> growthData = {};
  Map<String, dynamic> revenueData = {};
  List<dynamic> topDrivers = [];

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

  Future<void> fetchAllAnalytics() async {
    isLoading = true;
    update();
    
    await Future.wait([
      fetchGrowth(),
      fetchRevenue(),
      fetchDriverRanking(),
    ]);
    
    isLoading = false;
    update();
  }

  Future<void> fetchGrowth() async {
    try {
      var res = await CRUD().get(link: AppLink.growthV2, payload: {});
      if (res != 'failure' && res != null) {
        var d = res is String ? jsonDecode(res) : res;
        if (d['status'] == 'success') {
          growthData = d['data'];
        }
      }
    } catch (e) {
      Log.print('Error fetching growth analytics: $e');
    }
  }

  Future<void> fetchRevenue() async {
    try {
      var res = await CRUD().get(link: AppLink.revenueV2, payload: {});
      if (res != 'failure' && res != null) {
        var d = res is String ? jsonDecode(res) : res;
        if (d['status'] == 'success') {
          revenueData = d['data'];
        }
      }
    } catch (e) {
      Log.print('Error fetching revenue analytics: $e');
    }
  }

  Future<void> fetchDriverRanking() async {
    try {
      var res = await CRUD().get(link: AppLink.driverRankingV2, payload: {});
      if (res != 'failure' && res != null) {
        var d = res is String ? jsonDecode(res) : res;
        if (d['status'] == 'success') {
          topDrivers = d['data'];
        }
      }
    } catch (e) {
      Log.print('Error fetching driver ranking: $e');
    }
  }
}
