import 'package:cheminova/controller/get_single_placed_order_service.dart';
import 'package:cheminova/controller/place_order_controller.dart';
import 'package:cheminova/models/place_order_list_model.dart';
import 'package:get/get.dart';

import '../models/oder_place_model.dart';
import '../models/product_model1.dart';
import '../utils/log_service.dart';
import 'get_place_order_service.dart';

class GetPlacedOrderController extends GetxController {
  final GetOrderPlacedService _getOrderPlacedService = GetOrderPlacedService();
  final OrderPlacedController _orderPlacedController = Get.put(OrderPlacedController());
 final GetSingleOrderPlacedService _getSingleOrderPlacedService = GetSingleOrderPlacedService();
  var placedOrders = <PlacedOrderList>[].obs;
  var products = <Product>[].obs;

  var isLoading = false.obs;

  @override
  void onInit() {
    super.onInit();
    getOrders(); // Fetch the orders immediately on initialization
  }

  Future<void> getOrders() async {

      final fetchedOrders = await _getOrderPlacedService.getPlacedOrders();

      if (fetchedOrders != null && fetchedOrders.isNotEmpty) {
        placedOrders.addAll(fetchedOrders);
        //logger.w("Fetched orders: $fetchedOrders");

      } else {
        //logger.w("No orders fetched");
      }
    }


  Future<void> searchOrder() async {
    try {
      isLoading.value = true;
      final order = await _getSingleOrderPlacedService.getSinglePlacedOrder(placedOrders[0].id);
      if (order != null) {
        placedOrders.clear(); // Clear existing orders if needed
        placedOrders.add(order);
      } else {
        // Handle order not found case
      }
    } catch (e) {
      // Handle exceptions
    } finally {
      isLoading.value = false;
    }
  }

  // Optional: Reset the pagination if needed
  void resetPagination() {
    _getOrderPlacedService.resetPagination();
    placedOrders.clear(); // Clear existing data
    getOrders(); // Fetch fresh data
  }
}
