

import 'package:supplier_new/common/settings.dart';
import 'package:geolocator/geolocator.dart';

class  OrdersModel {
  String building_name = '';
  String phone = '';
  String address = '';
  String type_of_water = '';
  String capacity = '';
  String quantity = '';
  String time = '';
  String averageTime = '';
  String quoted_amount = '';
  String displayAddress='';
  double lat=0;
  double lng=0;
  double distanceInMeters=0;
  double distanceInKm=0.0;
  String dbId = '';
  String status='';
  String date='';
  String imageAsset='images/building.png';
  String delivery_agent_name = '';
  String tanker_name = '';
  String water_source_location='';
  String remarks='';

  String unload_start_time = '';

  String bookingid = '';
  String tank_name = '';
  String tankLocation = '';

  List<String> extraStatus = [];

  double? sourceLat;
  double? sourceLng;
  double? buildingLat;
  double? buildingLng;
  String delivery_agent_mobile='';
  String amount_due = '';
  String amount_paid = '';
  String supplier_upi_id = '9000950877@ybl';
  String supplier_name = '';
  String payment_mode = '';
  String tanker_status = '';
  String tanker_availability = '';
  String start_time = '';
  String stop_time = '';
  DateTime? orderDate;

  OrdersModel();

  factory OrdersModel.fromJson(Map<String, dynamic> json){
    OrdersModel rtvm = new OrdersModel();

    rtvm.building_name = json['buildingName'] ?? '';
    rtvm.phone = json['customerPhone'] ?? '';
    rtvm.dbId = json['_id']?? '';
    rtvm.address   = json['address'] ?? '';
    rtvm.type_of_water   = json['typeofwater'] ?? '';
    rtvm.capacity   = json['capacity'] ?? '';
    rtvm.quantity   = json['quantity']?? '';
    rtvm.time   = json['time'] ?? '';
    rtvm.date   = json['expectedDateOfDelivery'] ?? '';
    rtvm.status   = json['orderStatus'] ?? '';
    rtvm.quoted_amount   = json['price'].toString() ?? '';
    rtvm.lng=json['longitude'] ?? 0.0;
    rtvm.lat=json['latitude'] ?? 0.0;
    rtvm.delivery_agent_name = json['delivery_agent'] ?? '';
    rtvm.tanker_name = json['tankerName'] ?? '';
    rtvm.water_source_location = json['water_source_location'] ?? '';
    rtvm.remarks = json['remarks'] ?? '';
    rtvm.delivery_agent_mobile=json['delivery_agent_mobile']??'';


    // Split and trim
    List<String> parts = rtvm.address.split(',').map((e) => e.trim()).toList();

// Usually, the locality is the part before the main city (Hyderabad)displayAddress = "";
    if (parts.length >= 2) {
      rtvm.displayAddress = parts[parts.length -4]; // "Banjara Hills"
    }
    // Distance in meters
    rtvm.distanceInMeters = double.parse(
      Geolocator.distanceBetween(
        rtvm.lat,
        rtvm.lng,
        AppSettings.supplierLatitude,
        AppSettings.supplierLongitude,
      ).toStringAsFixed(2),
    );

// Distance in km
    rtvm.distanceInKm = double.parse(
      (rtvm.distanceInMeters / 1000).toStringAsFixed(2),
    );


    rtvm.tank_name = json['tankName'] ?? '';
    rtvm.tankLocation = json['tankLocation'] ?? '';

    rtvm.amount_due = json['amount_due'] ?? '';
    rtvm.amount_paid = json['amount_paid'] ?? '';
    rtvm.supplier_name = json['supplierName'] ?? '';
    rtvm.payment_mode = json['payment_mode'] ?? '';
    rtvm.start_time = json['start_time'] ?? '';
    rtvm.stop_time = json['stop_time'] ?? '';

    if (rtvm.date.isNotEmpty) {
      final parts = rtvm.date.split('-');

      if (parts.length == 3) {
        final day = int.tryParse(parts[0]) ?? 1;
        final year = int.tryParse(parts[2]) ?? 1970;

        final monthStr = parts[1].toLowerCase();

        const monthMap = {
          'jan': 1,
          'feb': 2,
          'mar': 3,
          'apr': 4,
          'may': 5,
          'jun': 6,
          'jul': 7,
          'aug': 8,
          'sep': 9,
          'oct': 10,
          'nov': 11,
          'dec': 12,
        };

        final month = monthMap[monthStr];

        if (month != null) {
          rtvm.orderDate = DateTime(year, month, day);
        }
      }
    }

    // ---------------- EXTRA DATA ----------------
    if (json['extra'] != null && json['extra'] is List) {
      for (var item in json['extra']) {
        if (item['status'] != null && item['status'] is List) {
          List<String> statusList =
          List<String>.from(item['status'].map((e) => e.toString()));

          rtvm.extraStatus = statusList;

          if (statusList.length >= 1) {
            rtvm.tanker_status = statusList[0].toLowerCase();
          }

          if (statusList.length >= 2) {
            rtvm.tanker_availability = statusList[1].toLowerCase();
          }
        }

        if (item['source_location'] != null) {
          rtvm.sourceLat =
              (item['source_location']['latitude'] ?? 0).toDouble();
          rtvm.sourceLng =
              (item['source_location']['longitude'] ?? 0).toDouble();
        }

        if (item['building_location'] != null) {
          rtvm.buildingLat =
              (item['building_location']['latitude'] ?? 0).toDouble();
          rtvm.buildingLng =
              (item['building_location']['longitude'] ?? 0).toDouble();
        }
      }
    }


    return rtvm;
  }
  Map<String, dynamic> toJson() => {
    "boreName":this.building_name,
  };
}