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 {
  // Service to fetch all placed orders
  final GetOrderPlacedService _getOrderPlacedService = GetOrderPlacedService();
  // Controller to manage order placement functionality
  final OrderPlacedController _orderPlacedController = Get.put(OrderPlacedController());
  // Service to fetch a single placed order
 final GetSingleOrderPlacedService _getSingleOrderPlacedService = GetSingleOrderPlacedService();

  // Observable list to store fetched placed orders
  var placedOrders = <PlacedOrderList>[].obs;
  // Observable list to track products related to placed orders
  var products = <Product>[].obs;
  // Observable to handle loading state
  var isLoading = false.obs;

  @override
  void onInit() {
    super.onInit();
    getOrders(); // Fetch the orders immediately on initialization
  }
  // Function to fetch all placed orders
  Future<void> getOrders() async {
  // Call the service to fetch placed orders
      final fetchedOrders = await _getOrderPlacedService.getPlacedOrders();

      if (fetchedOrders != null && fetchedOrders.isNotEmpty) {
        // Add fetched orders to the observable list
        placedOrders.addAll(fetchedOrders);
        //logger.w("Fetched orders: $fetchedOrders");

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

  // Function to search and fetch a single placed order by ID
  Future<void> searchOrder() async {
    try {
      isLoading.value = true;
      // Fetch a single order based on the first order's ID in the list
      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 function to reset pagination and fetch fresh data
  void resetPagination() {
    // Reset pagination in the service
    _getOrderPlacedService.resetPagination();
    placedOrders.clear(); // Clear existing data
    getOrders(); // Fetch fresh orders after resetting
  }
}
