// Angular Core
import { Component, Input, OnDestroy, OnInit, Output, EventEmitter } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';

// RxJs
import { Subscription, throwError } from 'rxjs';
import { catchError } from "rxjs/operators";

// Components
import { FirstordernoticeComponent } from '../firstordernotice/firstordernotice.component';
import { ReviewOrderComponent } from '../review-order/review-order.component';

// Services
import { CartService } from '../../../../services/cart/cart.service';
import { CartValidationService } from 'src/app/services/cartValidation/cart-validation.service';
import { AccountInfoService } from 'src/app/services/accountInfo/account-info.service';
import { StripePaymentModelComponent } from 'src/app/components/stripe-payment-model/stripe-payment-model.component';

// Third Party
import { NgbModal, NgbModalConfig, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
import { environment } from 'src/environments/environment';
import { DataTransmitterService } from 'src/app/services/dataTransmitter/data-transmitter.service';
import { AnalyticsService } from 'src/app/services/analytics/analytics.service';
//import { Subscription } from 'rxjs';

@Component({
  standalone: false,
  selector: 'app-cartconfirmation',
  templateUrl: './cartconfirmation.component.html',
  styleUrls: ['./cartconfirmation.component.scss']
})
export class CartconfirmationComponent implements OnInit, OnDestroy {
    @Input() suppliers!: any
    @Input() suppMessages!: any
    @Input() displayChangeMethod!: any
    @Input() paymentMethodInfo!: any
    @Input() suppMessageDisplay!: any
    @Input() cartConfirmationPopup!: NgbModalRef
    @Input() checkDisabled!: boolean
    @Output() paymentMethodChanged = new EventEmitter<{action : string, addNewPaymentId : string | null}>();

    isCollapsed:boolean[] = [];
    firstOrderNoticeSupp: number[] = [];
    firstOrderSuppSignType: any[] = [];
    imgUrl: string = environment.imageUrl;
    sitename!: string;
    sitenameListener!: Subscription;
    confirmLabel: string = "Confirm";
    reviewOrderPopup!: NgbModalRef;
    disableReviewOrder: boolean = false;
    singleSupplierNoPaymentSetup: boolean = false;
    supplierNoPaymentSetup: boolean = false;
    suppliersWithPayment: Array<{key: string, value: any}> = [];
    payMethodAdded: boolean = false;
    paymentMethodsSubscribe!:Subscription;
    reviewOrderSubscribe!: Subscription;
    prepaySuppliers: { [id: number]: 'both' | 'ccOnly' | 'achOnly' } = {};
  
  constructor(
    private modalService: NgbModal,
    private cartService : CartService,
    private cartValidationService: CartValidationService,
    private accountInfoService: AccountInfoService,
    private dataTransmitter: DataTransmitterService,
    private analyticsService: AnalyticsService,
  ) { }

    hasAnyPrepayEnforcementError(): boolean {
        const supplierArr = Object.keys(this.suppliers).map(key => this.suppliers[key]);
        return supplierArr.some(supplier => {
            const enforcement = this.getPaymentEnforcement(supplier);
            return !enforcement.canPay;
        });
    }
    
    ngOnInit(): void {
        this.sitenameListener = this.dataTransmitter.sitename.subscribe((sitename: string) => {
            this.sitename = sitename;
        });
        this.updateSuppliersWithPayment();
        // Update disableReviewOrder based on enforcement errors
        this.updateCheckDisabledMultiSupplier();
    }

    /**
     * Updates flags controlling the checkout state for multi-supplier orders.
     *
     * Flags updated:
     *  - `disableReviewOrder`: boolean — true if buyer cannot proceed due to missing payment setup.
     *  - `singleSupplierNoPaymentSetup`: boolean — true if cart has a single supplier lacks a payment account.
     *  - `supplierNoPaymentSetup`: boolean — true if any supplier lacks a payment account when cart has multiple suppliers.
     *
     * @param string addNewPaymentId
     * @returns {void}
     */
    updateCheckDisabledMultiSupplier(addNewPaymentId : string = '') {
        this.disableReviewOrder = false;
        this.singleSupplierNoPaymentSetup = false;
        this.supplierNoPaymentSetup = false;
        //By default, allStandardSupps is set to true
        //If any Supplier has Stripe enabled then
        //isAllStandardSupps will be set to false.
        let isAllStandardSupps: boolean = true;

        const supplierKeys = Object.keys(this.suppliers);
        if (supplierKeys.length === 1) {
          const supplier = this.suppliers[supplierKeys[0]];
          if (!supplier.is_supp_payment_acc_exists) {
                this.singleSupplierNoPaymentSetup = true;
          }
        }
        supplierKeys.forEach(key => {
            const supplier = this.suppliers[key];
            if (supplier.is_supp_payment_acc_exists && (!supplier.is_buyer_payment_acc_exists && !this.hasPaymentMethods)) {
                this.disableReviewOrder = true;
            }
            if (!supplier.is_supp_payment_acc_exists) {
                this.supplierNoPaymentSetup = true;
            } else {
                isAllStandardSupps = false;
            }

            if (supplier.supplierData.failed_orders_exists) {
                this.prepaySuppliers[supplier.supplierData.id] = 'ccOnly';
                this.setPayment(supplier, 'card');
            } else {
                if (supplier.supplierData.first_order_prepay_reqd && supplier.supplierData.is_first_order) {
                    if (supplier.supplierData.first_order_prepay_cc && supplier.supplierData.first_order_prepay_ach) {
                      this.prepaySuppliers[supplier.supplierData.id] = 'both';
                      this.setPayment(supplier, 'both', addNewPaymentId);
                    } else if (supplier.supplierData.first_order_prepay_cc && !supplier.supplierData.first_order_prepay_ach) {
                      this.prepaySuppliers[supplier.supplierData.id] = 'ccOnly';
                      this.setPayment(supplier, 'card');
                    } else if (!supplier.supplierData.first_order_prepay_cc && supplier.supplierData.first_order_prepay_ach) {
                      this.prepaySuppliers[supplier.supplierData.id] = 'achOnly';
                      this.setPayment(supplier, 'bank', addNewPaymentId, false);
                    }
                } else {
                    if (supplier.payment_type_cc && !supplier.payment_type_ach) {
                      this.prepaySuppliers[supplier.supplierData.id] = 'ccOnly';
                      this.setPayment(supplier, 'card');
                    } else if (!supplier.payment_type_cc && supplier.payment_type_ach) {
                      this.prepaySuppliers[supplier.supplierData.id] = 'achOnly';
                      this.setPayment(supplier, 'bank', addNewPaymentId, false);
                    } else if (supplier.payment_type_cc && supplier.payment_type_ach) {
                        this.prepaySuppliers[supplier.supplierData.id] = 'both';
                        this.setPayment(supplier, 'both', addNewPaymentId);
                    }
                }
            } 
            this.suppliers = {...this.suppliers};
            this.updateSuppliersWithPayment();
        });
        setTimeout(() => {
            this.saveUserCartpayMethod(this.suppliersWithPayment);
        }, 2000);
        this.singleSupplierNoPaymentSetup = isAllStandardSupps;
        this.disableReviewOrder = this.hasAnyPrepayEnforcementError();
    }
    
    userCartpayMethodSubscribe!:Subscription;
    saveUserCartpayMethod(userCartPayMethods: any) {
        this.userCartpayMethodSubscribe = this.cartService
            .saveUserCartpayMethod(userCartPayMethods)
            .pipe(
                catchError(() => {
                  return throwError(() => new Error('ups sommething happend'));
                })
            )
            .subscribe({
                next: (res: any) => {
                  if (res.data !== false) {
                    this.hasPaymentMethods = true;
                  }
                },
                error: (err: HttpErrorResponse) => {
                  this.accountInfoService.errorCallBack(err);
                },
                complete: () => { }
            });
    }
    
    /**
     * Sets the supplier's default payment method based on the given type and conditions.
     * If `type` is `'both'` and a valid `addNewPaymentId` is provided,
     * the specified payment method is set as default.
     * Otherwise, the method attempts to select a preferred payment type:
     * If `type` is `'both'`, it prefers `'card'` when available, otherwise `'bank'`.
     * If no default payment method exists(supplier.default_payment_id = 0) or the existing one does not match
     * the preferred type, a new default is selected.(supplier.default_payment_id is bank but prefrerred type is ccOnly)
     * @param {any} supplier
     * @param {string} type
     * @param {string} addNewPaymentId
     * @param {boolean} creditCard
     */
    setPayment(supplier: any, type: string, addNewPaymentId: string = '', creditCard: boolean = true) {
        if (type === 'both' && (addNewPaymentId !== '' && addNewPaymentId !== null)) {
            const method = supplier.payment_methods.find((pm: any) => pm.id === addNewPaymentId);
            supplier.default_payment_id = this.paymentMethodInfo[supplier.supplierData.id].default_payment_id = method?.id;
            supplier.default_payment_method = this.paymentMethodInfo[supplier.supplierData.id].default_payment_method = method?.name;
        } else {
            let preferType = type;
            if (type === 'both') {
                const hasType = supplier.payment_methods?.some((pm: any) => pm.type === 'card');
                preferType = hasType ? 'card' : 'bank';
            }
            const defaultMethod = supplier.payment_methods.find((pm: any) => pm.id === supplier.default_payment_id);
            const hasCC = supplier.payment_methods?.some((pm: any) => pm.card_type === 'credit');
            if ((defaultMethod && defaultMethod.type !== preferType && type !== 'both') || !defaultMethod) {
                let method = supplier.payment_methods.find((pm: any) => pm.type === preferType);
                supplier.default_payment_id = this.paymentMethodInfo[supplier.supplierData.id].default_payment_id = method?.id;
                supplier.default_payment_method = this.paymentMethodInfo[supplier.supplierData.id].default_payment_method = method?.name;
            }
            if (!defaultMethod && creditCard && hasCC) {
                let method = supplier.payment_methods.find((pm: any) => pm.card_type === 'credit');
                supplier.default_payment_id = this.paymentMethodInfo[supplier.supplierData.id].default_payment_id = method?.id;
                supplier.default_payment_method = this.paymentMethodInfo[supplier.supplierData.id].default_payment_method = method?.name;
            }
        }
    }
    
    hasPaymentMethods: boolean = false;
    hasPayMethodsSubscribe!:Subscription;
    hasPayMethods() {
        this.hasPayMethodsSubscribe = this.accountInfoService
            .hasPayMethods()
            .pipe(
                catchError(() => {
                  return throwError(() => new Error('ups sommething happend'));
                })
            )
            .subscribe({
                next: (res: any) => {
                  if (res.data !== false) {
                    this.hasPaymentMethods = true;
                  }
                },
                error: (err: HttpErrorResponse) => {
                  this.accountInfoService.errorCallBack(err);
                },
                complete: () => { }
            });
    };
    
    /**
     * Public method click Confirm in cartConfirmation modal
     * @return {undefined}
     */
    cartConfirmClickConfirm(suppliers: any, btnName: string) {
        this.displayFirstOrderNotice(suppliers, btnName);
    };

    firstOrderPopup!: NgbModalRef
    displayFirstOrderNotice(suppliers: any, btnName: string) {
        const dataArray = Object.keys(suppliers).map(key => ({key, value: suppliers[key]}));

        dataArray.forEach((supplier: any) => {
            if (supplier.value.supplierData.is_credit_app_doc_reqd === 1 && supplier.value.supplierData.is_first_order === true
                  && supplier.value.supplierData.delay_new_account_results === 0) {                
                this.firstOrderNoticeSupp.push(supplier.value.supplierData.id);
                this.firstOrderSuppSignType[supplier.value.supplierData.id] = supplier.value.supplierData.echosign_signatureType;
            }
        })
        if (this.firstOrderNoticeSupp.length === 0) {
            if (btnName === 'completeOrder') {
                this.reviewOrderPopup.close('Confirm');
                this.reviewOrderPopup = null as any;
            } else {
                this.cartConfirmationPopup.close('Confirm');
            }
           
        }
        if (this.firstOrderNoticeSupp.length > 0) {
            this.firstOrderPopup = this.modalService.open(FirstordernoticeComponent, {size: 'sm'});
            this.firstOrderPopup.componentInstance.firstOrderNoticeSupp = this.firstOrderNoticeSupp;
            this.firstOrderPopup.componentInstance.firstOrderSuppSignType = this.firstOrderSuppSignType;
            this.firstOrderPopup.componentInstance.reviewOrderPopup = this.reviewOrderPopup;
            this.firstOrderPopup.componentInstance.cartConfirmationPopup = this.cartConfirmationPopup;
            this.firstOrderPopup.componentInstance.firstOrderPopup = this.firstOrderPopup;
        }
    }

    /**
     * Calculating complete item amount for cart
     * @param {type} data
     * @return {Number}
     */
    itemTotal(data: any) {
        var iTotal = 0;
        const dataArray =  Object.keys(data).map(key => ({key, value: data[key]}));
        dataArray.forEach((obj: any) => {
            if (!obj.value.is_supp_payment_acc_exists) {
                const dataArray1 =  Object.keys(obj.value.items).map(key => ({key, value: obj.value.items[key]}));
                dataArray1.forEach((obj1: any) => {
                  var formatted_total_price = obj1.value?.total_price.toString().split(",").join("")
                  iTotal += Number(formatted_total_price);
                })
            }
        })
        return iTotal;
    };

    /**
     * Calculating complete fee amount for cart
     * @param {type} data
     * @return {Number}
     */
    feeTotal(data: any) {
      var fTotal = 0;
      data =  Object.keys(data).map(key => ({key, value: data[key]}));

      data.forEach((obj: any) => {
        if(!obj.value.shippingData.hasOwnProperty('shippingFee')) {
            obj.value.shippingData.shippingFee = 0;
        }
        if (!obj.value.is_supp_payment_acc_exists) {
            fTotal += Number(obj.value.shippingData.shippingFee);
        }
      })
      return fTotal;
    };

    /**
     * Calculating totals for each supplier
     * @param {type} supplier
     * @return {total|fee}
     */
    setTotals(supplier: any) {
      var fee = Number(supplier.shippingData.shippingFee);

      var supplierTotal = fee + supplier.totalOrderAmount;
      return supplierTotal;
    };

    cartConfirmClickBack(suppliers: any){
      this.cartService.cartConfirmClickBackEmitter.emit(suppliers)
    }

    /**
     * function to check if supplier qualifies for trxade credits
     * @returns {boolean}
     */
    displayIfCreditsExist(supplier: any) {
      var trxadeCredits = this.cartValidationService.checkIfCreditsExist(supplier.value);
      var credits = 0;
      if(supplier.value.qualifiedForCredit === true && trxadeCredits === true) {
        credits++;
      }
      if(credits > 0) {
          return true;
      }
      else {
          return false;
      }
    };

    /**
     * Calculating Trxade total for each supplier
     * @param {type} supplier
     */
    trxadeCreditsTotal(supplier: any) {
      var supplierTrxadeTotal = 0;
      var data: any =  Object.keys(supplier.items).map(key => ({key, value: data[key]}));

      data.forEach((item: any) => {
        supplierTrxadeTotal += item.credit_amount;
      })

      return supplierTrxadeTotal;
    };

    /**
     * To update payment-related values when switching to a new payment method
     * @param {any} event
     * @param {number} suppId
     * @return void
    */
    changePaymentMethod(event: any, suppId: any) {
        var paymentId = event.target.value;
        var paymentMethod = event.target.selectedOptions[0].text;
        if (paymentMethod == 'Add New') {
            this.showStripePaymentModel(suppId);
            event.target.value = this.paymentMethodInfo[suppId]?.default_payment_id || '';
        } else {
            this.displayPaymentDropDown(suppId, true);
            this.paymentMethodInfo[suppId] = {
                default_payment_id: paymentId,
                default_payment_method: paymentMethod,
                payment_date: this.paymentMethodInfo[suppId].payment_date
            };
            this.confirmLabel = "Review Order";
            this.suppliers[suppId].default_payment_method = paymentMethod;
            this.suppliers[suppId].default_payment_id = paymentId;
        }
        this.saveSuppPayMethod(suppId, paymentId, paymentMethod);
    }

    /**
     * Method to set the flag to display/hide the "Change method" text/payment methods dropdown
     * @param {number} suppId
     * @param {boolean} displayFlag
     * @return void
    */
    displayPaymentDropDown(suppId: number, displayFlag: boolean) {
       this.displayChangeMethod[suppId] = displayFlag;
       this.analyticsService.changeMethodClicked().subscribe();
    }
  
    /**
     * Opens the Stripe payment modal for setting up a payment method.
     * Subscribes to the addPayMethodStatus event to update the payment method status.
     */
    stripePaymentModel!: NgbModalRef
    showStripePaymentModel(suppId: any = null) {
        this.paymentMethodsSubscribe = this.accountInfoService
        .getAllPaymentMethods()
        .subscribe({
            next: (res: any) => {
                if (res.data !== false) {
                    this.payMethodAdded = true;
                    this.stripePaymentModel = this.modalService.open(StripePaymentModelComponent,{size: 'sm'});
                    this.stripePaymentModel.componentInstance.stripePaymentModel = this.stripePaymentModel;
                    this.stripePaymentModel.componentInstance.stripePaymentModelNo = this.stripePaymentModelNo;
                    this.stripePaymentModel.componentInstance.paymentMethodCards = res.data?.cards || [];
                    this.stripePaymentModel.componentInstance.paymentMethodBank = res.data?.bankAccounts || [];
                    this.stripePaymentModel.componentInstance.pendingBankPymentMethods = res.data?.pendingBankPayMethods || [];
                    this.stripePaymentModel.componentInstance.isFromCart = true;
                    this.stripePaymentModel.componentInstance.forSupp = suppId;

                    // Subscribe to addPayMethodStatus event
                    this.stripePaymentModel.componentInstance.addPayMethodStatus.subscribe((data: any) => {
                        if (data.status) {
                            this.paymentMethodChanged.emit({action : 'add', addNewPaymentId : data.addNewPaymentId}); // Payment Method is Added or Edited
                        }
                    });
                    this.stripePaymentModel.componentInstance.deletePaymentMethod.subscribe((addNewPaymentId: any) => {
                        this.paymentMethodChanged.emit({action : 'delete', addNewPaymentId : addNewPaymentId}); // Payment Method is Deleted
                    });
                }
            },
            error: (err: HttpErrorResponse) => {
              this.accountInfoService.errorCallBack(err);
            },
            complete: () => { }
        });
    };
    
    /**
     * Dismisses the Stripe payment modal.
     * @param action
     */
    stripePaymentModelNo(action: any) {
        this.stripePaymentModel.dismiss();
    };
    
    /**
     * Returns an array of suppliers with payment portal enabled.
     *
     * Transforms the suppliers object into an array of {key, value} pairs,
     * and filters to include only those suppliers where is_supp_payment_acc_exists is true.
     *
     * @returns array
     */
    updateSuppliersWithPayment() {
      this.suppliersWithPayment = Object.keys(this.suppliers)
        .map(key => ({ key, value: this.suppliers[key] }))
        .filter(supplier => supplier.value.is_supp_payment_acc_exists);
    }

    showCartConfirmationModal(suppliers: any){
      this.cartService.showCartConfirmationModalEmitter.emit(suppliers);
    }

    /**
     * Method to complete checkout process
     * object suppliers
    */
    completeOrderProcess(suppliers: any){
      this.cartService.cartCompleteOrderEmitter.emit({suppliers: suppliers, paymentMethodInfo: this.paymentMethodInfo});
    }
    
    showCartError(suppliersList: any) {
       this.cartService.cartErrorEmitter.emit({supplierList:suppliersList});
    }
    
    reviewOrder(suppliers: any) {
        const supplierInfo = Object.keys(suppliers).map(key => ({key, value: suppliers[key]}));
        const cartData: any = {};
        let itemsInfo: any = {};
        supplierInfo.forEach((supplier: any) => {
          itemsInfo = Object.keys(supplier.value.items);
          let paymentId = this.paymentMethodInfo[supplier.value.supplierData.id].default_payment_id;
          if (supplier.value.payment_type_check_only) {
               paymentId = "check";
          }
          cartData[supplier.value.supplierData.id] = {
            items: itemsInfo,
            shippingMethod: supplier.value.shippingData.selectedShipping,
            shipFee: supplier.value.shippingData.shippingFee,
            paymentmethodId: paymentId,
            surchargeEnabled: supplier.value.supplierData.cc_surcharge_enabled
          }
          supplier.value.cardType = supplier.value.payment_methods.find((pm: any) => pm.id === supplier.value.default_payment_id)?.card_type;
        });
        this.reviewOrderSubscribe = this.cartService.checkoutSessionUpdate({cartData: cartData})
        .subscribe({
            next: (res: any) => {
              this.cartConfirmationPopup?.close('Back to Cart');
              let isStandSuppExists = false;
              let isPaymentErrorExists = false;
              let paymentSuppCounter = 0;
              let errorSuppList: any[] = [];
              // Prevent multiple review order modals from opening
              if (this.reviewOrderPopup) {
                return;
              }
              let paymentSuppIndex: any = {};
              let surchargeAmount: any = {};
              const supplierInfo = Object.keys(suppliers).map(key => ({key, value: suppliers[key]}));
              supplierInfo.forEach((supplier: any) => {
                if (!supplier.value.payment_type_check_only && res.data[supplier.value.supplierData.id].error == true) {
                  isPaymentErrorExists = true;
                  errorSuppList.push(supplier.value.supplierData.name);
                } else {
                  if (!supplier.value.is_supp_payment_acc_exists) 
                  {
                    isStandSuppExists = true;
                  } else {
                    paymentSuppCounter = paymentSuppCounter + 1;
                    paymentSuppIndex[supplier.value.supplierData.id] = paymentSuppCounter;
                    const supplierId = supplier.value.supplierData.id;
                    surchargeAmount[supplierId] = 0.00;
                    if (!supplier.value.payment_type_check_only) {
                        // Stripe always returns the surcharge amount in cents, so you need to divide it by 100 to get the correct value.
                        const surchargeData = res.data?.[supplierId]?.yeeldData?.surcharge;
                        surchargeAmount[supplierId] = (surchargeData && !isNaN(parseFloat(surchargeData))) ? parseFloat(surchargeData) / 100 : 0;
                    }
                  }
                }
              });
              if (!isPaymentErrorExists) {
                  this.reviewOrderPopup = this.modalService.open(ReviewOrderComponent, {size: 'lg'});
                  this.reviewOrderPopup.componentInstance.suppliers = suppliers;
                  this.reviewOrderPopup.componentInstance.reviewOrderPopup = this.reviewOrderPopup;
                  this.reviewOrderPopup.componentInstance.sitename = this.sitename;
                  this.reviewOrderPopup.componentInstance.imgUrl = this.imgUrl;
                  this.reviewOrderPopup.componentInstance.paymentMethodInfo = this.paymentMethodInfo;
                  this.reviewOrderPopup.componentInstance.paymentSuppIndex = paymentSuppIndex; 
                  this.reviewOrderPopup.componentInstance.isStandSuppExists = isStandSuppExists;
                  this.reviewOrderPopup.componentInstance.surchargeAmount = surchargeAmount;
                  this.reviewOrderPopup.componentInstance.closeReviewOrder = (suppliers: any) => {
                      this.accountInfoService.backToReview().subscribe();
                      this.showCartConfirmationModal(suppliers);
                      this.reviewOrderPopup.close();
                  };
                  this.reviewOrderPopup.componentInstance.completeOrder = (suppliers: any) => {
                      this.cartConfirmClickConfirm(suppliers, 'completeOrder');
                  };
                  this.reviewOrderPopup.result.then((value) => {
                      if (value == 'Confirm') {
                          this.completeOrderProcess(suppliers);
                      }
                  }).catch(() => {
                      // Modal was dismissed/closed
                  }).finally(() => {
                      // Clear the modal reference so new modals can be opened
                      this.reviewOrderPopup = null as any;
                  });
                } else {
                    this.showCartError(errorSuppList);
                }
            },
            error: (err) => {
              this.cartService.errorCallBack(err);
            },
            complete: () => { },
        }); 
    }
    
    closeReviewOrder(suppliers: any) {
        this.reviewOrderPopup.close();
        this.reviewOrderPopup = null as any;
    };
    
    getPaymentEnforcement(supplier: any): {
    forceCC: boolean;
    forceACH: boolean;
    allowBoth: boolean;
    canPay: boolean;
    } {
        const suppData = supplier.supplierData;
        const buyerHasCC = supplier.payment_methods?.some((pm: any) => pm.type === 'card');
        const buyerHasACH = supplier.payment_methods?.some((pm: any) => pm.type === 'bank');
        let result = {
            forceCC: false,
            forceACH: false,
            allowBoth: false,
            canPay: true
        };
        if (suppData.first_order_prepay_reqd && suppData.is_first_order) {
            if (suppData.first_order_prepay_cc && !suppData.first_order_prepay_ach) {
                result.forceCC = true;
                result.canPay = !!buyerHasCC;
            } else if (!suppData.first_order_prepay_cc && suppData.first_order_prepay_ach) {
                result.forceACH = true;
                result.canPay = !!buyerHasACH;
            } else if (suppData.first_order_prepay_cc && suppData.first_order_prepay_ach) {
                result.allowBoth = true;
                result.canPay = !!(buyerHasCC || buyerHasACH);
            }
        } else {
            if (supplier.payment_type_cc && !supplier.payment_type_ach) {
                result.forceCC = true;
                result.canPay = !!buyerHasCC;
            } else if (!supplier.payment_type_cc && supplier.payment_type_ach) {
                result.forceACH = true;
                result.canPay = !!buyerHasACH;
            } else if (supplier.payment_type_cc && supplier.payment_type_ach) {
                result.allowBoth = true;
                result.canPay = !!(buyerHasCC || buyerHasACH);
            }
        }
        return result;
    }

    saveSuppPayMethodSubscribe!:Subscription;
    saveSuppPayMethod(suppId: number, paymentId: any, paymentMethod: any) {
        this.saveSuppPayMethodSubscribe = this.cartService
            .saveSuppPayMethod(suppId,paymentId,paymentMethod)
            .pipe(
                catchError(() => {
                  return throwError(() => new Error('ups sommething happend'));
                })
            )
            .subscribe({
                next: (res: any) => {
                  if (res.data !== false) {
                    this.hasPaymentMethods = true;
                  }
                },
                error: (err: HttpErrorResponse) => {
                  this.accountInfoService.errorCallBack(err);
                },
                complete: () => { }
            });
    }
    
    ngOnDestroy(): void {
        this.sitenameListener.unsubscribe();
        this.reviewOrderSubscribe?.unsubscribe();
        this.paymentMethodsSubscribe?.unsubscribe();
        this.hasPayMethodsSubscribe?.unsubscribe();
        this.saveSuppPayMethodSubscribe?.unsubscribe();
        this.userCartpayMethodSubscribe?.unsubscribe();
    }
}
