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

class PromoController extends GetxController {
  var promoList = [].obs;
  var isLoading = false.obs;
  final CRUD _crud = CRUD();

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

  Future<void> getPromos() async {
    isLoading.value = true;
    try {
      var response = await _crud.get(link: AppLink.getPassengersPromo);
      if (response != null && response != 'failure' && response != 'token_expired') {
        var decoded = response is String ? jsonDecode(response) : response;
        if (decoded['status'] == "success") {
          promoList.assignAll(decoded['message']);
        }
      } else {
        promoList.clear();
      }
    } catch (e) {
      Get.snackbar("خطأ", "فشل جلب أكواد الخصم: $e");
    } finally {
      isLoading.value = false;
    }
  }

  Future<bool> addPromo(Map<String, dynamic> data) async {
    isLoading.value = true;
    try {
      var response = await _crud.post(link: AppLink.addPassengersPromo, payload: data);
      if (response != null && response is Map && response['status'] == "success") {
        await getPromos();
        return true;
      }
      return false;
    } catch (e) {
      Get.snackbar("خطأ", "فشل إضافة كود الخصم: $e");
      return false;
    } finally {
      isLoading.value = false;
    }
  }

  Future<bool> deletePromo(String id) async {
    try {
      var response = await _crud.post(link: AppLink.deletePassengersPromo, payload: {"id": id});
      if (response != null && response is Map && response['status'] == "success") {
        await getPromos();
        return true;
      }
      return false;
    } catch (e) {
      Get.snackbar("خطأ", "فشل حذف كود الخصم: $e");
      return false;
    }
  }

  Future<bool> updatePromo(Map<String, dynamic> data) async {
    isLoading.value = true;
    try {
      var response = await _crud.post(link: AppLink.updatePassengersPromo, payload: data);
      if (response != null && response is Map && response['status'] == "success") {
        await getPromos();
        return true;
      }
      return false;
    } catch (e) {
      Get.snackbar("خطأ", "فشل تحديث كود الخصم: $e");
      return false;
    } finally {
      isLoading.value = false;
    }
  }
}
