// Angular Core
import { ChangeDetectorRef, Component, ElementRef, OnDestroy, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AbstractControl, FormBuilder, FormGroup, ValidationErrors, ValidatorFn, Validators } from '@angular/forms';
import { formatDate } from '@angular/common';
import { HttpErrorResponse } from '@angular/common/http';

// RxJs
import { Subscription, throwError } from 'rxjs';
import { catchError, distinctUntilChanged } from "rxjs/operators";

// Services
import { AccountInfoService } from 'src/app/services/accountInfo/account-info.service';
import { SessionService } from 'src/app/services/session/session.service';
import { LocalStorageService } from 'src/app/services/localstorage/local-storage.service';

// Interfaces
import { BuyingGroupListInterface } from 'src/app/interfaces/user/buying-group-list-interface';
import { UserDataInterface } from 'src/app/interfaces/user/user-data-interface';
import { GetStates } from 'src/app/interfaces/user/get-states';
import { SuppliersList } from 'src/app/interfaces/supplier/suppliers-list';
import { OwnerPositions } from 'src/app/interfaces/user/owner-positions';
import { SessionDataInterface } from 'src/app/interfaces/session-data-interface';
import { DataTransmitterService } from 'src/app/services/dataTransmitter/data-transmitter.service';
import { UtilitiesService } from 'src/app/services/utilities/utilities.service';

@Component({
    selector: 'app-store-info',
    templateUrl: './store-info.component.html',
    styleUrls: ['./store-info.component.scss'],
    standalone: false
})
export class StoreInfoComponent implements OnInit, OnDestroy {
    userStoreInfoForm: any = new FormGroup({});
    session!: SessionDataInterface['data'];
    isBuyer!: boolean;
    renderMe!: boolean;
    pmsList: any = [];
    validateErrorInfo: { [key: string]: boolean } = {};
    isBillingCollapsed = true
    isContactCollapsed = false
    isLicenseCollapsed = true
    isReferencesCollapsed = true
    isShippingCollapsed = true
    isInvalid = false;
    isSaveBtnClicked = false;
    userData!: UserDataInterface['data'];
    states!: GetStates['data'];
    buyingGroups!: BuyingGroupListInterface['data'];
    buyingGroupedList!: any[];
    unGroupedList!: any[];
    groupedList!: any[];
    invalidCount = 0;
    suppliersList!: SuppliersList['data'];
    groupedSuppList!: any[];
    uniqueValue!: string[];
    ownerPositions!: OwnerPositions['data'];
    suppAccNames = ['Wholesaler', 'Manufacturer'];
    userType!: string;
    sitename!: string;
    sitenameListener!: Subscription;
    getAccountInfoSubscribe!: Subscription;
    getStatesSubscribe!: Subscription;
    getOwnerPositionsSubscribe!: Subscription;
    buyingGroupListSubscribe!: Subscription;
    saveUserInfoSubscribe!: Subscription;
    getSuppliersSubscribe!: Subscription;
    getPmsListSubscribe!: Subscription;

    constructor(
        private formBuilder: FormBuilder,
        private accountInfoService: AccountInfoService,
        private sessionService: SessionService,
        private router: Router,
        private el: ElementRef,
        private localStorageService: LocalStorageService,
        private changeDetector: ChangeDetectorRef,
        private dataTransmitter: DataTransmitterService,
        private utilities: UtilitiesService
    ) {
        this.userStoreInfoForm = this.formBuilder.group({});
    }


    ngOnInit(): void {
        this.session = this.sessionService.getSession();
        this.isBuyer = this.session.is_buyer;
        this.renderMe = this.session.logged_in && (this.session.reg_step >= 2);
        this.userType = this.session.user_type;
        this.sitenameListener = this.dataTransmitter.sitename.subscribe((sitename) => {
            this.sitename = sitename;
        });
        /**
        * avoid partial load if not logged in
        */
        this.initForm(this.isBuyer);
        this.getAccInfo();

    }

