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 '../../print.dart';

class SecurityV2Controller extends GetxController {
  bool isLoading = true;
  List<dynamic> auditLogs = [];

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

  Future<void> fetchAuditLogs() async {
    isLoading = true;
    update();

    try {
      Log.print('Fetching from: ${AppLink.auditLogsV2}');
      var res = await CRUD().get(link: AppLink.auditLogsV2, payload: {});
      Log.print('Raw audit res type: ${res.runtimeType} | value: $res');

      if (res == 'failure' || res == 'token_expired') {
        Log.print('CRUD returned: $res');
        Get.snackbar("خطأ بالاتصال", "السيرفر أرجع: $res",
            backgroundColor: const Color(0x88FF0000),
            colorText: const Color(0xFFFFFFFF));
        auditLogs = [];
      } else if (res != null) {
        var d = res is String ? jsonDecode(res) : res;
        Log.print('Decoded audit response: $d');
        if (d['status'] == 'success') {
          var message = d['message'];
          if (message is List) {
            auditLogs = message;
            Log.print('Loaded ${auditLogs.length} audit logs');
          } else {
            auditLogs = [];
            Log.print('message is not List: ${message.runtimeType}');
          }
        } else {
          Log.print('Status not success: ${d['status']}');
          Get.snackbar("خطأ من السيرفر", "${d['message'] ?? d['status']}",
              backgroundColor: const Color(0x88FF0000),
              colorText: const Color(0xFFFFFFFF));
        }
      }
    } catch (e) {
      Log.print('Error fetching audit logs: $e');
      Get.snackbar("خطأ برمجي", "$e",
          backgroundColor: const Color(0x88FF0000),
          colorText: const Color(0xFFFFFFFF));
    }

    isLoading = false;
    update();
  }
}
