class OrderResponse {
  final List<Order> orders;

  OrderResponse({required this.orders});

  factory OrderResponse.fromJson(Map<String, dynamic> json) {
    return OrderResponse(
      orders: (json['orders'] as List? ?? [])
          .map((e) => Order.fromJson(e))
          .toList(),
    );
  }
}

class Order {
  final int orderheaderid;
  final String orderid;
  final String orderstatus;
  final DateTime? orderdate;
  final String? ordernotes;

  final String? deliverytime;
  final String? pending;
  final String? processing;
  final String? ready;
  final String? delivered;
  final String? cancelled;

  final double? deliverycharge;
  final String? kms;

  final String? pickupaddress;
  final String? pickupcustomer;
  final String? pickupcontactno;
  final String? pickupcity;

  final String? deliveryaddress;
  final String? deliverylat;
  final String? deliverylong;
  final String? deliverycustomer;
  final String? deliverycontactno;

  // ✅ Flat tenant fields (used directly in UI)
  final String? tenantname;
  final String? tenanttoken;
  final String? tenantcontactno;
  final String? tenantpostcode;
  final String? tenantsuburb;
  final String? tenantcity;
  final String? tenantimage;
  final String? registrationno;
  final String? gstno;

  // ✅ Flat tenant location fields
  final String? locationname;
  final String? locationcontactno;
  final String? locationpostcode;
  final String? locationsuburb;
  final String? locationcity;

  // ✅ App location
  final String? applocationname;

  // ✅ Financial
  final double? totaltaxamount;

  // ✅ Order details as a LIST (UI iterates over this)
  final List<OrderDetail>? orderdetails;

  Order({
    required this.orderheaderid,
    required this.orderid,
    required this.orderstatus,
    this.orderdate,
    this.ordernotes,
    this.deliverytime,
    this.pending,
    this.processing,
    this.ready,
    this.delivered,
    this.cancelled,
    this.deliverycharge,
    this.kms,
    this.pickupaddress,
    this.pickupcustomer,
    this.pickupcontactno,
    this.pickupcity,
    this.deliveryaddress,
    this.deliverylat,
    this.deliverylong,
    this.deliverycustomer,
    this.deliverycontactno,
    this.tenantname,
    this.tenanttoken,
    this.tenantcontactno,
    this.tenantpostcode,
    this.tenantsuburb,
    this.tenantcity,
    this.tenantimage,
    this.registrationno,
    this.gstno,
    this.locationname,
    this.locationcontactno,
    this.locationpostcode,
    this.locationsuburb,
    this.locationcity,
    this.applocationname,
    this.totaltaxamount,
    this.orderdetails,
  });

  factory Order.fromJson(Map<String, dynamic> json) {
    // ✅ Safely extract nested objects if present
    final tenant = json['tenant'] as Map<String, dynamic>? ?? {};
    final tenantlocation = json['tenantlocation'] as Map<String, dynamic>? ?? {};
    final applocation = json['applocation'] as Map<String, dynamic>? ?? {};

    // ✅ Parse orderdate safely
    DateTime? parsedDate;
    final rawDate = json['orderdate'];
    if (rawDate != null && rawDate.toString().isNotEmpty) {
      try {
        parsedDate = DateTime.parse(rawDate.toString());
      } catch (_) {
        parsedDate = null;
      }
    }

    // ✅ Safe parser — API may return orderdetails as {}, [], or null
    List<OrderDetail> parseOrderDetails(dynamic raw) {
      if (raw == null) return [];
      if (raw is List) return raw.map((e) => OrderDetail.fromJson(e as Map<String, dynamic>)).toList();
      if (raw is Map<String, dynamic>) return [OrderDetail.fromJson(raw)];
      return [];
    }

    return Order(
      orderheaderid: json['orderheaderid'] ?? 0,
      orderid: json['orderid'] ?? '',
      orderstatus: json['orderstatus'] ?? 'pending',
      orderdate: parsedDate,
      ordernotes: json['ordernotes'],

      deliverytime: json['deliverytime'],
      pending: json['pending'],
      processing: json['processing'],
      ready: json['ready'],
      delivered: json['delivered'],
      cancelled: json['cancelled'],

      deliverycharge: (json['deliverycharge'] ?? 0).toDouble(),
      kms: json['kms'],

      pickupaddress: json['pickupaddress'] ?? '',
      pickupcustomer: json['pickupcustomer'] ?? '',
      pickupcontactno: json['pickupcontactno'] ?? '',
      pickupcity: json['pickupcity'] ?? '',

      deliveryaddress: json['deliveryaddress'] ?? '',
      deliverylat: json['deliverylat']?.toString(),
      deliverylong: json['deliverylong']?.toString(),
      deliverycustomer: json['deliverycustomer'] ?? '',
      deliverycontactno: json['deliverycontactno'] ?? '',

      // ✅ Try flat field first, fallback to nested tenant object
      tenantname: json['tenantname'] ?? tenant['tenantname'] ?? 'Unknown Store',
      tenanttoken: json['tenanttoken'] ?? tenant['tenanttoken'] ?? '',
      tenantcontactno: json['tenantcontactno'] ?? tenant['tenantcontactno'] ?? '',
      tenantpostcode: json['tenantpostcode'] ?? tenant['tenantpostcode'] ?? '',
      tenantsuburb: json['tenantsuburb'] ?? tenant['tenantsuburb'] ?? '',
      tenantcity: json['tenantcity'] ?? tenant['tenantcity'] ?? '',
      tenantimage: json['tenantimage'] ?? tenant['tenantimage'],
      registrationno: json['registrationno'] ?? tenant['registrationno'] ?? '',
      gstno: json['gstno'] ?? tenant['gstno'] ?? '',

      locationname: json['locationname'] ?? tenantlocation['locationname'] ?? '',
      locationcontactno: json['locationcontactno'] ?? tenantlocation['locationcontactno'] ?? '',
      locationpostcode: json['locationpostcode'] ?? tenantlocation['locationpostcode'] ?? '',
      locationsuburb: json['locationsuburb'] ?? tenantlocation['locationsuburb'] ?? '',
      locationcity: json['locationcity'] ?? tenantlocation['locationcity'] ?? '',

      applocationname: json['applocationname'] ?? applocation['locationname'] ?? '',

      totaltaxamount: (json['totaltaxamount'] ?? 0).toDouble(),

      // ✅ Handles Map {}, List [], or null safely
      orderdetails: parseOrderDetails(json['orderdetails']),
    );
  }
}

class OrderDetail {
  final int orderdetailid;
  final String? productname;
  final int? orderqty;
  final double? price;
  final double? productsumprice;  // ✅ used for total amount calculation in UI
  final double? discountamount;   // ✅ used in OrderDetailsPage
  final String? productimage;     // ✅ used in OrderDetailsPage

  OrderDetail({
    required this.orderdetailid,
    this.productname,
    this.orderqty,
    this.price,
    this.productsumprice,
    this.discountamount,
    this.productimage,
  });

  factory OrderDetail.fromJson(Map<String, dynamic> json) {
    return OrderDetail(
      orderdetailid: json['orderdetailid'] ?? 0,
      productname: json['productname'] ?? 'Unknown Product',
      orderqty: json['orderqty'] ?? 0,
      price: (json['price'] ?? 0).toDouble(),
      // ✅ fallback to price if productsumprice not in response
      productsumprice: (json['productsumprice'] ?? json['price'] ?? 0).toDouble(),
      discountamount: (json['discountamount'] ?? 0).toDouble(),
      productimage: json['productimage'] ?? json['image'],
    );
  }
}