    initForm(isBuyer: boolean) {

        let taxExempt = [null, [this.validateDateExpire('taxExempt')]];
        if (!isBuyer) {
            taxExempt = [null];
        }
        this.userStoreInfoForm = this.formBuilder.group({
            legal_company_name: ['', [Validators.required, Validators.maxLength(100)]],
            legal_trade_name: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(100)]],
            website: ['', [Validators.maxLength(255), Validators.pattern(/^((http|https):\/\/)?(www.)?(?!.*(http|https|www.))[a-zA-Z0-9_-]+(\.[a-zA-Z]+)+((\/)[\w#]+)*(\/\w+\?[a-zA-Z0-9_]+=\w+(&[a-zA-Z0-9_]+=\w+)*)?$/)]],
            legal_address: ['', [Validators.required, Validators.maxLength(100)]],
            legal_city: ['', [Validators.required, Validators.maxLength(100), Validators.pattern(/^[a-zA-Z ]+$/)]],
            legal_state: ['', Validators.required],
            legal_zip: ['', [Validators.required, Validators.pattern(/^[0-9]{5}$/)]],
            legal_phone: ['', [Validators.required, Validators.maxLength(15), Validators.pattern(/^\d{3}-?\d{3}-?\d{4}$/)]],
            legal_fax: ['', [Validators.maxLength(15), Validators.pattern(/^\d{3}-?\d{3}-?\d{4}$/)]],

            billing_same_as_legal: [false],
            billing_address: ['', [Validators.required, Validators.maxLength(100)]],
            billing_city: ['', [Validators.required, Validators.maxLength(100), Validators.pattern(/^[a-zA-Z ]+$/)]],
            billing_state: ['', [Validators.required, Validators.maxLength(100)]],
            billing_zip: ['', [Validators.required, Validators.pattern(/^[0-9]{5}$/)]],
            billing_phone: ['', [Validators.required, Validators.pattern(/^\d{3}-?\d{3}-?\d{4}$/)]],
            billing_fax: ['', [Validators.maxLength(15), Validators.pattern(/^\d{3}-?\d{3}-?\d{4}$/)]],

            contact_firstname: ['', [Validators.required, Validators.maxLength(50)]],
            contact_lastname: ['', [Validators.required, Validators.maxLength(50)]],
            contact_position: ['', [Validators.required, Validators.maxLength(50)]],
            contact_phone: ['', [Validators.required, Validators.maxLength(15), Validators.pattern(/^\d{3}-?\d{3}-?\d{4}$/)]],
            contact_email: ['', [Validators.required, Validators.maxLength(255), Validators.email]],
            owner_firstname: ['', [Validators.required, Validators.maxLength(50)]],
            owner_lastname: ['', [Validators.required, Validators.maxLength(50)]],
            owner_position: ['', [Validators.required, Validators.maxLength(50)]],
            owner_phone: ['', [Validators.required, Validators.maxLength(50), Validators.pattern(/^\d{3}-?\d{3}-?\d{4}$/)]],
            owner_email: ['', [Validators.required, Validators.maxLength(255), Validators.email]],
            officer_firstname: ['', [Validators.maxLength(50)]],
            officer_lastname: ['', [Validators.maxLength(50)]],
            officer_position: ['', [Validators.maxLength(50)]],
            officer_phone: ['', [Validators.maxLength(15), Validators.pattern(/^\d{3}-?\d{3}-?\d{4}$/)]],
            officer_email: ['', [Validators.maxLength(255), Validators.email]],
            sameAsPBC: [false],
            purchaser_firstname: ['', [Validators.required, Validators.maxLength(50)]],
            purchaser_lastname: ['', [Validators.required, Validators.maxLength(50)]],
            purchaser_position: ['', [Validators.required, Validators.maxLength(50)]],
            purchaser_phone: ['', [Validators.required, Validators.maxLength(15), Validators.pattern(/^\d{3}-?\d{3}-?\d{4}$/)]],
            purchaser_email: ['', [Validators.required, Validators.maxLength(255), Validators.email]],
            accounting_firstname: ['', [Validators.maxLength(50)]],
            accounting_lastname: ['', [Validators.maxLength(50)]],
            accounting_position: ['', [Validators.maxLength(50)]],
            accounting_phone: ['', [Validators.maxLength(15), Validators.pattern(/^\d{3}-?\d{3}-?\d{4}$/)]],
            accounting_email: ['', [Validators.maxLength(255), Validators.email]],

            state_license_num: ['', [Validators.required, Validators.maxLength(50)]],
            dea_license_num: ['', [Validators.required, Validators.maxLength(50)]],
            tax_exempt_id: ['', Validators.maxLength(25)],
            state_license_expire: [null, [Validators.required, this.validateDateExpire('sln')]],
            dea_license_expire: [null, [Validators.required, this.validateDateExpire('dln')]],
            tax_exempt_expire_date: taxExempt,
            tax_reg_number: ['', [Validators.required, Validators.maxLength(100)]],
            npi_license_num: ['', [Validators.maxLength(50), Validators.pattern(/^[0-9]+$/)]],
            gpo_primary_buying_group_id: ['', [Validators.required]],
            gpo_secondary_buying_group_id: [''],
            status340B: [false],
            gpo_primary_buying_group_name: ['', [Validators.maxLength(100)]],
            gpo_secondary_buying_group_name: ['', [Validators.maxLength(100)]],
            gln_num: ['', [Validators.required, Validators.maxLength(50)]],

            primary_reference_id: this.suppAccNames.indexOf(this.userType) === -1 ? ['', [Validators.required]] : [''],
            primary_reference_name: ['', [Validators.maxLength(100)]],
            primary_reference_state: this.suppAccNames.indexOf(this.userType) === -1 ? ['', [Validators.required]] : [''],
            primary_reference_phone: this.suppAccNames.indexOf(this.userType) === -1 ? ['', [Validators.required, Validators.pattern(/^\d{3}-?\d{3}-?\d{4}$/)]] : [''],
            secondary_reference_id: this.suppAccNames.indexOf(this.userType) === -1 ? ['', [Validators.required]] : [''],
            secondary_reference_name: ['', [Validators.maxLength(100)]],
            secondary_reference_state: [''],
            secondary_reference_phone: ['', [Validators.pattern(/^\d{3}-?\d{3}-?\d{4}$/)]],
            pmsValue: this.suppAccNames.indexOf(this.userType) === -1 ? ['', Validators.required] : [''],
            tech_reference_name: ['', [Validators.maxLength(100)]],
            tech_reference_state: [''],
            tech_reference_phone: ['', [Validators.pattern(/^\d{3}-?\d{3}-?\d{4}$/)]],
            bank_reference_name: this.suppAccNames.indexOf(this.userType) === -1 ? ['', [Validators.required, Validators.maxLength(100)]] : [''],
            bank_reference_state: [''],
            bank_reference_phone: ['', [Validators.pattern(/^\d{3}-?\d{3}-?\d{4}$/)]]
        }, { updateOn: 'change' });
    }

    get userStoreInfoFormData() { return this.userStoreInfoForm.controls; }

    formControlValueChanged() {
        const primary_reference_name = this.userStoreInfoForm.get('primary_reference_name');
        const primary_reference_state = this.userStoreInfoForm.get('primary_reference_state');
        const primary_reference_phone = this.userStoreInfoForm.get('primary_reference_phone');
        const secondary_reference_name = this.userStoreInfoForm.get('secondary_reference_name');
        const secondary_reference_state = this.userStoreInfoForm.get('secondary_reference_state');
        const secondary_reference_phone = this.userStoreInfoForm.get('secondary_reference_phone');
        const tech_reference_name = this.userStoreInfoForm.get('tech_reference_name');
        const gpo_primary_buying_group_name = this.userStoreInfoForm.get('gpo_primary_buying_group_name');
        this.userStoreInfoForm.get('primary_reference_id').valueChanges
            .pipe(distinctUntilChanged())
            .subscribe(
                (val: any) => {
                    // Used == instead of === because val can sometimes be a string or an integer.
                    if (val == 999999) {
                        primary_reference_name.setValidators([Validators.required]);
                        primary_reference_state.setValue('')
                        primary_reference_phone.setValue('')
                    } else {
                        if (val === '111111') {
                            primary_reference_state.setValue('')
                            primary_reference_phone.setValue('')
                        } else if (val === '') {
                            primary_reference_state.setValue('')
                            primary_reference_phone.setValue('')
                        } else {
                            let selectedSupplier: SuppliersList['data'][0] | undefined = this.suppliersList.find((item: SuppliersList['data'][0]) => {
                                return item.id == val
                            })
                            primary_reference_state.setValue(selectedSupplier?.stateCode)
                            primary_reference_phone.setValue(selectedSupplier?.phone)
                        }
                        primary_reference_name.clearValidators();
                    }
                    primary_reference_name.updateValueAndValidity();
                });
        this.userStoreInfoForm.get('secondary_reference_id').valueChanges.subscribe(
            (val: any) => {
                if (val == 999999) {
                    secondary_reference_name.setValidators([Validators.required]);
                    secondary_reference_state.setValue('')
                    secondary_reference_phone.setValue('')
                } else {
                    if (val === '111111') {
                        secondary_reference_state.setValue('')
                        secondary_reference_phone.setValue('')
                    } else if (val === '') {
                        secondary_reference_state.setValue('')
                        secondary_reference_phone.setValue('')
                    } else {
                        let selectedSupplier: SuppliersList['data'][0] | undefined = this.suppliersList.find((item: SuppliersList['data'][0]) => {
                            return item.id == val
                        })
                        secondary_reference_state.setValue(selectedSupplier?.stateCode)
                        secondary_reference_phone.setValue(selectedSupplier?.phone)
                    }
                    secondary_reference_name.clearValidators();
                }
                secondary_reference_name.updateValueAndValidity();
            });
        this.userStoreInfoForm.get('pmsValue').valueChanges.subscribe(
            (val: any) => {
                if (val === 'Other') {
                    tech_reference_name.setValidators([Validators.required]);
                } else if (val === '') {
                    this.userStoreInfoFormData.tech_reference_state.patchValue('');
                    this.userStoreInfoFormData.tech_reference_phone.patchValue('');
                } else {
                    tech_reference_name.clearValidators();
                }
                tech_reference_name.updateValueAndValidity();
            });
        this.userStoreInfoForm.get('bank_reference_name').valueChanges.subscribe(
            (val: any) => {
                if (val === '') {
                    this.userStoreInfoFormData.bank_reference_state.patchValue('');
                    this.userStoreInfoFormData.bank_reference_phone.patchValue('');
                }
            });
        this.userStoreInfoForm.get('gpo_primary_buying_group_id').valueChanges.subscribe(
            (val: any) => {
                if (val == 999999) {
                    gpo_primary_buying_group_name.setValidators([Validators.required]);
                } else {
                    gpo_primary_buying_group_name.clearValidators();
                }
                gpo_primary_buying_group_name.updateValueAndValidity();
            });
        this.userStoreInfoForm.get('state_license_expire').valueChanges.subscribe(
            (val: any) => {
                this.userStoreInfoForm.get('state_license_expire').updateValueAndValidity({ emitEvent: false });
            });
        this.userStoreInfoForm.get('dea_license_expire').valueChanges.subscribe(
            (val: any) => {
                this.userStoreInfoForm.get('dea_license_expire').updateValueAndValidity({ emitEvent: false });
            });
        this.userStoreInfoForm.get('tax_exempt_expire_date').valueChanges.subscribe(
            (val: any) => {
                this.userStoreInfoForm.get('tax_exempt_expire_date').updateValueAndValidity({ emitEvent: false });
            });
        this.userStoreInfoForm.get('primary_reference_state').valueChanges.subscribe(
            (val: any) => {
                if (this.suppAccNames.indexOf(this.userType) === -1 && val !== "") {
                    this.updateUserData('primary_reference_state')
                }
            });
        this.userStoreInfoForm.get('secondary_reference_state').valueChanges.subscribe(
            (val: any) => {
                this.updateUserData('secondary_reference_state')
            });
        this.userStoreInfoForm.get('tech_reference_state').valueChanges.subscribe(
            (val: any) => {
                this.updateUserData('tech_reference_state')
            });
        this.userStoreInfoForm.get('bank_reference_state').valueChanges.subscribe(
            (val: any) => {
                this.updateUserData('bank_reference_state')
            });
        this.userStoreInfoForm.get('primary_reference_phone').valueChanges.subscribe(
            (val: any) => {
                if (this.suppAccNames.indexOf(this.userType) === -1 && val !== "") {
                    this.userStoreInfoForm.get('primary_reference_phone').updateValueAndValidity({ emitEvent: false });
                }
            });
        this.userStoreInfoForm.get('sameAsPBC').valueChanges.subscribe(
            (val: any) => {
                this.localStorageService.setItem('sameAsPBC', JSON.stringify(val))
                this.clearPrimaryBuyerSection();
                this.buyerSameAsPrimaryBusiness(val);
                this.updateUserData('purchaser_firstname');
                this.updateUserData('purchaser_lastname');
                this.updateUserData('purchaser_position');
                this.updateUserData('purchaser_phone');
                this.updateUserData('purchaser_email');
            });
    }

    getAccInfo() {

        this.getAccountInfoSubscribe = this.accountInfoService.getAccountInfo()
            .pipe(
                catchError(() => {
                    return throwError(() => new Error('ups sommething happend'));
                })
            )
            .subscribe({
                next: (res: UserDataInterface) => {
                    let response = res;
                    if (response.data.active === 1 && response.data.approved === 1) {
                        this.userData = response.data;
                        this.userData['billing_same_as_legal'] = false;
                        this.userData['status340B'] = false;
                        if (this.userData.legal_zip !== '') {
                            this.userData.legal_zip = this.userData.legal_zip;
                        }
                        if (this.userData.status_340B === 1) {
                            this.userData['status340B'] = true;
                        }
                        if (this.userData.billing_city_state_zip === 'Same as above') {
                            this.userData['billing_same_as_legal'] = true;
                        }
                    }
                    this.setStatesList();
                    this.setBuyingGroupDropdownDefaultValues();
                    this.setBuyingGroupDropDown();
                    this.getOwnerPositions();
                    let supplierArray = ['Wholesaler', 'Manufacturer'];
                    if (supplierArray.indexOf(response.data.ac_name) === -1) {
                        this.setSuppliersList();
                        this.setPMSList();
                    }
                    if (this.userData?.gpo_primary_buying_group_id === null || this.userData?.gpo_primary_buying_group_id === 0) {
                        this.userData.gpo_primary_buying_group_id = '';
                    }
                    if (this.userData?.gpo_secondary_buying_group_id === null || this.userData?.gpo_secondary_buying_group_id === 0) {
                        this.userData.gpo_secondary_buying_group_id = '';
                    }
                    if (this.userData?.secondary_reference_id === null || this.userData?.secondary_reference_id === 0) {
                        this.userData.secondary_reference_id = ''
                    }
                    if (this.userData?.billing_state === null) {
                        this.userData.billing_state = '';
                    }
                    if (this.userData?.officer_position === null) {
                        this.userData.officer_position = '';
                    }
                    this.userStoreInfoFormData.gpo_primary_buying_group_name.patchValue(this.userData?.gpo_primary_buying_group);
                    this.userStoreInfoFormData.gpo_secondary_buying_group_name.patchValue(this.userData?.gpo_secondary_buying_group);
                    this.userStoreInfoFormData.pmsValue.patchValue(this.userData?.tech_reference_name);
                    this.userStoreInfoForm.patchValue(this.userData);
                    var local_sameAsPBC: any = this.localStorageService.getItem('sameAsPBC');
                    if (local_sameAsPBC !== 'null' && local_sameAsPBC !== null && local_sameAsPBC !== 'false') {
                        this.userStoreInfoFormData.sameAsPBC.patchValue(JSON.parse(local_sameAsPBC));
                    }
                    else {
                        this.localStorageService.setItem('sameAsPBC', JSON.stringify(false));
                    }
                    this.changeDetector.detectChanges();
                    let date: any = '';
                    this.utilities.dateFormat = 'dd-mm-yyyy';
                    
                    const stateLicenseExpire = this.utilities.parseLocalDate(
                        this.userData.state_license_expire
                    );
                    if (stateLicenseExpire) {
                        this.userStoreInfoFormData.state_license_expire.setValue(stateLicenseExpire);
                    }

                    const deaLicenseExpire = this.utilities.parseLocalDate(
                        this.userData.dea_license_expire
                    );
                    if (deaLicenseExpire) {
                        this.userStoreInfoFormData.dea_license_expire.setValue(deaLicenseExpire);
                    }

                    const taxExemptExpireDate = this.utilities.parseLocalDate(
                        this.userData.tax_exempt_expire_date
                    );
                    if (taxExemptExpireDate) {
                        this.userStoreInfoFormData.tax_exempt_expire_date.setValue(taxExemptExpireDate);
                    }

                },
                error: (err: HttpErrorResponse) => {
                    this.accountInfoService.errorCallBack(err);
                },
                complete: () => {
                    this.formControlValueChanged();
                    // Check for 350 on page load after patchValue
                    const primary_reference_id = this.userStoreInfoForm.get('primary_reference_id')?.value;
                    if (this.session.is_preview_mode && primary_reference_id == 350) {
                        // Clear the value so the select box shows 'Select One'
                        this.userStoreInfoForm.get('primary_reference_id').setValue('');
                        this.userStoreInfoForm.get('primary_reference_name').setValue('');
                        this.userStoreInfoForm.get('primary_reference_state').setValue('');
                        this.userStoreInfoForm.get('primary_reference_phone').setValue('');
                    }
                }
            });
        this.sessionService.getAuth().then((response) => {
            this.session = this.sessionService.getSession()
        })
    };

    setStatesList() {
        this.getStatesSubscribe = this.accountInfoService.getStates()
            .pipe(
                catchError(() => {
                    return throwError(() => new Error('ups sommething happend'));
                })
            )
            .subscribe({
                next: (res: GetStates) => {
                    this.states = res.data;
                },
                error: (err) => {
                    this.accountInfoService.errorCallBack(err);
                },
                complete: () => { },
            })
    };

    getOwnerPositions() {
        this.getOwnerPositionsSubscribe = this.accountInfoService.getOwnerPositions()
            .pipe(
                catchError(() => {
                    return throwError(() => new Error('ups sommething happend'));
                })
            )
            .subscribe({
                next: (res: OwnerPositions) => {
                    this.ownerPositions = res.data;
                },
                error: (err) => {
                    this.accountInfoService.errorCallBack(err);
                },
                complete: () => { },
            })
    }

    /**
       * Below method is introduced as part of TRX-7349
       * Gets BuyingGroup list values and assign it to this.buyingGroups
       * which will be used to populate Buying Group Dropdown.  
    */
    setBuyingGroupDropDown() {
        this.buyingGroupListSubscribe = this.accountInfoService.buyingGroupList()
            .pipe(
                catchError(() => {
                    return throwError(() => new Error('ups sommething happend'));
                })
            )
            .subscribe({
                next: (res: BuyingGroupListInterface) => {
                    this.buyingGroups = res.data;
                    this.buyingGroupedList = this.setGroupedList(this.buyingGroups);
                },
                error: (err) => {
                    this.accountInfoService.errorCallBack(err);
                },
                complete: () => { },
            })
    };


    validateDateExpire(dateType: string): ValidatorFn {
        return (control: AbstractControl): ValidationErrors | null => {
            const expireDate = control.value;
            const today = new Date();
            today.setHours(0, 0, 0, 0); // normalize time
            
            //If Tax Exempt Expire date is "0000-00-00" then we don't need to validate.
            if (dateType === 'taxExempt' && expireDate === '0000-00-00') {
                return null;
            }

            // 1. Empty value — don't validate yet (let required handle it if needed)
            if (!expireDate) return null;

            // 2. Detect invalid string like "0000-00-00"
            if (control.touched && typeof expireDate === 'string' && expireDate === '0000-00-00') {
                return { invalidDate: true };
            }

            // 3. Convert if string, otherwise assume it's a Date
            const dateToCheck = typeof expireDate === 'string' ? new Date(expireDate) : expireDate;

            // 4. Handle completely invalid date input
            if (control.touched && (Object.prototype.toString.call(dateToCheck) !== '[object Date]' || isNaN(dateToCheck.getTime()))) {
                return { invalidDate: true };
            }

            // 5. Check if the date is in the past
            if (control.touched && dateToCheck < today) {
                return { expired: true };
            }

            return null;
        };
    };

    updateUserData(userEleName: string) {
        if (this.userStoreInfoFormData[userEleName] !== undefined) {
            let field: string = userEleName;
            let isRequired: boolean = this.userStoreInfoFormData[userEleName].hasValidator(Validators.required);
            let userData: any = this.userStoreInfoFormData[userEleName].value;
            if (userEleName == "dea_license_num" || userEleName == "state_license_num") {
                userData = this.userStoreInfoFormData[userEleName].value.toUpperCase();
            }
            if (userEleName == "state_license_expire" || userEleName == "dea_license_expire" || userEleName == "tax_exempt_expire_date") {
                userData = formatDate(userData, 'yyyy-MM-dd', 'en-US');
            }
            let validationErrors: any = this.userStoreInfoFormData[field].errors;
            let requestData: any = [];
            requestData['user_id'] = this.session.user_id;
            var intFields = ['npi_license_num', 'tax_exempt_id', 'gpo_secondary_buying_group_id'];
            if (intFields.includes(userEleName) && (userData === null || userData === '')) {
                userData = 0;
            }
            if (userData !== undefined && validationErrors === null
                && ((userData !== null && userData !== '' && isRequired === true) || (isRequired === false))
            ) {
                if (userEleName === 'status340B' && userData === false) {
                    userData = 0;
                }
                if (userEleName == 'pmsValue' && userData !== 'Other') {
                    userEleName = 'tech_reference_name';
                }
                requestData[userEleName] = userData;
                requestData = this.renameFields(requestData)
                requestData = Object.assign({}, requestData)
                this.saveUserInfoSubscribe = this.accountInfoService.saveUserInfo(requestData)
                    .pipe(
                        catchError(() => {
                            return throwError(() => new Error('ups sommething happend'));
                        })
                    )
                    .subscribe({
                        next: () => {
                        },
                        error: (err: HttpErrorResponse) => {
                            this.accountInfoService.errorCallBack(err);
                            this.userStoreInfoFormData[userEleName].setErrors({ 'serverError': true });
                        },
                        complete: () => {

                        }
                    });
            }
        }
    };
    
    updateGpoNameValidator(fieldPrefix: string) {
        const groupId = this.userStoreInfoForm.get('gpo_'+fieldPrefix+'_buying_group_id')?.value;
        const nameControl = this.userStoreInfoForm.get('gpo_'+fieldPrefix+'_buying_group_name');

        if (!nameControl) return;

        if (groupId == 999999) {
            nameControl.setValidators([Validators.required]);
        } else {
            nameControl.clearValidators();
        }

        nameControl.updateValueAndValidity();
    }

    validateStoreInfo() {
        this.updateGpoNameValidator('primary');
        this.updateGpoNameValidator('secondary');
        Object.values(this.userStoreInfoForm.controls).forEach((control) => {
            (control as AbstractControl).markAsTouched();
            (control as AbstractControl).updateValueAndValidity({ emitEvent: false });
        });
    };

    onCounterChange(counter: boolean) {
        this.isBillingCollapsed = counter;
    }

    setExpandPanelInfo(userEleName: string) {

        // Expand Billing Address Tab
        if (userEleName.indexOf('billing') !== -1) {
            this.isBillingCollapsed = false;
        }

        // Expand Contact Information Tab
        if (userEleName.indexOf('contact') !== -1 ||
            userEleName.indexOf('owner') !== -1 ||
            userEleName.indexOf('purchaser') !== -1 ||
            userEleName.indexOf('officer') !== -1 ||
            userEleName.indexOf('accounting') !== -1) {
            this.isContactCollapsed = false;
        }

        // Expand License Information Tab
        if (userEleName.indexOf('license') !== -1 ||
            userEleName.indexOf('tax') !== -1 || userEleName.indexOf('gpo') !== -1) {
            this.isLicenseCollapsed = false;
        }

        // Expand References Tab
        if (userEleName.indexOf('reference') !== -1 ||
            userEleName.indexOf('pmsValue') !== -1
        ) {
            this.isReferencesCollapsed = false;
        }
    };

    private scrollToFirstInvalidControl() {
        const firstInvalidControl: HTMLElement = this.el.nativeElement.querySelector(
            "form .ng-invalid"
        );

        window.scroll({
            top: this.getTopOffset(firstInvalidControl),
            left: 0,
            behavior: "smooth"
        });
    }

    private getTopOffset(controlEl: HTMLElement): number {
        const labelOffset = 50;
        return controlEl.getBoundingClientRect().top + window.scrollY - labelOffset;
    }

    saveUserStoreInfo() {
        if (this.userStoreInfoForm.valid === false) {
            this.scrollToFirstInvalidControl();
        }
        this.isSaveBtnClicked = true;
        let storeInfo = this.prepareStoreData();

        if (storeInfo !== undefined) {
            this.isBillingCollapsed = false;
            this.isContactCollapsed = false;
            this.isLicenseCollapsed = false;
            this.isReferencesCollapsed = false;
            // To display validation error messages in all sections
            this.validateStoreInfo();
            if (this.userStoreInfoForm.invalid) {
                Object.keys(this.userStoreInfoForm.controls).forEach(key => {
                  const control = this.userStoreInfoForm.get(key);
                  if (control?.invalid) {
                    console.log(`Control '${key}' is invalid.`);
                    console.log('Errors:', control?.errors);
                  }
                });
            }
            if (!this.userStoreInfoForm.invalid) {
                this.saveUserInfoSubscribe = this.accountInfoService.saveUserInfo(storeInfo)
                    .subscribe({
                        next: () => {
                            this.sessionService.reCheckSession();
                            if (this.session.is_buyer) {
                                this.router.navigate(['/market/questionnaire']);
                            }
                            if (this.session.is_supplier) {
                                this.router.navigate(['/market/licenseVerification']);
                            }
                        },
                        error: (err: HttpErrorResponse) => {
                            this.accountInfoService.errorCallBack(err);
                        },
                        complete: () => {

                        }
                    });
            }

        }
    };

    getRequiredAttrValue(elementName: string) {
        let isRequired: boolean = this.userStoreInfoFormData[elementName]?.hasValidator(Validators.required);
        if (isRequired) {
            return true;
        }
        return false;
    };

    prepareStoreData() {

        let storeInfo: any = {
            "legal_company_name": this.userStoreInfoFormData.legal_company_name.value,
            "legal_company_dba": this.userStoreInfoFormData.legal_trade_name.value,
            "xu_website": this.userStoreInfoFormData.website.value,
            "legal_street": this.userStoreInfoFormData.legal_address.value,
            "legal_city": this.userStoreInfoFormData.legal_city.value,
            "legal_state": this.userStoreInfoFormData.legal_state.value,
            "legal_zip": this.userStoreInfoFormData.legal_zip.value,
            "legal_phone": this.userStoreInfoFormData.legal_phone.value,
            "legal_fax": this.userStoreInfoFormData.legal_fax.value,
            "legal_gln_num": this.userStoreInfoFormData.gln_num.value,

            "billing_same_as_legal": this.userStoreInfoFormData.billing_same_as_legal.value,
            "billing_street": this.userStoreInfoFormData.billing_address.value,
            "billing_city": this.userStoreInfoFormData.billing_city.value,
            "billing_state": this.userStoreInfoFormData.billing_state.value,
            "billing_zip": this.userStoreInfoFormData.billing_zip.value,
            "billing_phone": this.userStoreInfoFormData.billing_phone.value,
            "billing_fax": this.userStoreInfoFormData.billing_fax.value,

            "xc_contact_firstname": this.userStoreInfoFormData.contact_firstname.value,
            "xc_contact_lastname": this.userStoreInfoFormData.contact_lastname.value,
            "xc_contact_position": this.userStoreInfoFormData.contact_position.value,
            "xc_contact_phone": this.userStoreInfoFormData.contact_phone.value,
            "xc_contact_email": this.userStoreInfoFormData.contact_email.value,
            "xc_owner_firstname": this.userStoreInfoFormData.owner_firstname.value,
            "xc_owner_lastname": this.userStoreInfoFormData.owner_lastname.value,
            "xc_owner_position": this.userStoreInfoFormData.owner_position.value,
            "xc_owner_phone": this.userStoreInfoFormData.owner_phone.value,
            "xc_owner_email": this.userStoreInfoFormData.owner_email.value,
            "xc_officer_email": this.userStoreInfoFormData.officer_email.value,
            "xc_officer_firstname": this.userStoreInfoFormData.officer_firstname.value,
            "xc_officer_lastname": this.userStoreInfoFormData.officer_lastname.value,
            "xc_officer_position": this.userStoreInfoFormData.officer_position.value,
            "xc_officer_phone": this.userStoreInfoFormData.officer_phone.value,
            "xc_purchaser_firstname": this.userStoreInfoFormData.purchaser_firstname.value,
            "xc_purchaser_lastname": this.userStoreInfoFormData.purchaser_lastname.value,
            "xc_purchaser_position": this.userStoreInfoFormData.purchaser_position.value,
            "xc_purchaser_phone": this.userStoreInfoFormData.purchaser_phone.value,
            "xc_purchaser_email": this.userStoreInfoFormData.purchaser_email.value,
            "xc_accounting_firstname": this.userStoreInfoFormData.accounting_firstname.value,
            "xc_accounting_lastname": this.userStoreInfoFormData.accounting_lastname.value,
            "xc_accounting_position": this.userStoreInfoFormData.accounting_position.value,
            "xc_accounting_phone": this.userStoreInfoFormData.accounting_phone.value,
            "xc_accounting_email": this.userStoreInfoFormData.accounting_email.value,

            "shipping_same_as_legal": true,
            "shipping_state_license_num": this.userStoreInfoFormData.state_license_num.value.toUpperCase(),
            "shipping_dea_license_num": this.userStoreInfoFormData.dea_license_num.value.toUpperCase(),
            "shipping_state_license_expire": formatDate(this.userStoreInfoFormData.state_license_expire.value, 'yyyy-MM-dd', 'en-US'),
            "shipping_dea_expire": formatDate(this.userStoreInfoFormData.dea_license_expire.value, 'yyyy-MM-dd', 'en-US'),
            "xu_tax_reg_number": this.userStoreInfoFormData.tax_reg_number.value,
            "xu_status_340B": this.userStoreInfoFormData.status340B.value === true ? 1 : 0,
            "gpo_primary_buying_group_id": this.userStoreInfoFormData.gpo_primary_buying_group_id.value,
            "gpo_primary_buying_group_name": this.userStoreInfoFormData.gpo_primary_buying_group_name.value,
            "gpo_secondary_buying_group_id": this.userStoreInfoFormData.gpo_secondary_buying_group_id.value,
            "gpo_secondary_buying_group_name": this.userStoreInfoFormData.gpo_secondary_buying_group_name.value,
            "xu_store_info_form": true
        };
        //TRX-7716
        if (this.session.is_buyer === true) {
            storeInfo["legal_tax_exempt_expire_date"] = this.userStoreInfoFormData.tax_exempt_expire_date.value != "0000-00-00" ? formatDate(this.userStoreInfoFormData.tax_exempt_expire_date.value, 'yyyy-MM-dd', 'en-US') : "0000-00-00";
            storeInfo["legal_tax_exempt_id"] = this.userStoreInfoFormData.tax_exempt_id.value;
        }
        storeInfo["legal_npi_license_num"] = this.userStoreInfoFormData.npi_license_num.value;
        if (this.userStoreInfoFormData.npi_license_num.value === '' || this.userStoreInfoFormData.npi_license_num.value === null) {
            storeInfo["legal_npi_license_num"] = 0;
        }

        /*
         * Below conditions added as per TRX-7352,
         * to make sure that we are sending proper value to the endpoint to prevent further issues.
         */
        if (this.userStoreInfoFormData.gpo_primary_buying_group_id.value === '' || this.userStoreInfoFormData.gpo_primary_buying_group_id.value === null) {
            storeInfo["gpo_primary_buying_group_id"] = 0;
        }

        if (this.userStoreInfoFormData.gpo_secondary_buying_group_id.value === '' || this.userStoreInfoFormData.gpo_secondary_buying_group_id.value === null) {
            storeInfo["gpo_secondary_buying_group_id"] = 0;
        }

        var supplierArray = ['Wholesaler', 'Manufacturer'];
        if (supplierArray.indexOf(this.userData.ac_name) === -1) {
            storeInfo['primary_supplier_id'] = this.userStoreInfoFormData.primary_reference_id.value;
            storeInfo['primary_reference_name'] = this.userStoreInfoFormData.primary_reference_name.value;
            storeInfo['primary_state'] = this.userStoreInfoFormData.primary_reference_state.value;
            storeInfo['primary_phone'] = this.userStoreInfoFormData.primary_reference_phone.value;
            storeInfo['secondary_supplier_id'] = this.userStoreInfoFormData.secondary_reference_id.value;
            storeInfo['secondary_reference_name'] = this.userStoreInfoFormData.secondary_reference_name.value;
            storeInfo['secondary_state'] = this.userStoreInfoFormData.secondary_reference_state.value;
            storeInfo['secondary_phone'] = this.userStoreInfoFormData.secondary_reference_phone.value;
            storeInfo['technology_company_name'] = this.userStoreInfoFormData.tech_reference_name.value;
            storeInfo['technology_state'] = this.userStoreInfoFormData.tech_reference_state.value;
            storeInfo['technology_phone'] = this.userStoreInfoFormData.tech_reference_phone.value;
            storeInfo['bank_company_name'] = this.userStoreInfoFormData.bank_reference_name.value;
            storeInfo['bank_state'] = this.userStoreInfoFormData.bank_reference_state.value;
            storeInfo['bank_phone'] = this.userStoreInfoFormData.bank_reference_phone.value;

            if (this.userStoreInfoFormData.pmsValue.value !== 'Other') {
                storeInfo['technology_company_name'] = this.userStoreInfoFormData.pmsValue.value;
            }
        }

        return storeInfo;
    };

    renameFields(data: any) {
        for (let key in data) {
            if (key == 'legal_trade_name') {
                data["legal_company_dba"] = data[key];
                delete data[key];
            }
            if (key == 'website' || key == 'tax_reg_number') {
                data["xu_" + key] = data[key];
                delete data[key];
            }
            if (key == 'legal_address') {
                data["legal_street"] = data[key];
                delete data[key];
            }
            if (key == 'shipping_address') {
                data["shipping_street"] = data[key];
                delete data[key];
            }
            if (key == 'billing_address') {
                data["billing_street"] = data[key];
                delete data[key];
            }
            if (key == 'contact_firstname' || key == 'contact_lastname' || key == 'contact_position' || key == 'contact_phone' || key == 'contact_email' || key == 'owner_firstname' || key == 'owner_lastname' || key == 'owner_position' || key == 'owner_phone' || key == 'owner_email' || key == 'officer_firstname' || key == 'officer_lastname' || key == 'officer_position' || key == 'officer_phone' || key == 'officer_email' || key == 'purchaser_firstname' || key == 'purchaser_lastname' || key == 'purchaser_position' || key == 'purchaser_phone' || key == 'purchaser_email' || key == 'accounting_firstname' || key == 'accounting_lastname' || key == 'accounting_position' || key == 'accounting_phone' || key == 'accounting_email') {
                data["xc_" + key] = data[key];
                delete data[key];
            }
            if (key == 'state_license_num' || key == 'dea_license_num' || key == 'state_license_expire') {
                data["shipping_" + key] = data[key];
                delete data[key];
            }
            if (key == 'dea_license_expire') {
                data["shipping_dea_expire"] = data[key];
                delete data[key];
            }
            if (key == 'status340B') {
                data["xu_status_340B"] = data[key];
                delete data[key];
            }
            if (key == 'tax_exempt_id' || key == 'tax_exempt_expire_date' || key == 'npi_license_num') {
                data["legal_" + key] = data[key];
                delete data[key];
            }
            if (key == 'primary_reference_state' || key == 'primary_reference_phone' || key == 'secondary_reference_state' || key == 'secondary_reference_phone' || key == 'bank_reference_state' || key == 'bank_reference_phone') {
                data[key.replace('_reference', '')] = data[key];
                delete data[key];
            }
            if (key == 'primary_reference_id' || key == 'secondary_reference_id') {
                data[key.replace('_reference', '_supplier')] = data[key];
                delete data[key];
            }
            if (key == 'tech_reference_state' || key == 'tech_reference_phone') {
                data[key.replace('tech_reference', 'technology')] = data[key];
                delete data[key];
            }
            if (key == 'tech_reference_name') {
                data["technology_company_name"] = data[key];
                delete data[key];
            }
            if (key == 'bank_reference_name') {
                data["bank_company_name"] = data[key];
                delete data[key];
            }
            if (key == 'gln_num') {
                data["legal_gln_num"] = data[key];
                delete data[key];
            }
        }
        return data;
    }

    setSuppliersList() {
        this.getSuppliersSubscribe = this.accountInfoService.getSuppliers()
            .pipe(
                catchError(() => {
                    return throwError(() => new Error('ups sommething happend'));
                })
            )
            .subscribe({
                next: (res: SuppliersList) => {
                    this.suppliersList = res.data;
                    this.groupedSuppList = this.setGroupedList(this.suppliersList);
                },
                error: (err: HttpErrorResponse) => {
                    this.accountInfoService.errorCallBack(err);
                },
                complete: () => {

                }
            });
    };

    setPMSList() {
        this.getPmsListSubscribe = this.accountInfoService.getPmsList()
            .pipe(
                catchError(() => {
                    return throwError(() => new Error('ups sommething happend'));
                })
            )
            .subscribe({
                next: (res: any) => {
                    this.pmsList = res.data;
                    if (this.userData.tech_reference_name !== ""
                        && this.userData.tech_reference_name !== null) {
                        var valueIndex = this.pmsList.indexOf(this.userData.tech_reference_name);
                        if (valueIndex === -1) {
                            this.userStoreInfoFormData.pmsValue.value = 'Other';
                        } else {
                            this.userStoreInfoFormData.pmsValue.value = this.pmsList[valueIndex];
                        }
                    }
                },
                error: (err: HttpErrorResponse) => {
                    this.accountInfoService.errorCallBack(err);
                },
                complete: () => { }
            });
    };

    setReferenceTabDropdownDefaultValues() {
        if (this.userData.primary_reference_state === '') {
            this.userData.primary_reference_state = null;
        }
        if (this.userData.secondary_reference_state === '') {
            this.userData.secondary_reference_state = null;
        }
        if (this.userData.tech_reference_state === '') {
            this.userData.tech_reference_state = null;
        }
        if (this.userData.bank_reference_state === '') {
            this.userData.bank_reference_state = null;
        }
        if (this.userData.primary_reference_id === '') {
            this.userData.primary_reference_id = null;
        }
        if (this.userData.secondary_reference_id === '') {
            this.userData.secondary_reference_id = null;
        }
    };

    /**
    * Grouping the Suppliers\Buying groups list based on unique group Name
    */
    setGroupedList(unGroupedList: any[]) {
        this.uniqueValue = [...new Set(unGroupedList.map(item => item.group))];
        this.groupedList = this.uniqueValue.map(group => ({
            name: group,
            values: unGroupedList.filter(d => d.group === group)
        }))
        return this.groupedList;
    };

    /**
      * Below method is introduced as part of TRX-7349
      * Sets Buying group dropdown default value to null to select "Select One" option
    */
    setBuyingGroupDropdownDefaultValues() {
        if (this.userData.gpo_primary_buying_group_id === 0) {
            this.userData.gpo_primary_buying_group_id = null;
        }
        if (this.userData.gpo_secondary_buying_group_id === 0) {
            this.userData.gpo_secondary_buying_group_id = null;
        }
    };

    setLicenseExpireDate(licenseType: string) {
        if (this.userData[licenseType] === '0000-00-00') {
            this.userData[licenseType] = null;
        }
        if (this.userData[licenseType] !== '0000-00-00' && this.userData[licenseType] !== null) {
            var parts = this.userData[licenseType].split('-');
            this.userData[licenseType] = new Date(parts[0], parts[1] - 1, parts[2]);
        }
    };


    updatePMSValue(pmsValue: string, pmsEleName: string) {
        if (pmsValue === 'Other') {
            this.userStoreInfoFormData['tech_reference_name'].value = '';
            if (pmsEleName !== undefined) {
                this.userStoreInfoForm.get(pmsEleName)?.updateValueAndValidity();
            }
        }
    };

    checkForOtherOption(type: string) {
        if (this.userStoreInfoFormData[type + "_reference_id"].value == 999999) {
            this.userStoreInfoFormData[type + "_reference_name"].value = '';
        }
    };

    /**
     * Method clears Primary Buyer Section values
     * before performing any action on Primary Buyer section.
     * @returns {undefined}
     */
    clearPrimaryBuyerSection() {
        this.userStoreInfoForm.patchValue({
            purchaser_firstname: '',
            purchaser_lastname: '',
            purchaser_phone: '',
            purchaser_position: '',
            purchaser_email: '',
        })
    };

    /**
     * Method will check if given parameter i.e, sameAsPBC
     * is true or not.
     * If true, that means User opted to copy data Primary Business Contact
     * to Primary Buyer Section and the data that is given in Primary Business Contact
     * will be copied to Primary Busines Contact section.
     *
     * If false, then method will clear Primary Buyer Validation messages
     * and setting those to false, so that we don't have any issue 
     * while submitting the form.
     *
     * @param boolean sameAsPBC
     * @returns {undefined}
     */
    buyerSameAsPrimaryBusiness(sameAsPBC: boolean) {
        if (sameAsPBC === true) {
            this.clearPrimaryBuyerSection();
            this.userStoreInfoForm.patchValue({
                purchaser_firstname: this.userStoreInfoFormData.contact_firstname.value,
                purchaser_lastname: this.userStoreInfoFormData.contact_lastname.value,
                purchaser_phone: this.userStoreInfoFormData.contact_phone.value,
                purchaser_position: this.userStoreInfoFormData.contact_position.value,
                purchaser_email: this.userStoreInfoFormData.contact_email.value,
            })
        }
    };

    billingSameAsLegalAddr() {
        if (this.userStoreInfoFormData.billing_same_as_legal.value === true) {
            this.clearBillingSection();
            this.userStoreInfoForm.patchValue({
                billing_address: this.userStoreInfoFormData.legal_address.value,
                billing_city: this.userStoreInfoFormData.legal_city.value,
                billing_fax: this.userStoreInfoFormData.legal_fax.value,
                billing_phone: this.userStoreInfoFormData.legal_phone.value,
                billing_state: this.userStoreInfoFormData.legal_state.value,
                billing_zip: this.userStoreInfoFormData.legal_zip.value,
            })
        }
    };

    clearBillingSection() {
        this.userStoreInfoForm.patchValue({
            billing_address: '',
            billing_city: '',
            billing_fax: '',
            billing_phone: '',
            billing_state: '',
            billing_zip: '',
        })
    };

    cityValidationMsg = "Please enter valid Information.";
    phnValidationMsg = "Please enter phone or fax number only.";
    zipValidationMsg = "Please enter valid zip code.";
    emailValidationMsg = "Please enter valid email.";
    generalValidationMsg = "Please enter valid data.";
    selectBoxValidationMsg = "Please select at least one.";

    getValidationMsg(field: string) {

        let err_msg = ''; let err_field_name = field;
        const errors = this.userStoreInfoFormData[field].errors;

        if (errors) {
            if (field == 'legal_company_name') {
                err_field_name = "Business Legal Name";
            }
            if (field == 'legal_trade_name') {
                err_field_name = "Business Trade Name";
            }
            if (field == 'legal_address' || field == 'shipping_address' || field == 'billing_address') {
                err_field_name = "Street";
            }
            if (field == 'legal_city' || field == 'shipping_city' || field == 'billing_city') {
                err_field_name = "City";
            }
            if (field == 'contact_firstname' || field == 'owner_firstname' || field == 'officer_firstname' || field == 'purchaser_firstname' || field == 'accounting_firstname') {
                err_field_name = "First Name";
            }
            if (field == 'contact_lastname' || field == 'owner_lastname' || field == 'officer_lastname' || field == 'purchaser_lastname' || field == 'accounting_lastname') {
                err_field_name = "Last Name";
            }
            if (field == 'contact_position' || field == 'owner_position' || field == 'officer_position' || field == 'purchaser_position' || field == 'accounting_position') {
                err_field_name = "Position";
            }
            if (field == 'contact_email' || field == 'owner_email' || field == 'officer_email' || field == 'purchaser_email' || field == 'accounting_email') {
                err_field_name = "Email";
            }
            if (field == 'tech_reference_name' || field == 'bank_reference_name') {
                err_field_name = "Name";
            }
            if (field == 'primary_reference_name') {
                err_field_name = "Primary Supplier";
            }
            if (field == 'secondary_reference_name') {
                err_field_name = "Secondary Supplier";
            }

            if (errors['maxlength']) {
                err_msg = this.titleCase(err_field_name) + " should not contain more than " + errors['maxlength'].requiredLength + " characters.";
            }
            if (errors['minlength']) {
                err_msg = this.titleCase(err_field_name) + " should contain at least " + errors['minlength'].requiredLength + " characters.";
            }
            if (errors['pattern']) {
                err_msg = "Please enter valid " + err_field_name;
            }
        }
        return err_msg;
    }

    titleCase(s: string) {
        return s.replace(/^[-_]*(.)/, (_, c) => c.toUpperCase()).replace(/[-_]+(.)/g, (_, c) => ' ' + c.toUpperCase())
    }

    /**
     * Check if the current user's account name belongs to supplier or buyer.
     * Returns true if it belongs to a supplier.
     * @returns Boolean
     */
    isSupplier() {
        return this.suppAccNames.includes(this.userData?.ac_name);
    }

    ngOnDestroy() {
        this.getAccountInfoSubscribe?.unsubscribe();
        this.getStatesSubscribe?.unsubscribe();
        this.getOwnerPositionsSubscribe?.unsubscribe();
        this.buyingGroupListSubscribe?.unsubscribe();
        this.saveUserInfoSubscribe?.unsubscribe();
        this.getSuppliersSubscribe?.unsubscribe();
        this.getPmsListSubscribe?.unsubscribe();
        this.sitenameListener.unsubscribe();
    }

}