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

class ComplaintController extends GetxController {
  var complaintList = [].obs;
  var isLoading = false.obs;
  var showOnlyDelayed = false.obs;
  final CRUD _crud = CRUD();
  
  List<dynamic> get delayedComplaints {
    final weekAgo = DateTime.now().subtract(const Duration(days: 7));
    return complaintList.where((c) {
      if (c['statusComplaint'] == 'Resolved') return false;
      try {
        final date = DateTime.parse(c['date_filed']);
        return date.isBefore(weekAgo);
      } catch (e) {
        return false;
      }
    }).toList();
  }

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

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

  Future<bool> updateComplaintStatus(String id, String status, String resolution) async {
    isLoading.value = true;
    try {
      var response = await _crud.post(link: "${AppLink.server}/serviceapp/update_complaint.php", payload: {
        "id": id,
        "statusComplaint": status,
        "resolution": resolution,
      });
      if (response != null && response is Map && response['status'] == "success") {
        await getComplaints();
        return true;
      }
      return false;
    } catch (e) {
      Get.snackbar("خطأ", "فشل تحديث الشكوى: $e");
      return false;
    } finally {
      isLoading.value = false;
    }
  }
}
