import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sefer_admin1/constant/links.dart';
import 'package:sefer_admin1/controller/functions/crud.dart';

import '../../constant/api_key.dart';
import '../../constant/box_name.dart';
import '../../main.dart';
import '../../print.dart';

class DashboardController extends GetxController {
  bool isLoading = false;
  List dashbord = [];
  String creditSMS = '0';
  final formKey = GlobalKey<FormState>();
  final smsText = TextEditingController();

  Future getDashBoard() async {
    isLoading = true;
    update();

    // 🔹 Request main dashboard data
    var res = await CRUD().get(link: AppLink.getdashbord, payload: {});
    print('📡 Main dashboard response: $res');

    if (res != 'failure') {
      var d = jsonDecode(res);
      print('✅ Decoded main dashboard: ${jsonEncode(d)}');
      dashbord = d['message'];
    } else {
      print('❌ Failed to load main dashboard');
    }

    // 🔹 Request wallet dashboard data
    var resPayments = await CRUD().postWallet(
      link: AppLink.getPaymentsDashboard,
      payload: {},
    );
    print('💳 Wallet dashboard response: $resPayments');

    if (resPayments != 'failure') {
      var p = resPayments;
      print('✅ Decoded wallet dashboard: ${jsonEncode(p)}');

      if (dashbord.isNotEmpty &&
          p['message'] is List &&
          p['message'].isNotEmpty) {
        dashbord[0].addAll(p['message'][0]);
      }
    } else {
      print('❌ Failed to load wallet dashboard');
    }

    // 🔹 Check SMS credit
    var res2 = await CRUD().kazumiSMS(
      link: 'https://sms.kazumi.me/api/sms/check-credit',
      payload: {"username": "Sefer", "password": AK.smsPasswordEgypt},
    );

    creditSMS = res2['credit'];
    print('📱 SMS Credit Response: ${jsonEncode(res2)}');
    print('💰 creditSMS: $creditSMS');

    isLoading = false;
    update();
  }

  sendSMSMethod() async {
    if (formKey.currentState!.validate()) {
      for (var phoneNumber in box.read(BoxName.tokensDrivers)['message']) {
        // for (var i = 0; i < 2; i++) {
        await CRUD().sendSmsEgypt(
          phoneNumber['phone'].toString(),
          // box.read(BoxName.tokensDrivers)['message'][i]['phone'].toString(),
          smsText.text,
        );
        // print('CRUD().phoneDriversTest.: ${phoneNumber['phone']}');
        Future.delayed(const Duration(microseconds: 20));
      }
      Get.back();
    }
  }

  @override
  void onInit() async {
    getDashBoard();

    super.onInit();
  }
}
