import { Component, ElementRef, OnInit, ViewChild } from "@angular/core";
import { FormArray, FormBuilder, FormControl, FormGroup, Validators } from "@angular/forms";
import { ActivatedRoute, Router } from "@angular/router";
import * as _ from 'lodash';
import * as moment from "moment";
import { MessageService, PrimeNGConfig } from 'primeng/api';
import { forkJoin } from "rxjs";
import { CommonFunctionService } from "src/app/core/common/common-function.service";
import { ValidationService } from "src/app/core/common/validation.service";
import { HotelBookingManagementService } from "src/app/core/services/HotelServices/hotel_booking_management.service";
import { API } from "src/app/core/services/api.service";

@Component({
  selector: 'app-hotel-booking-view',
  templateUrl: './hotel-booking-view.component.html',
})
export class HotelBookingViewComponent {
  dialogStatus = [];
  isOpenAddNote: boolean = false;
  VendorInvoiceForm:FormGroup;
  isOpenCancellationPolicyModal: boolean = false;
  isOpenAddConfirmationNumberModal: boolean = false;
  isOpenAddVendorInvoiceNumberModal: boolean = false;
  isOpenAddInvoiceNumberModal: boolean = false;
  openInvoiceNumberModal() {
    this.isOpenAddInvoiceNumberModal = true;
  }
  trip_id = '';
  active_tab;
  AllCurrency;
  addConfirmationNumber
  AssignUserList;
  User_Name;
  User_Id = [{ user_id: '', user_name: 'Assign to me' }];
  AssignUser;
  User_Type;
  value: Date;
  AllLanguage;
  WhatsApp_Support;
  agency_decimal_definer = '2';
  supplier_decimal_definer = '2';
  modalReference;
  hotelBookingResp;
  hotelItenaryResp;
  hotelRoomDetail;
  hotelGuestDetail;
  hotelRoomGuestDetail;
  hotelPassengerResp;
  hotelCostingResp;
  hotelPaymentResp;
  hotelPaymentList;
  hotelTotalAmount;
  hotelNotesResp;
  bookingId;
  supplierNightlyRate = [];
  hotelDocumentResp;
  hotelSupplierCancellationPolicy;
  hotelAgentCancellationPolicy;
  hotelPassSupplierCancellationPolicy;
  hotelPassAgentCancellationPolicy;
  title = "appBootstrap";
  @ViewChild("NotesText") NotesInp: ElementRef;
  closeResult: string = "";
  confirmationForm: FormGroup;
  updateAccountingForm: FormGroup;
  ConfirmationNo;
  ConfirmationDate;
  ConfirmationStaffName;
  ConfirmationStaffRemarks;
  agencyPolicyCharge;
  supplierPolicyCharge;
  bookingHistory: boolean = false;
  bookingDetails: boolean = false;
  ReleaseModal: boolean = false;
  UpdateInStatus: boolean = false;
  UpdAccountPayStatus: boolean = false;
  rateBreakup: boolean = false;
  CancellationDetails = null;
  is_roomwise_policy: boolean = false;
  checkBookingCancel = false;
  CancellationRemarks = '';
  Cancellation_Agent_Amont = 0;
  Cancellation_Supp_Amont = 0;
  //SAGAR
  currency_list = null;
  booking_customer_data = null;
  itinerary_tab_data = null;
  guest_tab_data = null;
  costing_tab_data = null;
  payment_tab_data = null;
  document_tab_data = null;
  note_tab_data = null;
  verification_tab_data = null;
  veri_tab_data_mid = null;
  selected__mail_document_type = "";
  mailForm: FormGroup;
  StatusGroup: FormGroup;
  hotelBookingForm: FormGroup;
  notesform: FormGroup;
  updateAccountingPayForm: FormGroup;
  BookingStatus = [
    { key: 0, value: "In Progress" },
    { key: 1, value: "Pending" },
    { key: 3, value: "Confirmed" },
    { key: 4, value: "Cancelled" },
    { key: 6, value: "Reserved" }
  ];
  thirdPartyInvoiceStatus = [
    {name: 'In Process' ,value: 'In Process'},
    {name: 'Pending' ,value: 'Pending'},
    {name: 'Success' ,value: 'Success'},
    {name: 'Failed' ,value: 'Failed'}
  ]
  paymentStatusList = [
    {name: 'Paid' ,value: 'PAID'},
    {name: 'Partly Paid' ,value: 'PARTLYPAID'},
  ]
  paymentModeList = [
    {name: 'Payment Gateway', value: 'PAYMENTGATEWAY'},
    {name: 'Wallet Adjustment', value: 'WALLET'},
    {name: 'Accounting System Ledger', value: 'ACCONTING'},
  ]
  tab_data_status = { itinerary: "loading", passenger: "loading", costing: "loading", payment: "loading", document: "loading" };
  features;
  AllPaymentData;
  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private fb: FormBuilder,
    public APIServ: HotelBookingManagementService,
    private ApiServ: API,
    private messageService: MessageService,
    public validationServ: ValidationService,
    private primengConfig: PrimeNGConfig,
    public commonserv: CommonFunctionService,
  ) {
    this.route.queryParams.subscribe(params => {
      this.trip_id = params['id'];
    });
  }

  // private getDismissReason(reason: any): string {
  //   if (reason === ModalDismissReasons.ESC) {
  //     return "by pressing ESC";
  //   } else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
  //     return "by clicking on a backdrop";
  //   } else {
  //     return `with: ${reason}`;
  //   }
  // }
  ngOnInit(): void {
    // this.ApiServ.setTitle('Hotel Booking');
    this.getFeatures('2308111245266426287');
    this.initFormsGroup();
    this.GetAllData();
    this.initConfirmationForm(null);
    this.primengConfig.ripple = true;
    this.User_Type = sessionStorage.getItem('userType');
    this.User_Name = sessionStorage.getItem('userName');
    this.User_Id[0]['user_id'] = sessionStorage.getItem('userId');
  }

  GetAllData(){
    forkJoin(
      this.getCurrencyList(),
      this.APIServ.getAllCurrency(),
      this.getPageHeadersDetails(),
      this.GetAllLAng(),
    ).subscribe(res=>{
      if(res?.length > 0){
        this.AllCurrency = res[0];
        this.currency_list = res[1];
        if (res[2]) {
          this.booking_customer_data = res[2];
          this.booking_customer_data.booking_date = this.booking_customer_data.booking_date ? this.commonserv.UtcToLocaleTime(this.booking_customer_data.booking_date, 'DD MMM YYYY, HH:mm:ss') : null;
          this.booking_customer_data.customer_contact = this.booking_customer_data.customer_contact != null && this.booking_customer_data.customer_contact.trim() != '' ? (this.booking_customer_data.customer_contact.charAt(0) == '+' || this.booking_customer_data.customer_contact.charAt(0) == '-' ? this.booking_customer_data.customer_contact : '+' + this.booking_customer_data.customer_contact) : '';
          this.AssignUser = this.booking_customer_data.assigned_user_name?this.booking_customer_data.assigned_user_name:null;
        }
        this.AllLanguage = res[3];
        this.getItineraryTabDetails();
      }
    })
  }

  initFormsGroup() {
    this.StatusGroup = this.fb.group({
      statusArr: this.fb.array([])
    });

    this.hotelBookingForm = this.fb.group({
        reasonOfNote: this.validationServ.required
    });
    this.notesform = this.fb.group({
      Note: this.validationServ.required
  });
    this.updateAccountingForm = this.fb.group({
      acc_invoice_status: this.validationServ.required,
      acc_invoice_number: this.validationServ.required,
      acc_ref_number: this.validationServ.required
    });

    this.updateAccountingPayForm = this.fb.group({
      booking_id: this.validationServ.required,
      payment_status: this.validationServ.required,
      payment_mode: this.validationServ.required,
      currency: [""],
      pending_amt: [0],
      amount: this.validationServ.required,
      receipt_no: this.validationServ.required,
      remark: this.validationServ.required,
  });
    this.VendorInvoiceForm = this.fb.group({
      vendor_invoice_number : this.validationServ.required
    });
  };

  get statusArr() {
    return this.StatusGroup.get('statusArr') as FormArray;
  };

  showStatusDialog(ind) {
    this.dialogStatus[ind] = true;
  }

  CreateStatusGroup(data) {
    if (data.length > 0 && data) {
      data.forEach((e, i) => {
        this.dialogStatus[i] = false;
        this.statusArr.push(this.fb.group({
          status: [e.status_id, Validators.required]
        }));
      });
    };
  };
  

  tabClick(e) {
    console.log(e);
    switch (e.index) {
      case 0: {
        this.active_tab = e.index;
        this.getItineraryTabDetails();
        break;
      }
      case 1: {
        this.active_tab = e.index;
        this.getPassengerTabDetails();
        break;
      }
      case 2: {
        this.active_tab = e.index;
        this.getCostingTabDetails();
        break;
      }
      case 3: {
        this.active_tab = e.index;
        this.getBookingNoteDetails();
        break;
      }
      case 4: {
        this.getDocumentTabDetails();
        break;
      }
      case 5: {
        this.getBookingNoteDetails();
        break;
      }
      case 6: {
        this.getHBookingDetails();
        break;
      }
    }
  }
  getPageHeadersDetails() {
    this.booking_customer_data = null;
    return this.APIServ.getCustomerDetails(this.trip_id)
  }
  getItineraryTabDetails() {
    this.tab_data_status.itinerary = "loading";
    this.itinerary_tab_data = null;
    this.APIServ.GetItenaryDetails(this.trip_id).subscribe((data: any) => {
      if (data) {
        this.CreateStatusGroup(data);
        this.itinerary_tab_data = data;
        this.WhatsApp_Support = data[0] ?  data[0].is_whatsapp_notify : false;//added is whatapp check of agency 
        if (this.itinerary_tab_data[0].payment_mode) {
          this.updateAccountingPayForm.get('payment_mode').setValue(this.itinerary_tab_data[0].payment_mode);
        }
        if (this.itinerary_tab_data.assigned_user) {
          this.itinerary_tab_data.assigned_user == this.User_Id[0]['user_id'] ? this.User_Id[0]['user_name'] = this.User_Name : this.itinerary_tab_data = [{ user_id: this.itinerary_tab_data.assigned_user, user_name: this.itinerary_tab_data.assigned_user_name }]
        }
        let hotelCities = [];
        if (this.itinerary_tab_data.length > 0 && this.itinerary_tab_data) {
          this.itinerary_tab_data.forEach(e => {
            e.reserved_timeline_local = e.reserved_timeline_local ? this.commonserv.UtcToLocaleTime(e.reserved_timeline_local, 'DD MMM YYYY, HH:mm:ss') : e.reserved_timeline_local;
            let onlyTime = e.user_timezone ? e.user_timezone.replace('UTC', '') : '';
            let obj_supplier_currency = this.currency_list.find(x => x.currency_code == e['supplier_currency']);
            let supplier_decimal_definer = obj_supplier_currency ? obj_supplier_currency.currency_deci_definer : '2';
            e['supplier_total_amount'] = e['supplier_total_amount'] ? this.commonserv.amountDefiner(e['supplier_total_amount'],supplier_decimal_definer) : e['supplier_total_amount'];
            if (onlyTime) {
              let time = onlyTime.replace(')', ' Local Time)');
              e.user_timezone = time;
            }
            if (e.hotel_city_code) {
              hotelCities.push(e.hotel_city_code);
            };
            e['lan'] = null;
            e['lon'] = null;
            e['Ip'] = null;
            if (e?.booking_user_lat_lon) {
              let booking_user_IP_details = JSON.parse(e.booking_user_lat_lon);
              e['lan'] = booking_user_IP_details ? booking_user_IP_details?.lat : null
              e['lon'] = booking_user_IP_details ? booking_user_IP_details?.lon : null
              e['Ip'] = booking_user_IP_details ? booking_user_IP_details?.query : null
            };
          })
        }
        if (hotelCities.length > 0 && hotelCities) {
          this.GetSpecifiCitydetail(hotelCities);
        }
        this.tab_data_status.itinerary = "success";
      } else {
        this.tab_data_status.itinerary = "failed";
      }
    }, (error) => {
      this.tab_data_status.itinerary = "failed";
    });
  }
  cityList = null;
  /**
  * @author Abdul Razzak
  * to get Specific city list
  * @param val city code
  */
  GetSpecifiCitydetail(val) {
    let obj = {
      cityCodes: val,
    };
    this.APIServ.GethotelCityName(obj).subscribe((data) => {
      if (data) {
        this.cityList = data;
      } else {
        this.cityList = null;
      }
    });
  }

  mapHotelBkgDeadline(data) {
    let agent_cancellation_policy = data.cancellation_policy.filter(x => x.from_type == 'agent').sort(function (a, b) { return a.sequence_no - b.sequence_no });
    let dateTimeArray = [];
    if (agent_cancellation_policy && agent_cancellation_policy.length > 0) {
      agent_cancellation_policy.forEach(cp => {
        let date = cp.deadline_date_from != null && cp.deadline_date_from != '' ? this.commonserv.UtcToLocaleTime(cp.deadline_date_from, 'DD MMM YYYY') : '';
        let time = cp.deadline_time_from != null && cp.deadline_time_from != '' ? this.commonserv.UtcToLocaleTime(cp.deadline_time_from, 'hh:mm A') : '';
        let datetime = date && date != '' ? `${date} ${time}` : ''
        if (datetime && datetime != null) {
          dateTimeArray.push(datetime);
        }
      });

      let $this = this;
      dateTimeArray = dateTimeArray.sort(function (a, b) { return parseInt($this.commonserv.UtcToLocaleTime(a, 'YYYYMMDDHHmm')) - parseInt($this.commonserv.UtcToLocaleTime(b, 'YYYYMMDDHHmm')) });
    }
    return dateTimeArray && dateTimeArray.length > 0 ? dateTimeArray[0] : '';
  }

  getPassengerTabDetails() {
    this.tab_data_status.passenger = "loading";
    this.guest_tab_data = null;
    this.APIServ.getPassengerDetails(this.trip_id).subscribe((data: any) => {
      if (data) {
        this.guest_tab_data = data;
        this.guest_tab_data.map(li => {
          li.booking_date = this.commonserv.UtcToLocaleTime(li.booking_date, 'DD MMM YYYY, HH:mm:ss')
        })
        this.tab_data_status.passenger = "success";
      } else {
        this.tab_data_status.passenger = "failed";
      }
    }, (error) => {
      this.tab_data_status.passenger = "failed";
    });
  }
  getCostingTabDetails() {
    this.tab_data_status.costing = "loading";
    this.costing_tab_data = null;
    this.APIServ.getCostingDetails(this.trip_id).subscribe((data: any) => {
      if (data) {
        let booking_list = [];
        data.map(bkg => {
          let Supplements = [];
          let contract_name = [];
          let Offers = [];
          let room_name  = [];
          let booking_count = 1;
          let obj_agency_currency = this.currency_list.find(x => x.currency_code == bkg.currency);
          let agency_decimal_definer = obj_agency_currency ? obj_agency_currency.currency_deci_definer : '2';
          let obj_supplier_currency = this.currency_list.find(x => x.currency_code == bkg.room_rate_list[0].supplier_currency);
          let supplier_decimal_definer = obj_supplier_currency ? obj_supplier_currency.currency_deci_definer : '2';

          bkg.room_rate_list.map(room_rate_det=>{
            room_rate_det['Date']=[];
            room_rate_det['Price']=[];
            room_rate_det['Allocation']=[];
            room_rate_det['Booked']=[];
            room_rate_det['Available_after_booking']=[];
            room_rate_det['total'] = 0;
            let nightly_rate = room_rate_det.nightly_rate ? JSON.parse(room_rate_det.nightly_rate) : undefined;
            if(room_rate_det.contract_name){
              contract_name.push(room_rate_det.contract_name);
            }
            let Supplement_obj = room_rate_det.supplements ? JSON.parse(room_rate_det.supplements) : undefined;
            if(Supplement_obj){
              Supplement_obj[0].forEach(supp_data=>{
                Supplements.push(supp_data.Description);
              })
            }
            let Offer_Obj = room_rate_det.offers ? JSON.parse(room_rate_det.offers) : undefined;
            if(Offer_Obj?.length > 0){
              Offer_Obj.forEach(e=>{
                Offers.push(e.offer_name);
              })
            }
            if(nightly_rate){
              room_name.push(room_rate_det.room_name);
              if(room_name.includes(room_rate_det.room_name)){
                let filter_data = room_name.filter(e=>e == room_rate_det.room_name);
                booking_count = filter_data.length;
              }
              nightly_rate.forEach(night_rate=>{
                let booked = bkg.room_list?.[0].room_booking_status == '3' ? (parseInt(night_rate.booked ) + booking_count) : night_rate.booked;
                let price_obj = night_rate.PriceDetails.find(e=>e.PriceDetailType == 'BasePrice')
                room_rate_det.Date.push(night_rate.date);
                room_rate_det.Allocation.push(night_rate.allocation);
                room_rate_det.Booked.push(booked);
                room_rate_det.Price.push(price_obj.PriceInSourceCurrency);
                room_rate_det.Available_after_booking.push(night_rate.allocation != 'FREESALE' ? (night_rate.allocation - booked) : night_rate.allocation);
                room_rate_det.total += price_obj.PriceInSourceCurrency;
              });
              room_rate_det.total = this.commonserv.amountDefiner(room_rate_det.total,supplier_decimal_definer)
            }
          })
          let room_details_arr = [];
          bkg.room_list.forEach((room_det,i)=>{
            room_det['hotel_confirmation_number'] = room_det.hotel_confirmation_number;
            room_det['booking_id'] = bkg.booking_id;
            room_det['lead_guest'] = this.booking_customer_data.lead_guest;
            room_det['hotel_confirmation_number_date'] = bkg.hotel_confirmation_number_date;
            room_det['hotel_confirmation_staff_name'] = bkg.hotel_confirmation_staff_name;
            room_det['hotel_confirmation_staff_remarks'] = bkg.hotel_confirmation_staff_remarks;
            room_det['supplier_confirmation_number'] = bkg.supplier_confirmation_number;
            room_det['Room_Allocation_Data'] = bkg.room_rate_list[i];
            room_details_arr.push(room_det);
          })
          Offers = [...new Set(Offers)]; 
          let obj_booking = {
            booking_id: bkg.booking_id,
            invoice_no: bkg.vendor_invoice_number,
            agency_currency: bkg.currency,
            supplier_currency: bkg.room_rate_list[0].supplier_currency,
            supplier_name: bkg.supplier_name,
            supplier_amount: this.commonserv.amountDefiner(bkg.supplier_total_amount, supplier_decimal_definer),
            total_amount: this.commonserv.amountDefiner(bkg.agent_total_amount, agency_decimal_definer),
            rate_list_total_amount: this.commonserv.amountDefiner(bkg.agent_total_amount_without_buffer, agency_decimal_definer),
            invoice_number: bkg.invoice_number,
            Supplement: Supplements.join(', '),
            Contract: contract_name.join(', '),
            Offer: Offers.join(', '),
            adjustment: this.commonserv.amountDefiner(bkg.buffer, agency_decimal_definer),
            commercial_plan: bkg.commercial_plan,
            adt: bkg.adt,
            chd: bkg.chd,
            promo_name: bkg.promo_code,
            redeemed_points: bkg.redeemed_points,
            loyalty_point_discount: bkg.loyalty_point_discount,
            promo_amt: this.commonserv.amountDefiner(bkg.promo_total_discount, agency_decimal_definer),
            hold_amount: this.commonserv.amountDefiner(bkg.hold_amount, agency_decimal_definer),
            room_details_list:room_details_arr
          }
          booking_list.push(obj_booking);
        });
        let obj_agency_currency = this.currency_list.find(x => x.currency_code == data[0].currency);
        let agency_decimal_definer = obj_agency_currency ? obj_agency_currency.currency_deci_definer : '2';
        let obj_costing_tab = {
          trip_id: data[0].trip_id,
          coupon_code: "",
          coupon_discount: this.commonserv.amountDefiner(0, agency_decimal_definer),
          currency: data[0].currency,
          payment_gateway: data[0].payment_gateway_name,
          pg_fee: this.commonserv.amountDefiner(data[0].pg_fee, agency_decimal_definer),
          thirdparty_invoice_number: data[0].thirdparty_invoice_number,
          thirdparty_invoice_status: data[0].thirdparty_invoice_status,
          thirdparty_reference_number: data[0].thirdparty_reference_number,
          booking_list: booking_list,
        }
        this.costing_tab_data = obj_costing_tab;
        this.tab_data_status.costing = this.costing_tab_data ? "success" : "failed";
        console.log(this.costing_tab_data);
      } else {
        this.tab_data_status.costing = "failed";
      }
    }, (error) => {
      this.tab_data_status.costing = "failed";
    });
  }
  getPaymentTabDetails() {
    this.tab_data_status.payment = "loading";
    this.payment_tab_data = null;
    this.APIServ.getPaymentDetails(this.trip_id).subscribe((data: any) => {
      if (data) {
        this.payment_tab_data = data;
        if (this.payment_tab_data) {
          let obj_agency_currency = this.currency_list.find(x => x.currency_code == this.payment_tab_data.booking_list[0].invoice_currency);
          this.agency_decimal_definer = obj_agency_currency ? obj_agency_currency.currency_deci_definer : '2';

          this.payment_tab_data.total_amount = this.commonserv.amountDefiner(this.payment_tab_data.total_amount, this.agency_decimal_definer);
          this.payment_tab_data.total_paid_amount = this.commonserv.amountDefiner(this.payment_tab_data.total_paid_amount, this.agency_decimal_definer);
          this.payment_tab_data.total_pending_amount = this.commonserv.amountDefiner(this.payment_tab_data.total_pending_amount, this.agency_decimal_definer);
          
          this.updateAccountingPayForm.get('currency').setValue(this.payment_tab_data.booking_list[0].invoice_currency);
          this.updateAccountingPayForm.get('booking_id').setValue(this.payment_tab_data.booking_list[0].booking_id);
          this.updateAccountingPayForm.get('pending_amt').setValue(this.payment_tab_data.total_pending_amount);

          if (this.payment_tab_data.booking_list) {
            this.payment_tab_data.booking_list.map(x => {
              x.invoice_number = x.invoice_number != null && x.invoice_number != '' ? x.invoice_number : 'Pending';
              x.payment_gateway_name = x.payment_gateway_name != null && x.payment_gateway_name != '' ? x.payment_gateway_name : 'NA';
              x.transaction_number = x.transaction_number != null && x.transaction_number != '' ? x.transaction_number : 'NA';
              x.invoice_date_and_time = x.invoice_date_and_time != null ? this.commonserv.UtcToLocaleTime(x.invoice_date_and_time, 'DD MMM YYYY, HH:mm:ss') : 'NA';
              x.invoice_due_date = x.invoice_due_date != null ? this.commonserv.UtcToLocaleTime(x.invoice_due_date, 'DD MMM YYYY, HH:mm:ss') : 'NA';
              x.invoice_paid_amount = this.commonserv.amountDefiner(x.invoice_paid_amount, this.agency_decimal_definer);
              x.amount = this.commonserv.amountDefiner(x.amount, this.agency_decimal_definer);
            });
          }
        }
        this.tab_data_status.payment = "success";
      } else {
        this.tab_data_status.payment = "failed";
      }
    }, (error) => {
      this.tab_data_status.payment = "failed";
    });
  }
  getDocumentTabDetails() {
    this.tab_data_status.document = "loading";
    this.document_tab_data = null;
    this.APIServ.getDocumentDetails(this.trip_id).subscribe((data: any) => {
      if (data) {
        this.document_tab_data = data.filter(x => x.document_number != null && x.document_number != '');
        this.document_tab_data.map(li => {
          li.issue_date = this.commonserv.UtcToLocaleTime(li.issue_date, 'DD MMM YYYY, HH:mm:ss')
        })
        this.tab_data_status.document = this.document_tab_data ? "success" : "failed";
      } else {
        this.tab_data_status.document = "failed";
      }
    }, (error) => {
      this.tab_data_status.document = "failed";
    });
  }
  getBookingNoteDetails() {
    this.note_tab_data = null;
    this.APIServ.getNotesDetail(this.trip_id).subscribe((data) => {
      if (data) {
        this.note_tab_data = data;
        this.note_tab_data.map(li => {
          li.noted_on = this.commonserv.UtcToLocaleTime(li.noted_on, 'DD MMM YYYY, HH:mm:ss')
        })
      }
    }, (error) => {
    });
  }
  
  getHBookingDetails() {
    this.APIServ.getHotelBookingDetail(this.itinerary_tab_data[0].booking_id).subscribe((data) => {
      if (!data || !Array.isArray(data) || data.length < 2) {
        console.error('Invalid data format:', data);
        return;
      }
      let SuppData = data.filter(li => li.type == 'Supplier')[0]
      let AgencyData = data.filter(li => li.type == 'Agency')[0]
      const extractRoomData = (roomData) => {
        return roomData.rooms.reduce((acc, room) => {
          acc.room_names.push(room.roomName);
          acc.board_types.push(room.boardType);
          acc.guests.push(room.guests);
          acc.lead_guest.push(room.leadGuest);
          return acc;
        }, {
          room_names: [],
          board_types: [],
          guests: [],
          lead_guest: []
        });
      };
  
      const verificationTabData = extractRoomData(SuppData);
      const verificationTabDataMid = extractRoomData(AgencyData);
      this.verification_tab_data = {
        ...SuppData,
        ...verificationTabData
      };
  
      this.veri_tab_data_mid = {
        ...AgencyData,
        ...verificationTabDataMid
      };
      
      const setCancellationCharge = (data) => {
        switch (data.cancelType) {
          case 'Night':
            data.SupCanclCharge = `${data.cancellationCharge} Night`;
            data.AgencyCanclCharge = `${data.agentCancellationCharge} Night`;
            break;
          case 'Percentage':
            data.SupCanclCharge = `${data.cancellationCharge} %`;
            data.AgencyCanclCharge = `${data.agentCancellationCharge} %`;
            break;
          case 'Flat':
            data.SupCanclCharge = `${data.currency} ${data.cancellationCharge}`;
            data.AgencyCanclCharge = `${data.agencyCurrency} ${data.agentCancellationCharge}`;
            break;
          default:
            break;
        }
      };

      setCancellationCharge(this.veri_tab_data_mid);
      setCancellationCharge(this.verification_tab_data);
      if (this.AllCurrency && this.AllCurrency.length > 0 && this.veri_tab_data_mid.currency) {
        let obj_currency = this.AllCurrency.find(x => x.currency_code == this.veri_tab_data_mid.currency);
        let agnecy_currency = this.AllCurrency.find(x => x.currency_code == this.veri_tab_data_mid.agencyCurrency);

        let amount_format = obj_currency ? obj_currency.amount_format : "";
        let decimal_seperator = obj_currency ? obj_currency.decimal_seperator : "";
        let agnecy_amount_format = obj_currency ? agnecy_currency.amount_format : "";
        let agnecy_decimal_seperator = obj_currency ? agnecy_currency.decimal_seperator : "";
        this.veri_tab_data_mid.supplierAmount = this.commonserv.amountFormater(this.veri_tab_data_mid.supplierAmount, agnecy_amount_format, agnecy_decimal_seperator)
        this.veri_tab_data_mid.bookingAmount = this.commonserv.amountFormater(this.veri_tab_data_mid.bookingAmount, agnecy_amount_format, agnecy_decimal_seperator)
        this.verification_tab_data.supplierAmount = this.commonserv.amountFormater(this.verification_tab_data.supplierAmount, amount_format, decimal_seperator)
        this.verification_tab_data.bookingAmount = this.commonserv.amountFormater(this.verification_tab_data.bookingAmount, amount_format, decimal_seperator)

      }
      this.veri_tab_data_mid.isBoardH = JSON.stringify(verificationTabData.board_types) != JSON.stringify(verificationTabDataMid.board_types);
      this.veri_tab_data_mid.isRoomH = JSON.stringify(verificationTabData.room_names) != JSON.stringify(verificationTabDataMid.room_names);
      this.veri_tab_data_mid.isGuestH = JSON.stringify(verificationTabData.guests) != JSON.stringify(verificationTabDataMid.guests);
      this.veri_tab_data_mid.isLeadGH = JSON.stringify(verificationTabData.lead_guest) != JSON.stringify(verificationTabDataMid.lead_guest);
      this.veri_tab_data_mid.isSupCanc = new Date(this.verification_tab_data.cancellationDeadline?.hotelCancellationDeadline)?.getTime() < new Date(this.veri_tab_data_mid.cancellationDeadline?.hotelCancellationDeadline)?.getTime();
      this.veri_tab_data_mid.isAgenCanc = new Date(this.verification_tab_data.cancellationDeadline?.utcCancellationDeadline)?.getTime() < new Date(this.veri_tab_data_mid.cancellationDeadline?.utcCancellationDeadline)?.getTime();
      this.veri_tab_data_mid.isInDateH = moment(this.verification_tab_data.checkInDate).format('dd MMM YYYY') != moment(this.veri_tab_data_mid.checkInDate).format('dd MMM YYYY');
      this.veri_tab_data_mid.isOutDateH = moment(this.verification_tab_data.checkOutDate).format('dd MMM YYYY') != moment(this.veri_tab_data_mid.checkOutDate).format('dd MMM YYYY');
    }, (error) => {
      console.error('Error fetching hotel booking details:', error);
    });
  } 

  getCurrencyList(){
   return  this.ApiServ.AdminGet("/CurrencyMaster/GetAllCurrencies")
  }

  initConfirmationForm(itinerary_data) {
    let obj = {
      booking_id: itinerary_data != null && itinerary_data.booking_id != null && itinerary_data.booking_id != '' ? itinerary_data.booking_id : "",
      // hotel_confirmation_number: itinerary_data != null && itinerary_data.hotel_confirmation_number != null && itinerary_data.hotel_confirmation_number != '' ? itinerary_data.hotel_confirmation_number.split(',') : [],
      hotel_confirmation_number_date: itinerary_data != null && itinerary_data.hotel_confirmation_number_date != null && itinerary_data.hotel_confirmation_number_date != '' ? new Date(itinerary_data.hotel_confirmation_number_date) : new Date(),
      hotel_confirmation_staff_name: itinerary_data != null && itinerary_data.hotel_confirmation_staff_name != null && itinerary_data.hotel_confirmation_staff_name != '' ? itinerary_data.hotel_confirmation_staff_name : "",
      hotel_confirmation_staff_remarks: itinerary_data != null && itinerary_data.hotel_confirmation_staff_remarks != null && itinerary_data.hotel_confirmation_staff_remarks != '' ? itinerary_data.hotel_confirmation_staff_remarks : "",
      supplier_confirmation_number: itinerary_data != null && itinerary_data.supplier_confirmation_number != null && itinerary_data.supplier_confirmation_number != '' ? itinerary_data.supplier_confirmation_number : ""
    }
    this.confirmationForm = this.fb.group({
      booking_id: [obj.booking_id],
      // hotel_confirmation_number: [obj.hotel_confirmation_number],
      hotel_confirmation_number:this.fb.array([]),
      supplier_confirmation_number:[obj.supplier_confirmation_number],
      hotel_confirmation_number_date: [obj.hotel_confirmation_number_date],
      hotel_confirmation_staff_name: [obj.hotel_confirmation_staff_name],
      hotel_confirmation_staff_remarks: [obj.hotel_confirmation_staff_remarks],
    });
    let formarray = this.confirmationForm.controls['hotel_confirmation_number'] as FormArray;
    if(itinerary_data?.room_list?.length > 0){
      itinerary_data.room_list.forEach(data=>{
        formarray.push(
          this.fb.group({
            room_name:data.room_name,
            room_id:data.hotel_room_id,
            confirmation_no:data.hotel_confirmation_number,
          })
        )
      })
    }else if(itinerary_data){
      formarray.push(
        this.fb.group({
          room_name:itinerary_data.room_name,
          room_id:itinerary_data.hotel_room_id,
          confirmation_no:itinerary_data.hotel_confirmation_number,
        })
      )
    }
  }

  // open(content: any) {
  //   this.modalReference = this.modalService
  //     .open(content, { ariaLabelledBy: "" })
  //     .result.then(
  //       (result) => {
  //         this.closeResult = `Closed with: ${result}`;
  //       },
  //       (reason) => {
  //         this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
  //       }
  //     );
  // }
  openConfirmationNumberModal(content: any, itinerary_data) {
    this.initConfirmationForm(itinerary_data);
    this.isOpenAddConfirmationNumberModal = true;
  }
  openVendorInvoiceNumberModal(id,invoice) {
    this.isOpenAddVendorInvoiceNumberModal = true;
    this.VendorInvoiceForm = this.fb.group({
      booking_id:id,
      vendor_invoice_number:[invoice,Validators.compose([Validators.required])]
    })
  }
  saveConfirmationNumber() {
    let obj = this.confirmationForm.value;
    let postdata = {
      booking_id:obj.booking_id,
      supplier_confirmation_number:obj.supplier_confirmation_number,
      hotel_confirmation_number_date:obj.hotel_confirmation_number_date,
      hotel_confirmation_staff_name:obj.hotel_confirmation_staff_name,
      hotel_confirmation_staff_remarks:obj.hotel_confirmation_staff_remarks,
      hotel_rooms:[]
    }
    let hotel_confirm_number = [];
    obj.hotel_confirmation_number.forEach(data=>{
      hotel_confirm_number.push(
        {
          hotel_room_id:data.room_id,
          hotel_confirmation_number:data.confirmation_no
        }
      );
    })
    postdata.hotel_rooms = hotel_confirm_number;
    this.APIServ.saveConfirmationNumber(postdata).subscribe((data) => {
      if(data?.resp){
        this.isOpenAddConfirmationNumberModal = false;
        if(this.active_tab == 2){
          this.getCostingTabDetails();
        }else {
          this.getItineraryTabDetails();
        }
      }
    });
  }
  saveNotes() {
    if (this.notesform.status == 'INVALID') {
      this.validationServ.showValidationsMsg(this.notesform);
      return;
    }
    let obj = {
      booking_refrence_number: this.trip_id,
      booking_notes_free_text: this.notesform.get('Note').value,
    };
    this.APIServ.saveNotesDetail(obj).subscribe((data) => {
      if (data) {
        this.getBookingNoteDetails();
        this.commonserv.showMessage(data["resp"], data["respMsg"]);
        // this.modalService.dismissAll();
      } else {
        this.commonserv.showMessage(data["resp"], data["respMsg"]);
      }
      this.isOpenAddNote = false;
    });
  }

  getPriceDetailType(breakupDetails, priceType) {
    try {
      let price = breakupDetails.PriceDetails.filter(
        (el) => el.PriceDetailType == priceType
      )[0].Price;
      return price;
    } catch {
      return 0;
    }
  }


  map_booking_status(booking_status, payment_status) {
    if (booking_status != null) {
      if (booking_status == 3) {
        return 'Confirmed';
      }
      else if (booking_status == 4) {
        return 'Cancelled';
      }
      else if ((booking_status == 0 || booking_status == 2) && payment_status != null) {
        return 'Pending';
      }
      else if (booking_status == 6) {
        return 'Reserved';
      }
      else {
        return 'In Progress';
      }
    } else {
      return 'In Progress';
    }
  }
  map_room_status(status) {
    if (status != null) {
      switch (status) {
        case '0': {
          return 'In Progress';
        }
        case '2': {
          return 'Failed';
        }
        case '3': {
          return 'Confirmed';
        }
        case '4': {
          return 'Cancelled';
        }
        case '6': {
          return 'Reserved';
        }
        default: {
          return 'In Progress';
        }
      }
    } else {
      return 'In Progress';
    }
  }
  map_payment_status(status, is_authorised) {
    if (status != null && status != "") {
      switch (status) {
        case "PAID": {
          return is_authorised ? 'Paid (Authorized)' : 'Paid';
        }
        case "PENDING": {
          return 'Pending';
        }
        case "FAILED": {
          return 'Failed';
        }
        case "PARTLYPAID": {
          return 'Partly Paid';
        }
        default :{
          return 'Not Attempt';
        }
      }
    } else {
      return 'Not Attempt';
    }
  }

  //
  //
  //
  displayModal: boolean;

  displayBasic: boolean;

  displayBasic2: boolean;

  bookingIdIndex = 0;

  displayMaximizable: boolean;

  displayPosition: boolean;

  position: string;

  isOpenSendEmailModal: boolean = false;
  isOpenAddBookingCancelModal: boolean = false;
  selectedItinerary = [];
  showModalDialog() {
    this.displayModal = true;
  }
  bookingHistoryModal() {
    this.bookingHistory = true;
  }
  bookingIdModal() {
    this.bookingDetails = true;
  }
  ReleaseModalBtn(ind) {
    this.ReleaseModal = true;
    this.bookingIdIndex = ind;
  }
  closeModalBtn() {
    this.ReleaseModal = false;
  }
  closeAccountPayStatusBtn() {
    this.UpdAccountPayStatus = false;
  }
  closeUpdateAccountingInvoice() {
    this.UpdateInStatus = false;
}
  UpdateAccountingInvoice() {
    this.UpdateInStatus = true;
  }
  UpdAccountPayStatusBtn() {
    this.UpdAccountPayStatus = true;
  }
  rateBreakupModal(obj_booking) {
    let obj = [];
    if (obj_booking.room_rate_list != null) {
      obj_booking.room_rate_list.map(room => {
        obj.push({
          room_name: room.room_name,
          nightly_rate: room.nightly_rate != null ? this.mapNightlyRate(JSON.parse(room.nightly_rate)) : null
        });
      });
    }
    this.supplierNightlyRate = obj;
    console.log(this.supplierNightlyRate);
    this.rateBreakup = true;
  }
  mapNightlyRate(nightly_rate) {
    let obj = [];
    nightly_rate.map(rate => {
      let obj_base_price = rate.PriceDetails.find(x => x.PriceDetailType == 'BasePrice');
      let obj_agency_currency = this.currency_list.find(x => x.currency_code == obj_base_price.Currency);
      let agency_decimal_definer = obj_agency_currency ? obj_agency_currency.currency_deci_definer : '2';

      let obj_supplier_currency = this.currency_list.find(x => x.currency_code == obj_base_price.SourceCurrency);
      let supplier_decimal_definer = obj_supplier_currency ? obj_supplier_currency.currency_deci_definer : '2';
      obj.push({
        date: rate.date,
        supplier_currency: obj_base_price.SourceCurrency,
        supplier_amount: this.commonserv.amountDefiner(obj_base_price.PriceInSourceCurrency, supplier_decimal_definer),
        roe: this.commonserv.amountDefiner(obj_base_price.ExchangeRate, agency_decimal_definer),
        agency_currency: obj_base_price.Currency,
        base_price: this.commonserv.amountDefiner(this.getPriceDetailType(rate, "BasePrice"), agency_decimal_definer),
        markup_surcharge_amount: this.commonserv.amountDefiner(this.getPriceDetailType(rate, "Surcharge"), agency_decimal_definer),
        // discount_surcharge_amount: this.commonserv.amountDefiner(rate.discount_surcharge_amount, agency_decimal_definer),
        markup_amount: this.commonserv.amountDefiner(((this.getPriceDetailType(rate, "Markup") * 10000000) + (this.getPriceDetailType(rate, "AdditionalMarkUpPrice") * 10000000)) / 10000000, agency_decimal_definer),
        transaction_fee: this.commonserv.amountDefiner(this.getPriceDetailType(rate, "TransactionFee"), agency_decimal_definer),
        discount: this.commonserv.amountDefiner(this.getPriceDetailType(rate, "Discount"), agency_decimal_definer),
        input_tax: this.commonserv.amountDefiner(this.getPriceDetailType(rate, "InputTax"), agency_decimal_definer),
        output_tax: this.commonserv.amountDefiner(this.getPriceDetailType(rate, "OutputTax"), agency_decimal_definer),
        total: this.commonserv.amountDefiner(rate.net, agency_decimal_definer),
      });
    });
    return obj;
  }
  showBasicDialog() {
    this.displayBasic = true;
  }

  showBasicDialog2() {
    this.displayBasic2 = true;
  }

  showMaximizableDialog() {
    this.displayMaximizable = true;
  }

  showPositionDialog(position: string) {
    this.position = position;
    this.displayPosition = true;
  }
  back_to_listing() {
    this.router.navigate(['/BookingManagement/HotelBooking/Search']);
  }
 // add required validtion 
  //  updated by Abdul Razzak on 13 mar 2024
  //updated by Arfat Qureshi on 18 mar 2024, added language and whatsapp property in send mail pop up
  openSendEmailModal(document_number, document_type) {
    this.mailForm = this.fb.group({
      document_number: [document_number],
      document_type: [document_type],
      email_id: this.validationServ.email,
      languageId: document_type == 'Itinerary' ? this.validationServ.required : '',
      is_wapp : false
    });
    //set the default email Id of user in the send mail field
    if(this.booking_customer_data){
      this.mailForm.get('email_id').setValue(this.booking_customer_data['guest_email_address']);
    }
    this.selected__mail_document_type =  document_type;
    this.isOpenSendEmailModal = true;
  }
  openSendAddNote() {
    this.isOpenAddNote = true;
    this.notesform.reset();
    this.notesform.markAsUntouched();
  }
  OpenCancellationPolicyModal(itinerary, isOpen) {
    try {
      console.log(itinerary);
      let cancellation_policy = itinerary.cancellation_policy;
      //let cancellation_policy = [{ "from_type": "supplier", "room_name": "Double room ? Disability access", "cancellation_policy_text": null, "sequence_no": 2, "deadline_date_from": "2022-09-21", "deadline_time_from": "00:00:00", "deadline_date_to": "2022-09-25", "deadline_time_to": "00:00:00", "currency": "USD", "amount": 100, "is_roomwise_policy": true, "format_type": "Flat", "hotel_room_details_id": "2208231504398246022", "no_of_rooms": 1 }, { "from_type": "supplier", "room_name": "DOUBLE STANDARD", "cancellation_policy_text": null, "sequence_no": 2, "deadline_date_from": "2022-09-21", "deadline_time_from": "00:00:00", "deadline_date_to": "2022-09-25", "deadline_time_to": "00:00:00", "currency": "USD", "amount": 100, "is_roomwise_policy": true, "format_type": "Flat", "hotel_room_details_id": "2208231504398247445", "no_of_rooms": 1 }, { "from_type": "agent", "room_name": "DOUBLE STANDARD", "cancellation_policy_text": null, "sequence_no": 2, "deadline_date_from": "2022-09-21", "deadline_time_from": "00:00:00", "deadline_date_to": "2022-09-25", "deadline_time_to": "00:00:00", "currency": "USD", "amount": 100, "is_roomwise_policy": true, "format_type": "Flat", "hotel_room_details_id": "2208231504398247445", "no_of_rooms": 1 }, { "from_type": "supplier", "room_name": "DOUBLE STANDARD", "cancellation_policy_text": null, "sequence_no": 2, "deadline_date_from": "2022-09-21", "deadline_time_from": "00:00:00", "deadline_date_to": "2022-09-25", "deadline_time_to": "00:00:00", "currency": "USD", "amount": 100, "is_roomwise_policy": true, "format_type": "Flat", "hotel_room_details_id": "2208231504398248361", "no_of_rooms": 1 }, { "from_type": "agent", "room_name": "Double room ? Disability access", "cancellation_policy_text": null, "sequence_no": 2, "deadline_date_from": "2022-09-21", "deadline_time_from": "00:00:00", "deadline_date_to": "2022-09-25", "deadline_time_to": "00:00:00", "currency": "USD", "amount": 100, "is_roomwise_policy": true, "format_type": "Flat", "hotel_room_details_id": "2208231504398246022", "no_of_rooms": 1 }, { "from_type": "supplier", "room_name": "Double room ? Disability access", "cancellation_policy_text": null, "sequence_no": 1, "deadline_date_from": "2022-08-22", "deadline_time_from": "00:00:00", "deadline_date_to": "2022-09-21", "deadline_time_to": "00:00:00", "currency": "USD", "amount": 0, "is_roomwise_policy": true, "format_type": "Flat", "hotel_room_details_id": "2208231504398246022", "no_of_rooms": 1 }, { "from_type": "agent", "room_name": "DOUBLE STANDARD", "cancellation_policy_text": null, "sequence_no": 2, "deadline_date_from": "2022-09-21", "deadline_time_from": "00:00:00", "deadline_date_to": "2022-09-25", "deadline_time_to": "00:00:00", "currency": "USD", "amount": 100, "is_roomwise_policy": true, "format_type": "Flat", "hotel_room_details_id": "2208231504398248361", "no_of_rooms": 1 }, { "from_type": "agent", "room_name": "DOUBLE STANDARD", "cancellation_policy_text": null, "sequence_no": 1, "deadline_date_from": "2022-08-22", "deadline_time_from": "00:00:00", "deadline_date_to": "2022-09-21", "deadline_time_to": "00:00:00", "currency": "USD", "amount": 0, "is_roomwise_policy": true, "format_type": "Flat", "hotel_room_details_id": "2208231504398248361", "no_of_rooms": 1 }, { "from_type": "agent", "room_name": "Double room ? Disability access", "cancellation_policy_text": null, "sequence_no": 1, "deadline_date_from": "2022-08-22", "deadline_time_from": "00:00:00", "deadline_date_to": "2022-09-21", "deadline_time_to": "00:00:00", "currency": "USD", "amount": 0, "is_roomwise_policy": true, "format_type": "Flat", "hotel_room_details_id": "2208231504398246022", "no_of_rooms": 1 }, { "from_type": "supplier", "room_name": "DOUBLE STANDARD", "cancellation_policy_text": null, "sequence_no": 1, "deadline_date_from": "2022-08-22", "deadline_time_from": "00:00:00", "deadline_date_to": "2022-09-21", "deadline_time_to": "00:00:00", "currency": "USD", "amount": 0, "is_roomwise_policy": true, "format_type": "Flat", "hotel_room_details_id": "2208231504398248361", "no_of_rooms": 1 }, { "from_type": "supplier", "room_name": "DOUBLE STANDARD", "cancellation_policy_text": null, "sequence_no": 1, "deadline_date_from": "2022-08-22", "deadline_time_from": "00:00:00", "deadline_date_to": "2022-09-21", "deadline_time_to": "00:00:00", "currency": "USD", "amount": 0, "is_roomwise_policy": true, "format_type": "Flat", "hotel_room_details_id": "2208231504398247445", "no_of_rooms": 1 }, { "from_type": "agent", "room_name": "DOUBLE STANDARD", "cancellation_policy_text": null, "sequence_no": 1, "deadline_date_from": "2022-08-22", "deadline_time_from": "00:00:00", "deadline_date_to": "2022-09-21", "deadline_time_to": "00:00:00", "currency": "USD", "amount": 0, "is_roomwise_policy": true, "format_type": "Flat", "hotel_room_details_id": "2208231504398247445", "no_of_rooms": 1 }];
      //let cancellation_policy = [{"from_type":"supplier","room_name":"Standard Double Room,1 King Bed","cancellation_policy_text":null,"sequence_no":1,"deadline_date_from":"2022-08-22","deadline_time_from":null,"deadline_date_to":"2022-08-29","deadline_time_to":null,"currency":"USD","amount":0,"is_roomwise_policy":false,"format_type":"Percentage","hotel_room_details_id":"2208231413218409642","no_of_rooms":1},{"from_type":"supplier","room_name":"Standard Double Room,1 King Bed","cancellation_policy_text":null,"sequence_no":1,"deadline_date_from":"2022-08-22","deadline_time_from":null,"deadline_date_to":"2022-08-29","deadline_time_to":null,"currency":"USD","amount":0,"is_roomwise_policy":false,"format_type":"Percentage","hotel_room_details_id":"2208231413218410665","no_of_rooms":1},{"from_type":"agent","room_name":"Standard Double Room,1 King Bed","cancellation_policy_text":null,"sequence_no":2,"deadline_date_from":"2022-08-29","deadline_time_from":null,"deadline_date_to":"2022-09-13","deadline_time_to":null,"currency":"USD","amount":100,"is_roomwise_policy":false,"format_type":"Percentage","hotel_room_details_id":"2208231413218409642","no_of_rooms":1},{"from_type":"supplier","room_name":"Standard Double Room,1 King Bed","cancellation_policy_text":null,"sequence_no":2,"deadline_date_from":"2022-08-29","deadline_time_from":null,"deadline_date_to":"2022-09-13","deadline_time_to":null,"currency":"USD","amount":100,"is_roomwise_policy":false,"format_type":"Percentage","hotel_room_details_id":"2208231413218409642","no_of_rooms":1},{"from_type":"supplier","room_name":"Standard Double Room,1 King Bed","cancellation_policy_text":null,"sequence_no":2,"deadline_date_from":"2022-08-29","deadline_time_from":null,"deadline_date_to":"2022-09-13","deadline_time_to":null,"currency":"USD","amount":100,"is_roomwise_policy":false,"format_type":"Percentage","hotel_room_details_id":"2208231413218408033","no_of_rooms":1},{"from_type":"agent","room_name":"Standard Double Room,1 King Bed","cancellation_policy_text":null,"sequence_no":1,"deadline_date_from":"2022-08-22","deadline_time_from":null,"deadline_date_to":"2022-08-29","deadline_time_to":null,"currency":"USD","amount":0,"is_roomwise_policy":false,"format_type":"Percentage","hotel_room_details_id":"2208231413218410665","no_of_rooms":1},{"from_type":"agent","room_name":"Standard Double Room,1 King Bed","cancellation_policy_text":null,"sequence_no":1,"deadline_date_from":"2022-08-22","deadline_time_from":null,"deadline_date_to":"2022-08-29","deadline_time_to":null,"currency":"USD","amount":0,"is_roomwise_policy":false,"format_type":"Percentage","hotel_room_details_id":"2208231413218409642","no_of_rooms":1},{"from_type":"agent","room_name":"Standard Double Room,1 King Bed","cancellation_policy_text":null,"sequence_no":2,"deadline_date_from":"2022-08-29","deadline_time_from":null,"deadline_date_to":"2022-09-13","deadline_time_to":null,"currency":"USD","amount":100,"is_roomwise_policy":false,"format_type":"Percentage","hotel_room_details_id":"2208231413218408033","no_of_rooms":1},{"from_type":"agent","room_name":"Standard Double Room,1 King Bed","cancellation_policy_text":null,"sequence_no":1,"deadline_date_from":"2022-08-22","deadline_time_from":null,"deadline_date_to":"2022-08-29","deadline_time_to":null,"currency":"USD","amount":0,"is_roomwise_policy":false,"format_type":"Percentage","hotel_room_details_id":"2208231413218408033","no_of_rooms":1},{"from_type":"supplier","room_name":"Standard Double Room,1 King Bed","cancellation_policy_text":null,"sequence_no":1,"deadline_date_from":"2022-08-22","deadline_time_from":null,"deadline_date_to":"2022-08-29","deadline_time_to":null,"currency":"USD","amount":0,"is_roomwise_policy":false,"format_type":"Percentage","hotel_room_details_id":"2208231413218408033","no_of_rooms":1},{"from_type":"supplier","room_name":"Standard Double Room,1 King Bed","cancellation_policy_text":null,"sequence_no":2,"deadline_date_from":"2022-08-29","deadline_time_from":null,"deadline_date_to":"2022-09-13","deadline_time_to":null,"currency":"USD","amount":100,"is_roomwise_policy":false,"format_type":"Percentage","hotel_room_details_id":"2208231413218410665","no_of_rooms":1},{"from_type":"agent","room_name":"Standard Double Room,1 King Bed","cancellation_policy_text":null,"sequence_no":2,"deadline_date_from":"2022-08-29","deadline_time_from":null,"deadline_date_to":"2022-09-13","deadline_time_to":null,"currency":"USD","amount":100,"is_roomwise_policy":false,"format_type":"Percentage","hotel_room_details_id":"2208231413218410665","no_of_rooms":1}];
      console.log(cancellation_policy);
      let room_list = [];
      if (cancellation_policy) {
        if (cancellation_policy.some(x => x.is_roomwise_policy)) {
          this.is_roomwise_policy = true;
          let room_group_list = _.groupBy(cancellation_policy, function (d) { return d.hotel_room_details_id; });
          for (let item in room_group_list) {
            let selected_room = room_group_list[item];

            let agent_cancellation_policy = selected_room.filter(x => x.from_type == 'agent').sort(function (a, b) { return a.sequence_no - b.sequence_no });
            let supplier_cancellation_policy = selected_room.filter(x => x.from_type == 'supplier').sort(function (a, b) { return a.sequence_no - b.sequence_no });

            for (let index = 0; index < selected_room[0].no_of_rooms; index++) {
              room_list.push({
                room_name: selected_room[0].room_name,
                timezone: cancellation_policy[0].timezone,
                agent_cancellation_policy: this.mapCancellationPolicy(agent_cancellation_policy),
                supplier_cancellation_policy: this.mapCancellationPolicy(supplier_cancellation_policy)
              });
            }
          }
        } else {
          this.is_roomwise_policy = false;
          let room_group_list = _.groupBy(cancellation_policy, function (d) { return d.hotel_room_details_id; });
          for (let item in room_group_list) {
            let selected_room = room_group_list[item];
            let agent_cancellation_policy = selected_room.filter(x => x.from_type == 'agent').sort(function (a, b) { return a.sequence_no - b.sequence_no });
            let supplier_cancellation_policy = selected_room.filter(x => x.from_type == 'supplier').sort(function (a, b) { return a.sequence_no - b.sequence_no });
            room_list.push({
              room_name: cancellation_policy[0].room_name,
              timezone: cancellation_policy[0].timezone,
              agent_cancellation_policy: this.mapCancellationPolicy(agent_cancellation_policy),
              supplier_cancellation_policy: this.mapCancellationPolicy(supplier_cancellation_policy)
            });
            break;
          }
        }
      }
      this.selectedItinerary = room_list;
    } catch {
      this.selectedItinerary = [];
    }
    isOpen ? this.isOpenCancellationPolicyModal = true : '';
  }
  mapCancellationPolicy(cancellation_policy) {
    let resp = [];
    cancellation_policy.map(item => {
      if (item.format_type == 'Percentage' || item.format_type == 'Flat' || item.format_type == 'Night' || item.format_type == 'Nights') {
        let obj_currency = item.format_type == 'Flat' && item.currency != null && item.currency != '' ? this.currency_list.find(x => x.currency_code == item.currency) : null;
        let decimal_definer = obj_currency ? obj_currency.currency_deci_definer : '2';
        resp.push({
          from_date: (item.format_type == 'Percentage' || item.format_type == 'Flat' || item.format_type == 'Night' || item.format_type == 'Nights') && item.deadline_date_from != null && item.deadline_date_from != '' ? moment(item.deadline_date_from).format('DD MMM YYYY hh:mm A') : '',
          to_date: (item.format_type == 'Percentage' || item.format_type == 'Flat' || item.format_type == 'Night' || item.format_type == 'Nights') && item.deadline_date_to != null && item.deadline_date_to != '' ? moment(item.deadline_date_to).format('DD MMM YYYY hh:mm A') : '',
          from_time: (item.format_type == 'Percentage' || item.format_type == 'Flat'|| item.format_type == 'Night' || item.format_type == 'Nights') ? this.commonserv.UtcToLocaleTime(item.deadline_time_from,'hh:mm a') : '',
          to_time: (item.format_type == 'Percentage' || item.format_type == 'Flat' || item.format_type == 'Night' || item.format_type == 'Nights') ? this.commonserv.UtcToLocaleTime(item.deadline_time_to, 'hh:mm a') : '',
          text: item.cancellation_policy_text,
          format_type: item.format_type,
          timezone: item.timezone,
          currency: this.getFormatType(item),
          amount: item.format_type == 'Flat' ? this.commonserv.amountDefiner(item.amount, decimal_definer) : parseInt(item.amount)
        });
      } else {
        resp.push({
          from_date: '',
          to_date: '',
          from_time: '',
          to_time: '',
          text: item.cancellation_policy_text,
          format_type: 'Text',
          currency: '',
          amount: ''
        });
      }
    });

    return {
      format_type: cancellation_policy[0].format_type,
      policy: resp,
    }
  }
  IsEmailLoader = false;

  getFormatType(item) {
    let type = '';
    if(item.format_type == 'Flat') {
      type = item.currency;
    }else if(item.format_type == 'Percentage') {
      type = '%';
    }else if(item.format_type == 'Night' || item.format_type == 'Nights') {
      let night = parseInt(item.amount);
      if(night > 1) type = 'Nights';
      else type = 'Night';
    }
    return type;
  }
  //  updated by Abdul Razzak on 13 mar 2024
  sendDocumentMail() {
    this.IsEmailLoader = true;
    let formData = this.mailForm.value;
    
    if (this.mailForm.status == 'INVALID') {
      this.validationServ.showValidationsMsg(this.mailForm);
      this.IsEmailLoader = false;
      return;
    }
      let url = '';
      if (formData.document_type == 'Itinerary') {
        let itineraryReqObj = {
          "BookingRefNo": this.trip_id,
          "CustomEmail": formData.email_id,
          "isB2B": false,
          "autoTrigger": false,
          "languageId": formData.languageId
        };
        this.APIServ.sendItineraryDocumentMail(itineraryReqObj).subscribe((data: any) => {
          if (data) {
            this.IsEmailLoader = false;
            if (data.resp) {
              this.messageService.add({ severity: 'success', summary: 'Success', detail: 'Itinerary sent to your mail id' });
              this.isOpenSendEmailModal = false;
            } else {
              this.messageService.add({ severity: 'error', summary: 'Failed', detail: 'Internal server error' });
            }
          }
        }, (error) => {
          this.IsEmailLoader = false;
          this.messageService.add({ severity: 'error', summary: 'Failed', detail: 'Internal server error' });
          this.isOpenSendEmailModal = false;
        });
      } else if (formData.document_type == 'Invoice') {
        this.APIServ.sendInvoiceDocumentMail(formData.document_number, formData.email_id).subscribe((data: any) => {
          if (data) {
            this.IsEmailLoader = false;
            if (data.resp) {
              this.messageService.add({ severity: 'success', summary: 'Success', detail: 'Invoice sent to your mail id' });
              this.isOpenSendEmailModal = false;
            } else {
              this.IsEmailLoader = false;
              this.messageService.add({ severity: 'error', summary: 'Failed', detail: 'Internal server error' });
            }
          }
        }, (error) => {
          this.IsEmailLoader = false;
          this.messageService.add({ severity: 'error', summary: 'Failed', detail: 'Internal server error' });
          this.isOpenSendEmailModal = false;
        });
      } else if (formData.document_type == 'Voucher') {
        let ReqObj = {
          "BookingRefNo": this.trip_id,
          "CustomEmail": formData.email_id,
          "isB2B": false,
          "autoTrigger": false,
          "languageId": formData.languageId
        };
        this.APIServ.sendVoucherDocumentMail(ReqObj).subscribe((data: any) => {
          if (data) {
            this.IsEmailLoader = false;
            if (data.resp) {
              this.messageService.add({ severity: 'success', summary: 'Success', detail: 'Voucher sent to your mail id' });
              this.isOpenSendEmailModal = false;
            } else {
              this.messageService.add({ severity: 'error', summary: 'Failed', detail: 'Internal server error' });
            }
          }
        }, (error) => {
          this.IsEmailLoader = false;
          this.messageService.add({ severity: 'error', summary: 'Failed', detail: 'Internal server error' });
          this.isOpenSendEmailModal = false;
        });
      }

  }


  updateStatus(BookingId, ind) {
    if (this.statusArr.controls[ind].status == 'INVALID') {
      this.validationServ.showValidationsMsg(this.statusArr.controls[ind]);
      return;
    };
    let val = this.StatusGroup.get('statusArr').value;
    let hotelBookingModify = {
      booking_id: BookingId,
      status_id: val[ind].status
    };
    this.APIServ.UpdateBooking(hotelBookingModify).subscribe((res) => {
      if (res) {
        this.messageService.add({
          severity: res['resp'] ? 'success' : 'error',
          detail: res['respMsg'],
        });
        this.dialogStatus[ind] = false;
        this.getItineraryTabDetails();
      }
    });
  };

  closeCancelDialog() {
    this.checkBookingCancel = false;
    this.isOpenAddBookingCancelModal = false;
  }

  //Standalone features
  featureList = {
    FC_64 :false,
    FC_81 :false,
    FC_85 :false,
  }
  getFeatures(pageId) {
    this.ApiServ.AdminGet("/MenuMasterNew/GetAllFeatureCode/2110180851430030870/" + pageId).subscribe(res => {
      this.features = res;
      if (this.features && this.features.length > 0) {
        this.features.forEach(e => {
          if (this.featureList[e.feature_code] === false) this.featureList[e.feature_code] = true;
        });
      };
    })
  }

  checkFeature(f_Code) {
    return this.features.some(z => z.feature_code == f_Code);
  }
  
    //Created by Arfat Qureshi Get all langugae by OrgId
    GetAllLAng(){
      return this.ApiServ.AdminGet('/LanguageMapping/GetLanguagesByOrgId')
  }
  SaveInvoiceNumber(){
    if(this.VendorInvoiceForm.status == 'VALID'){
      let val = this.VendorInvoiceForm.getRawValue();
      let obj = {
        booking_id: val.booking_id,
        vendor_invoice_number: val.vendor_invoice_number,
      };
      this.ApiServ.AdminGoPost('/Invoice/UpdateInvoiceVendor',obj).subscribe(data=>{
        if(data){
          this.commonserv.showMessage(data['Resp'],data['Message']);
          if(data.Resp){
            this.isOpenAddVendorInvoiceNumberModal = false;
            this.getCostingTabDetails();
          }
        }
      })
    }else {
      this.VendorInvoiceForm.markAsTouched();
    }
  }
}
