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

class KazanController extends GetxController {
  var kazanData = {}.obs;
  var isLoading = false.obs;
  final CRUD _crud = CRUD();

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

  Future<void> getKazan() async {
    isLoading.value = true;
    try {
      var response = await _crud.get(link: "${AppLink.getKazanPercent}?country=syria");
      if (response != null && response != 'failure' && response != 'token_expired') {
        var decoded = response is String ? jsonDecode(response) : response;
        if (decoded['status'] == "success") {
          var message = decoded['message'];
          if (message is List && message.isNotEmpty) {
            kazanData.value = message[0];
          }
        }
      }
    } catch (e) {
      Get.snackbar("خطأ", "فشل جلب بيانات التسعير: $e");
    } finally {
      isLoading.value = false;
    }
  }

  Future<bool> updateKazan(Map<String, dynamic> data) async {
    isLoading.value = true;
    try {
      final String link = data.containsKey('id') ? AppLink.updateKazanPercent : AppLink.addKazanPercent;
      
      Map<String, String> payload = {};
      data.forEach((key, value) {
        payload[key] = value.toString();
      });

      var response = await _crud.post(link: link, payload: payload);
      if (response != null && response is Map && response['status'] == "success") {
        await getKazan();
        return true;
      }
      return false;
    } catch (e) {
      Get.snackbar("خطأ", "فشل تحديث التسعير: $e");
      return false;
    } finally {
      isLoading.value = false;
    }
  }
}
