import 'dart:convert';
import 'package:get/get.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';


class NotificationController extends GetxController {
  RxBool isLoading = false.obs;
  RxList<NotificationModel> notifications = <NotificationModel>[].obs;

  Future<void> fetchNotifications() async {
    isLoading.value = true;

    SharedPreferences prefs = await SharedPreferences.getInstance();

    // SAFE READ → Handles int or string
    dynamic t = prefs.get("tenantId");
    dynamic l = prefs.get("locationId");

    String tenantId = t?.toString() ?? "";
    String locationId = l?.toString() ?? "";

    final url =
        "https://jupiter.nearle.app/live/api/v1/utils/gettenantnotifications/?tenantid=$tenantId&locationid=$locationId";

    try {
      var response = await http.get(Uri.parse(url));

      print(url);

      if (response.statusCode == 200) {
        final data = jsonDecode(response.body);

        if (data["status"] == true) {
          notifications.value = (data["details"] as List)
              .map((e) => NotificationModel.fromJson(e))
              .toList();
        }
      }
    } catch (e) {
      print("Notification API Error: $e");
    }

    isLoading.value = false;
  }

  @override
  void onInit() {
    fetchNotifications(); // auto load on page open
    super.onInit();
  }
}



class NotificationModel {
  final int notificationid;
  final String title;
  final String message;
  final String notificationdate;

  NotificationModel({
    required this.notificationid,
    required this.title,
    required this.message,
    required this.notificationdate,
  });

  factory NotificationModel.fromJson(Map<String, dynamic> json) {
    return NotificationModel(
      notificationid: json["notificationid"],
      title: json["title"] ?? "",
      message: json["message"] ?? "",
      notificationdate: json["notificationdate"] ?? "",
    );
  }
}
