import { Component, DoCheck, ElementRef, OnInit, EventEmitter, Output, Input, OnChanges, SimpleChanges, ViewChild } from '@angular/core';

import { HttpClient, HttpHeaders, HttpResponse, HttpStatusCode } from '@angular/common/http';
 
import { FormBuilder, FormGroup, FormArray, Validators, AbstractControl, ValidationErrors, ValidatorFn, AsyncValidatorFn } from '@angular/forms';
 
import { NameServerService } from './service/name-server.service';
import { Router } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { DomainService } from '../rgnt-domain/service/domain.service';
import { Domain } from '../model/domain.model';
// import { error } from 'jquery';
// import { HttpStatusCode } from '@angular/common/http';
 
import { UserService } from '../user/service/user.service';
import { debounceTime, firstValueFrom, lastValueFrom, Subject, takeUntil } from 'rxjs';
 
import { AssetService } from '../asset.service';
import { UserDomainService } from '../user-domain-details/service/user-domain.service';
import { Location } from '@angular/common';
import { PreviewService } from '../preview/service/preview.service';
import { OrganisationDetailsService } from '../organisation-details/service/organisation-details.service';
import { DocumentUploadService } from '../document-upload/service/document-upload.service';
import { RegistrationService } from '../registration/service/Registration.service';
import { DnssecDetails } from '../model/DnsSecDetails.model';
import { DnsSecService } from './service/dns-sec.service';
import * as CryptoJS from 'crypto-js';
import { environment } from '../environments/environment';



declare var bootstrap: any;
 
@Component({
    selector: 'app-name-server-form',
    templateUrl: './name-server-form.component.html',
    styleUrls: ['./name-server-form.component.css'],
    standalone: false
})
export class NameServerFormComponent implements OnInit, OnChanges {
  
  @Input() applicationId: string = '';
  @Input() paramValue: number = 0;
  @Input() domainId: number = 0;
  @Input() organisationId: number = 0;
  @Input() nameServerLength:number=0;
  @Output() formSubmitted: EventEmitter<void> = new EventEmitter<void>();
  @Output() back: EventEmitter<void> = new EventEmitter<void>(); // Emit event after form submission
 formSubmittedForDnsSec:boolean=false;
  nameServerForm: FormGroup;
 
  hasNSDetails: boolean = true;
 
  limitofNameServer: number = 0;
  nameIdentifiersList:any[] = [];
  
bankName:string='';
domainName:string='';
  signatureVerified: boolean | null = null;
lastSignedHash: string | null = null;
tokens: any[] = [];
certificates: any[] = [];
tokenPassword = '';
passwordErrorMessage = '';
  isSigned= false;
  // isLoading : boolean = false;
  
modalInstance: any;
 dataTypes: string[] = [
    'TextPKCS7',
    'TextPKCS1',
    'XML',
    'Sha256HashPKCS7',
    'Sha256HashPKCS1',
    'TextPKCS7ATTACHED'
  ];
  selectedToken: any = "";
  selectedCertificate: any = "";
  selectedDataType: string = '';
  embridgeUrl = 'https://localhost.emudhra.com:26769';
  dscApi = environment.apiURL;
  enable: boolean = true;
  constructor(
    private fb: FormBuilder,
    private previewService: PreviewService,
    private location: Location,
    private nameServerService: NameServerService,
    private router: Router,
    private toastr: ToastrService,
    private domainService:DomainService,
    private userDomainService: UserDomainService,
    private userService: UserService,
    private assetService:AssetService,
    private organizationService:OrganisationDetailsService,
    private documentService:DocumentUploadService,
    private registrationService:RegistrationService,
    private dnsSecService: DnsSecService,
    private http: HttpClient,
 
  ) {
    
    if(this.organisationId < 1 || this.organisationId == null || this.organisationId == undefined){
      this.organisationId = this.router.getCurrentNavigation().extras?.state['organisationId'];
    }
    if(this.applicationId != ''){
      this.applicationId = this.router.getCurrentNavigation().extras?.state['applicationId'];
    //console.log(this.applicationId)
    }
    if(this.domainId < 1 || this.domainId == undefined || this.domainId == null){
    //console.log("entered inside constructor")
      this.domainId = this.router.getCurrentNavigation().extras?.state['domainId'];
    //console.log(this.domainId)
    }
    this.nameServerLength=this.nameServerLength?this.nameServerLength:this.router.getCurrentNavigation().extras?.state['nameServerLength']
    //console.log(this.nameServerLength)
    this.limitofNameServer = this.router.getCurrentNavigation().extras?.state['limitOfNameServers'] || 0;

    //console.log("limit of name server "+this.limitofNameServer)
    this.nameServerForm = this.fb.group({
  hasNSDetails: ['yes', Validators.required],
  nameServers: this.fb.array([], [this.validateDualIPs()]) // validator goes here
});
   
  }

  @Input() currentStep: number;

  async ngOnChanges(changes: SimpleChanges) {
    //console.log('ewxe ng Onchnages')
      if(changes['currentStep']?.currentValue==2){
         //console.log('ewxe ng Onchnages')
        
        await this.getLoggedInUserDetails();
         
        this.getDomainDetailsByUserId();
         await this.fetDomainsOfOrganization(this.organisationId);
        // sessionStorage.setItem('loadedNameServer',"active");
   
        await this.getDomainDetails();
        this.getNameServerCountOfDomain(this.domainId);
      }
      if(changes['paramValue']){
       //console.log("entered patam bvaej")
        this.domainId = this.paramValue;
        // this.getDomainDetails();
        // await this.fetDomainsOfOrganization(this.organisationId);
        
      //console.log(this.paramValue+" "+this.domainId)
      }
  }

  async getDomainDetailsByUserId(){
    await lastValueFrom(this.userDomainService.getDomainDataByOnboardingStatus(this.user.userId,true)).then(
      (response)=>{
          this.domain=response.body;
         //console.log(this.domain)
      },(error)=>{
          if(error.status==HttpStatusCode.Unauthorized){
              this.navigateToSessionTimeOut();
          }
      }
  )
 }

  
 
  loggedInUserEmail: string = localStorage.getItem('email');
  user: any = null;
  async getLoggedInUserDetails() {
  //console.log('email: ' + this.loggedInUserEmail);
    await lastValueFrom(this.userService.getUserByEmailId(this.loggedInUserEmail)).then(
      (response) => {
        if (response.status === HttpStatusCode.Ok) {
          this.user = response.body;
         //console.log(this.user);
          this.organisationId = this.user.organisationId;
          this.fetchOrganizationDetails(this.organisationId);
         // this.fetchOrgDocs(this.organisationId);
          this.fetchThePriceDetails();
        //console.log(this.organisationId);
        }
      },
      (error) => {
        //console.log(error)
        if (error.status === HttpStatusCode.Unauthorized) {
          this.router.navigateByUrl("/session-timeout");
        }
      },
    );
  }
 
  domainsOfOrg: any = [];
  async getDomainsByOrgId(){
   //console.log(this.organisationId)
    await lastValueFrom(this.domainService.getAllDomainsByOrgId(this.organisationId)).then(
      (response)=>{  
      //console.log(response.body)
        this.domainsOfOrg=response.body;
        response.body.forEach(domain=>{
          if(domain.isOnboardingDomain === true){
          //console.log('executed')
            this.domainId=domain.domainId;
          //console.log(this.domainId)
          }
        });
      //console.log(this.domainId)
      }
    );
    return this.domainsOfOrg;
  }
 
  async ngOnInit() {
    await this.getLoggedInUserDetails();
     await this.getDomainDetails();
      await this.getDnsDigestType();
    await this.getDnsAlgorithmType();
     this.getAllStaticData();
      this.getStaticDataForTds();
      this.getOrgTaxDetails();
      this.getNameServerCountOfDomain(this.domainId);
   //console.log("domainId---------------"+this.domainId);
    //console.log(this.organisationId)
    //console.log(this.applicationId);
    // if(sessionStorage.getItem(''))
    // await this.fetDomainsOfOrganization(this.organisationId);
    
   
   
    // await this.fetDomainsOfOrganization(this.organisationId);
    // this.fetchThePriceDetails();
    const state = history.state;
    this.nameIdentifiersList = state.nameIdentifiersList || [];
    this.bankName = state.bankName;
    this.domainName = state.domainName;
    this.nameServerForm.get('hasNSDetails')?.valueChanges.subscribe((value) => {
      this.hasNSDetails = value === 'yes';
 
      if (this.hasNSDetails && this.nameServers.length === 0) {
        // this.addNameServer();
      } else if (!this.hasNSDetails) {
        this.clearAllNameServers();
      }
    });
    this.nameServers.controls.forEach((server: FormGroup) => {
      server.get('hostName')?.valueChanges.subscribe(() => {
        this.revalidateHostnames();
      });
    });

    this.nameServers.controls.forEach(control => {
  control.get('ipAddress')?.valueChanges.subscribe(() => {
    this.nameServers.updateValueAndValidity();
  });

  control.get('ipv6Address')?.valueChanges.subscribe(() => {
    this.nameServers.updateValueAndValidity();
  });
});
      this.submitNsClickSubject.pipe(
      debounceTime(this.DEBOUNCE_TIME),
      takeUntil(this.destroy$)
      ).subscribe(() => {
       this.onSubmit(); 
      });
  }
   ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
  }
 onButtonClickForSave(): void {
    // Check the button's disabled conditions.
    // If the button is *not* disabled (by form invalidity or loading state),
    // then trigger the debounce.
    const isButtonCurrentlyDisabled = this.nameServerForm.invalid || this.isLoading;

    if (!isButtonCurrentlyDisabled) {
      this.submitNsClickSubject.next(); // Push a value to the subject to start the debounce timer
    } else {
      // If the button is disabled due to form invalidity, mark as touched to show errors immediately.
      if (this.nameServerForm.invalid) {
        this.nameServerForm.markAllAsTouched();
        // this.toastr.warning('Please fill all required fields correctly.');
      }
      // If disabled due to isLoading, no extra toast needed as spinner indicates action.
    }
  }


 isChrome(): boolean {
        return this.assetService.isChrome();
      }
      isEdge():boolean{
        return this.assetService.isEdge();
      }


// async onButtonClickForSave(): Promise<void> {

//   const isButtonCurrentlyDisabled = this.nameServerForm.invalid || this.isLoading;

//   if (isButtonCurrentlyDisabled) {
//     this.nameServerForm.markAllAsTouched();
//     return;
//   }

//   await this.onSubmit();   // 🔥 DIRECT CALL (NO SUBJECT)
// }

  countOfNameServer:number=0
  nameServersOfOrg:any
  gstPercentage:number=0
  async fetchnameServerofOrg(organisationId) {
    try {
      const result = await lastValueFrom(this.nameServerService.getNameServersByOrgId(organisationId));
      
      this.nameServersOfOrg= result.body; // Return the result
    } catch (error) {
      //  Handle errors here.  Important to catch errors.
      //console.error("Error fetching name servers:", error);
      // throw error; //  Re-throw the error to be handled by the caller, or handle it.
    }
  }
  countOfDomains:number=0
 async fetDomainsOfOrganization(organisationId: number): Promise<void> {
  try {
    if (organisationId !== 0) {
      const result = await lastValueFrom(this.domainService.getAllDomainsByOrgId(organisationId));
      await this.fetchnameServerofOrg(this.organisationId);
      //console.log("Domains:", result);
      this.countOfDomains = result.body.length;
    } else {
      this.countOfDomains = 1; // Assuming a default count if organisationId is 0
    }

    // Always add two name servers based on the new requirement
    this.addNameServer();
    this.addNameServer();

    //console.log(this.nameServerLength + "nameserverlength");
    //console.log(this.nameServerLength === 0, this.nameServerLength === undefined, this.countOfDomains === 1);
  } catch (error) {
    //console.error("Error fetching domains:", error);
    throw error;
  }
}
  domain:Domain= new Domain();
  domainCost:number=0;
  aliasCost:number=0;
  enableBackButton:boolean=false;
  nsRecordTotalPrice:number=0;
  async getDomainDetails(){
    //console.log(this.domainId)
    await this.getDnsSecDetailsByDomainId(this.domainId);
    await lastValueFrom(this.domainService.getDomainByDomainId(this.domainId)).then(
      (response)=>{
        this.domain=response.body;
        this.nsRecordTotalPrice=this.domain.nsRecordPrice? this.domain.nsRecordPrice : 0;
        //console.log(this.domain)
         if(this.domain.isOnboardingDomain==false&&this.domain.isOnboardingDomain!=undefined){
       this.fetDomainsOfOrganization(this.organisationId);
      this.enableBackButton=true;
    }else{
      //console.log(this.domain.isOnboardingDomain==true,this.domain.isOnboardingDomain==true,this.domain.applicationStatus=='Incomplete')
      if(this.domain.isOnboardingDomain==true && this.domain.applicationStatus!='Incomplete' &&(this.domain.applicationStatus!=null&&this.domain.applicationStatus!=undefined)){
             this.fetDomainsOfOrganization(this.organisationId);
         this.enableBackButton=true;
      }
    }
        this.domainCost=this.domain.domainPrice
        this.aliasCost=this.domain.aliasPrice
        this.getNsRecordOfDomain();
        this.fetchThePriceDetails();
        //console.log(this.domain)
      },(error)=>{
        if(error.status===HttpStatusCode.Unauthorized){
          this.navigateToSessionTimeOut();
        }
    })
  }
  nsRecordList:any
  nsRecordHostNames:string[]=[]
  countWithBothIPv4AndIPv6:number=0;
  async getNsRecordOfDomain(){
    await lastValueFrom(this.nameServerService.getNameServersByDomainId(this.domain.domainId)).then(
      (response)=>{
        this.nsRecordList=response.body;
        //console.log(this.nsRecordList+"------------"+"nsrecordlist")
        this.nsRecordList.forEach(nsrecord=>{
          this.nsRecordHostNames.push(nsrecord?.hostName)
        })
//         this.countWithBothIPv4AndIPv6 = this.nsRecordList.filter(ns =>
//   !!ns.ipAddress && !!ns.ipv6Address
// ).length;
        //console.log(response)
      },(error)=>{
        if(error.status===HttpStatusCode.Unauthorized){
          this.navigateToSessionTimeOut();
        }
    }
    )
  }

  revalidateHostnames() {
    this.nameServers.controls.forEach((server: FormGroup) => {
      server.get('hostName')?.updateValueAndValidity({ emitEvent: false });
    });
  }
  navigateToSessionTimeOut(){
    this.router.navigateByUrl("/session-timeout")
  }
  get nameServers(): FormArray {
    return this.nameServerForm.get('nameServers') as FormArray;
  }



  getIPAddressRequiredState(isIPV6: false) {
    
  }
 
  createNameServer(): FormGroup {
    //console.log(this.domainId)
    
    return this.fb.group({
      organisationId: this.organisationId,
      applicationId: this.applicationId,
      domainId: this.domainId,
      userMailId: localStorage.getItem('email'),
       
         hostName: [
        '',
        [
          Validators.required,
          this.hostNameValidator(),
          this.uniqueHostNameValidator.bind(this) // Apply the custom validator here
        ]
      ],
      ipAddress: [
        '',
        [
          // Validators.required,
          Validators.pattern(
            /^(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)$/
          ),
          this.uniqueIpAddressValidator.bind(this),
        ],
        [this.ipAddressUsedByOtherDomainValidator()] // Move it here!
      ],
      ipv6Address: [
  '',
  [
    Validators.pattern(
      /^(([0-9a-fA-F]{1,4}:){7}([0-9a-fA-F]{1,4}|:)|(([0-9a-fA-F]{1,4}:){6}(:[0-9a-fA-F]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-fA-F]{1,4}:){5}(((:[0-9a-fA-F]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-fA-F]{1,4}:){4}(((:[0-9a-fA-F]{1,4}){1,3})|((:[0-9a-fA-F]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-fA-F]{1,4}:){3}(((:[0-9a-fA-F]{1,4}){1,4})|((:[0-9a-fA-F]{1,4}){0,1}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-fA-F]{1,4}:){2}(((:[0-9a-fA-F]{1,4}){1,5})|((:[0-9a-fA-F]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-fA-F]{1,4}:){1}(((:[0-9a-fA-F]{1,4}){1,6})|((:[0-9a-fA-F]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-fA-F]{1,4}){1,7})|((:[0-9a-fA-F]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/
    ),
    this.uniqueIpV6AddressValidator.bind(this),
  ],
  [this.ipAddressUsedByOtherDomainValidatorIpv6()]
],
      dnsServiceProvider:[
        '',
        [
          Validators.required,this.alphabetValidator
          // this.uniqueHostNameValidator.bind(this) // Apply the custom validator here
        ]
      ],
      ipServiceProvider:[
        '',
        [
          Validators.required,this.alphabetValidator
          // this.uniqueHostNameValidator.bind(this) // Apply the custom validator here
        ]
      ]
    },{ validators: [this.atLeastOneIpRequiredValidator().bind(this)] })
  }

   atLeastOneIpRequiredValidator(): ValidatorFn {
  return (group: AbstractControl): ValidationErrors | null => {
    const ip = group.get('ipAddress')?.value;
    const ipv6 = group.get('ipv6Address')?.value;

    if (!ip && !ipv6) {
      return { atLeastOneIpRequired: true };
    }

    return null;
  };
}

  validateDualIPs(): ValidatorFn {
  return (control: AbstractControl): ValidationErrors | null => {
    const formArray = control as FormArray;
    if (!formArray || !(formArray instanceof FormArray)) return null;

    // Reset ONLY our custom validation error, not others
    formArray.controls.forEach(ctrl => {
      const fg = ctrl as FormGroup;
      ['ipAddress', 'ipv6Address'].forEach(field => {
        const currentControl = fg.get(field);
        if (!currentControl) return;

        const errors = currentControl.errors;
        if (errors) {
          delete errors['tooManyDualIPs']; // remove our custom error only
          if (Object.keys(errors).length === 0) {
            currentControl.setErrors(null);
          } else {
            currentControl.setErrors(errors); // keep other errors
          }
        }
      });
    });

    // Count how many have both IPs
    let dualGroups: FormGroup[] = [];
    for (const group of formArray.controls) {
      const fg = group as FormGroup;
      const ip = fg.get('ipAddress')?.value;
      const ipv6 = fg.get('ipv6Address')?.value;

      if (ip && ipv6) {
        dualGroups.push(fg);
      }
    }

    const existingDualCount = this.nsRecordList?.filter((ns: any) => ns.ipAddress && ns.ipv6Address)?.length ?? 0;
    const totalDual = dualGroups.length + existingDualCount;

    if (totalDual > this.minimumCombinedIPS) {
      const excess = totalDual - this.minimumCombinedIPS;
      const lastExcessGroups = dualGroups.slice(-excess);

      lastExcessGroups.forEach(group => {
        ['ipAddress', 'ipv6Address'].forEach(field => {
          const control = group.get(field);
          if (!control) return;

          const prevErrors = control.errors || {};
          control.setErrors({ ...prevErrors, tooManyDualIPs: true });
        });
      });

      return { tooManyDualIPs: true };
    }

    return null;
  };
}
 
  hostNameValidator(): ValidatorFn {
  return (control: AbstractControl): { [key: string]: any } | null => {
    const value = control.value.trim();
    //console.log('hostNameValidator called with value:', value);

    if (!value) {
      //console.log('Value is empty or null');
      return null;
    }

    // Rule 1: Valid characters (letters, numbers, hyphens, underscores, spaces)
    // IMPORTANT: Hostnames typically DO NOT allow spaces.
    // If you intend for this to be a strict hostname validator,
    // consider changing the regex to /^[a-zA-Z0-9-_]+$/
    // For now, keeping your provided regex /^[a-zA-Z0-9-_ ]+$/
    const validCharactersRegex = /^[a-zA-Z0-9-]+$/;
    if (!validCharactersRegex.test(value)) {
      //console.log('Invalid characters detected:', value);
      return { invalidCharacters: { value: value } };
    }

    // Rule 2: No leading or trailing hyphens or underscores
    if (value.startsWith('-') || value.endsWith('-')) {
      //console.log('Invalid start/end character (hyphen or underscore):', value);
      return { invalidStartEndCharacter: { value: value } }; // Changed error key for clarity
    }

    // Rule 3: No two or more consecutive hyphens
    const consecutiveHyphensRegex = /--+/;
    if (consecutiveHyphensRegex.test(value)) {
      //console.log('Consecutive hyphens detected:', value);
      return { consecutiveHyphens: { value: value } };
    }

    // Rule 5: No hyphens in the third and fourth positions unless it's a punycode prefix (xn--)
    if (value.length >= 4 && !value.startsWith('xn--')) {
      const thirdAndFourth = value.substring(2, 4);
      if (thirdAndFourth === '--') {
        //console.log('Invalid third/fourth hyphen:', value);
        return { invalidThirdFourthHyphen: { value: value } };
      }
    }

    //console.log('Validation passed:', value);
    return null;
  };
}
 
 // Updated Unique IP Address Validator
uniqueIpAddressValidator(control: AbstractControl): ValidationErrors | null {
  const ipAddress = control.value;

  // 👉 Skip validation if field is empty (avoid showing duplicate error)
  if (!ipAddress || ipAddress.trim() === '') {
    return null;
  }

  // 🔍 Check if there's any other form group with the same IP address
  const duplicate = this.nameServers.controls.some((server: FormGroup) => {
    return server !== control.parent &&
           server.get('ipAddress')?.value === ipAddress;
  });

  // 🚫 Return error if duplicate found
  if (duplicate) {
    return { duplicateIpAddress: true };
  }

  return null; // ✅ No duplicates
}

uniqueIpV6AddressValidator(control: AbstractControl): ValidationErrors | null {
  const ipAddress = control.value;

  // 👉 Skip validation if the field is empty
  if (!ipAddress || ipAddress.trim() === '') {
    return null;
  }

  // 🔍 Check if any other form group has the same IPv6 address
  const duplicate = this.nameServers.controls.some((server: FormGroup) => {
    return server !== control.parent &&
           server.get('ipv6Address')?.value === ipAddress;
  });

  if (duplicate) {
    return { duplicateIpv6Address: true };
  }

  return null; // ✅ No duplicates found
}
 
uniqueHostNameValidator(control: AbstractControl): ValidationErrors | null {
  const hostName = control.value;

  if (this.nsRecordHostNames.length !== 0) {
    //console.log(this.nsRecordHostNames);
  }

  // Check for duplicates within the form array
  const duplicateInForm = this.nameServers.controls.some((server: FormGroup) => {
    return server.get('hostName')?.value.toLowerCase() === hostName.toLowerCase() && server !== control.parent;
  });

  // Check for duplicates in the external array
  const duplicateInExternal = this.nsRecordHostNames.some((externalHostName: string) => {
    return externalHostName.toLowerCase() === hostName.toLowerCase();
  });

  // Return error if duplicate is found in either the form or the external array
  if (duplicateInForm || duplicateInExternal) {
    return { duplicateHostName: true };
  }

  return null; // No duplicates found
}
ipAddressUsedByOtherDomainValidator(): AsyncValidatorFn {
  return (control: AbstractControl): Promise<ValidationErrors | null> => {
    if (!control.value) {
      return Promise.resolve(null);  // No validation if there's no value
    }

    const ipToCheck = control.value;

    // If the IP address length is less than 11, skip the validation
    if (control.value.length < 7) {
      return Promise.resolve(null);  // No validation needed
    }

    // Use lastValueFrom to handle Observable to Promise conversion
    return lastValueFrom(this.previewService.validateIpAdresses(ipToCheck)).then((existsForDomain) => {
      if (existsForDomain) {
        return { ipAddressUsed: true };  // Error object if IP is already used
      }
      return null;  // No errors if IP address is not in use
    }).catch((error) => {
      //console.error('Error validating IP address:', error);
      // if(error.ok==false&& error.status==400){
      //console.log("prohibited")
      // }
      return { ipAddressUsed: true };  // Handle any server errors
    });
  };
}

ipAddressUsedByOtherDomainValidatorIpv6(): AsyncValidatorFn {
  return (control: AbstractControl): Promise<ValidationErrors | null> => {
    if (!control.value) {
      return Promise.resolve(null);  // No validation if there's no value
    }

    const ipToCheck = control.value;

    // If the IP address length is less than 11, skip the validation
    if (control.value.length < 7) {
      return Promise.resolve(null);  // No validation needed
    }

    // Use lastValueFrom to handle Observable to Promise conversion
    return lastValueFrom(this.previewService.validateIpv6Adresses(ipToCheck)).then((existsForDomain) => {
      if (existsForDomain) {
        return { ipv6AddressUsed: true };  // Error object if IP is already used
      }
      return null;  // No errors if IP address is not in use
    }).catch((error) => {
      //console.error('Error validating IP address:', error);
      // if(error.ok==false&& error.status==400){
      //console.log("prohibited")
      // }
      return { ipv6AddressUsed: true };  // Handle any server errors
    });
  };
}
 
price:number=0
priceforNameServer:number=0;
addNameServer(): void {
  //console.log("entered add name servers");
  //console.log("count of domain" + this.countOfDomains);
  //console.log("free ns recyuy" + this.freeNSRecord);

  // Calculate the current total potential name servers.
  // This 'total' includes name servers already in the array plus any from 'nameServerLength'.
  const total = (this.nameServers?.length ?? 0) + (this.nameServerLength ?? 0);
  //console.log(total + " " + this.maxNsRecord);

  // Determine if adding a name server is allowed based on limitofNameServer
  // and maxNsRecord.
  let canAdd = false;

  if (this.limitofNameServer === undefined || this.limitofNameServer === null || this.limitofNameServer <= 0) {
    // If limitofNameServer is not set, 0, or less (no specific limit imposed)
    // then only check against maxNsRecord.
    if (total < this.maxNsRecord) {
      canAdd = true;
    }
  } else {
    // If limitofNameServer is a positive value (a specific limit is imposed)
    // then check against both the current count and maxNsRecord.
    if ((this.nameServers?.length ?? 0) < this.limitofNameServer && total < this.maxNsRecord) {
      canAdd = true;
    }
  }

  if (canAdd) {
    this.nameServers.push(this.createNameServer());
    // this.validateDualIPs(); 

    // Pricing logic remains as per your original structure,
    // applied after a name server has been successfully added.
    if (this.limitofNameServer === undefined || this.limitofNameServer === null || this.limitofNameServer <= 0) {
      // If no specific limit, check for free name servers remaining
      //console.log(this.orgDetails)
      if ((this.nameServers?.length ?? 0) > (this.orgDetails?.remainingFreeNameServers ?? 0)+(this.domain?.remainingPurchasedNameServers ?? 0)) {
        //console.log("Price change or entered for the second and later domain");
        this.price += this.priceforNameServer;
      }
    } else {
      // If limitofNameServer is active, set price to 0 (as per your current logic)
      this.price = 0;
    }
  } else {
    //console.log("Cannot add more name servers. Limit reached (either maxNsRecord or limitofNameServer).");
  }
}
 
async removeLastNameServer(index: number) {
  //console.log("Initial nameServers length:", this.nameServers.length);

  // Prevent removing the last remaining name server
  if (this.nameServers.length <= 1) {
    //console.warn("Cannot remove: Only one name server remaining.");
    return;
  }

  const domainCount = Number(this.countOfDomains) || 0;
  const previousEffectiveLength = this.nameServers.length + (this.nameServerLength || 0);
  //console.log(`domainCount: ${domainCount}, effectiveLength: ${previousEffectiveLength}`);
  if(this.limitofNameServer==0 || this.limitofNameServer==null || this.limitofNameServer==undefined){
  // Determine if removal is allowed
  const canRemove = domainCount > 1
    ? previousEffectiveLength > 2
    : previousEffectiveLength > 2;

  if (!canRemove) {
    //console.warn("Removal not allowed based on domain count and effective length.");
    return;
  }

  // Perform removal
  //console.log(`Removing name server at index: ${index}`);
  this.nameServers.removeAt(index); // For FormArray; use splice(index, 1) if it's a regular array
  //console.log("After removal, nameServers length:", this.nameServers.length);

  // Decide on price reduction
  const shouldReducePrice = this.nameServers.length >= this.orgDetails.remainingFreeNameServers+(this.domain?.remainingPurchasedNameServers ?? 0)
  //console.log(`shouldReducePrice: ${shouldReducePrice}, remainingFreeNameServers: ${this.orgDetails.remainingFreeNameServers}`);

  if (shouldReducePrice) {
    this.price -= this.priceforNameServer;
    //console.log(`Price reduced by ${this.priceforNameServer}. New price: ${this.price}`);
  } else {
    //console.log("Price reduction not applied.");
  }
}else{
   const canRemove = domainCount > 1
    ? previousEffectiveLength > 2
    : previousEffectiveLength > 2;

  if (!canRemove) {
    //console.warn("Removal not allowed based on domain count and effective length.");
    return;
  }

  // Perform removal
  //console.log(`Removing name server at index: ${index}`);
  this.nameServers.removeAt(index); // For FormArray; use splice(index, 1) if it's a regular array
  //console.log("After removal, nameServers length:", this.nameServers.length);

  // Decide on price reduction
  const shouldReducePrice = this.nameServers.length>this.limitofNameServer

  if (shouldReducePrice) {
    this.price -= this.priceforNameServer;
    //console.log(`Price reduced by ${this.priceforNameServer}. New price: ${this.price}`);
  } else {
    //console.log("Price reduction not applied.");
  }
}
}
  updatePrice(){
    if(this.nameServers?.length+this.nameServerLength>0){
      //  this.fetchThePriceDetails();
      //console.log(this.price,this.domainId);
    }
  }

  nameServerCount: number = 0;
  async getNameServerCountOfDomain(domainId: number){
    const response =  await lastValueFrom(this.nameServerService.getNameServersByDomainId(this.domainId));
    if(response.status === HttpStatusCode.Ok){
      this.nameServerCount = response.body.length;
      //console.log(this.nameServerCount);
    }

  }
 
  clearAllNameServers(): void {
    while (this.nameServers.length > 2) {
      this.nameServers.removeAt(this.nameServers.length - 1);
    }
  }

  routeBack(){
    this.location.back();
  }
 
  goBack(): void {
    this.back.emit();
  }
  errorMessage='';
  isSubmitDisabled = false;
  isLoading = false;
  private submitNsClickSubject = new Subject<void>();
  private destroy$ = new Subject<void>();
  private readonly DEBOUNCE_TIME = 1000; // Debounce time in milliseconds

  async onSubmit() {
    this.isLoading = true;

    //console.log(this.orgDetails.remainingFreeNameServers);
    // return
   // await this.getLoggedInUserDetails();
   

    await this.getDomainsByOrgId();
    //console.log(this.domain)
    //console.log(this.paramValue+" "+this.domainId)
    if (this.paramValue > 0) {
        this.domainId = this.paramValue;
    }
    if (this.nameServerForm.invalid) {
        this.nameServerForm.markAllAsTouched();
        return;
        // alert('Please fill all required fields.');
    } else {
        const formData = {
            nameServers: this.nameServerForm.value.nameServers,
        };
        formData.nameServers.forEach((element: any) => { // Added : any for type safety
            element.domainId = this.domainId;
            element.organisationId = this.organisationId;
            element.applicationId = this.applicationId;
            element.createdByEmailId=this.loggedInUserEmail;
        });
        //console.log("entered to thus "+" "+(this.orgDetails.remainingFreeNameServers==null)+"---"+(this.orgDetails.remainingFreeNameServers!<1))
        if (this.orgDetails.remainingFreeNameServers == null || this.orgDetails.remainingFreeNameServers > 0) {

            //console.log("entered to this"+ formData.nameServers.length);
            if (this.orgDetails.remainingFreeNameServers > 0) {
                const nameserversSubmitted = formData.nameServers.length;

                // Calculate how many free nameservers can actually be used in this transaction.
                // This will be the minimum of the submitted nameservers and the remaining free ones.
                const freeNameserversToUse = Math.min(nameserversSubmitted, this.orgDetails.remainingFreeNameServers);

                // Update the count of free nameservers used by adding the amount actually utilized.
               this.domain.countOfFreeNameServersUsed += freeNameserversToUse;

               //new code from here 


            }
            if (this.orgDetails.remainingFreeNameServers != null && this.orgDetails.remainingFreeNameServers != 0) {
                //console.log("entered inside the null",this.freeNSRecord,formData.nameServers.length)
                this.orgDetails.remainingFreeNameServers = Math.max(0, this.orgDetails.remainingFreeNameServers - (formData.nameServers.length));
            }
            if (this.orgDetails.remainingFreeNameServers < 0) {
                this.orgDetails.remainingFreeNameServers = 0;
            }

        }
        if ((this.domain.remainingPurchasedNameServers ?? 0) > 0 && this.orgDetails.remainingFreeNameServers === 0) {
            this.domain.remainingPurchasedNameServers = Math.max(
                0,
                this.domain.remainingPurchasedNameServers - formData.nameServers.length
            );
        }

        try {
          
            const response = await lastValueFrom(this.nameServerService.addNameServer(formData));

            // (response) => { ... } logic
            console.log(response);
            if (response != null) {


                  // await this.updateUserOrgDetailsAndDomainPrice(this.user.organisationId,this.domain.domainId);
                  await this.updateUserOnboardingStep();
             
               
                   await this.updateOrganisation(this.orgDetails);
             
             
                  // await this.updatePriceForDomain(this.domain);
              
                  await this.saveDNSSecRecords();
                this.toastr.success("Name servers added successfully");
                //console.log(this.domain,this.price)


                //console.log(this.nameServerLength)
                this.formSubmitted.emit();
                this.isLoading = false;
                // if (this.nameServerLength > 0) {
                //     this.router.navigateByUrl("/domain-details?domainId=" + this.domainId).then(() => {
                //         this.location.replaceState("/domain-details?domainId=" + this.domainId);
                //     });

                // }
                this.router.navigateByUrl('/rgnt-domains').then(() => {
    this.location.replaceState('/rgnt-domains');
});
                //console.log(this.assetService.getPreviousUrl())
                if (this.assetService.getPreviousUrl() == '/add-domain') {
                    this.router.navigateByUrl('/rgnt-domains');
                }
            }
        } catch (error) {
            // (error) => { ... } logic
            this.isLoading = false; // Stop loading state
            // Handle error here
            //console.log(error);
            this.isSubmitDisabled = false;
            this.toastr.error("Address is Reserved");

            //console.error('Error submitting form:', error);
        }
    }
    // Moved the final this.isLoading = false; outside the else block, 
    // but the logic inside the try/catch already handles setting it to false.
    // However, if the logic above failed before the try/catch, this would catch it.
    // In the original code, it was unreachable if nameServerForm.invalid was true.
    this.isLoading = false;
}

//new
// async onSubmit(): Promise<void> {
//   console.log("🚀 onSubmit START");

//   this.isLoading = true;

//   try {
//     console.log("📡 Fetching domains by OrgId...");
//     await this.getDomainsByOrgId();

//     console.log("📌 ParamValue:", this.paramValue);

//     if (this.paramValue > 0) {
//       this.domainId = this.paramValue;
//     }

//     console.log("📌 Final Domain ID:", this.domainId);

//     // ❌ FORM INVALID
//     if (this.nameServerForm.invalid) {
//       console.warn("❌ Form INVALID", this.nameServerForm.value);
//       this.nameServerForm.markAllAsTouched();
//       this.isLoading = false;
//       return;
//     }

//     console.log("✅ Form VALID", this.nameServerForm.value);

//     const formData = {
//       nameServers: this.nameServerForm.value.nameServers,
//     };

//     console.log("📦 Raw Form Data:", JSON.stringify(formData));

//     // ✅ Attach identifiers
//     formData.nameServers.forEach((element: any, index: number) => {
//       element.domainId = this.domainId;
//       element.organisationId = this.organisationId;
//       element.applicationId = this.applicationId;
//       element.createdByEmailId = this.loggedInUserEmail;

//       console.log(`🔧 NS[${index}] Prepared:`, element);
//     });

//     // 🔥 CALL API
//     console.log("📡 Calling addNameServer API...");
//     const response = await lastValueFrom(
//       this.nameServerService.addNameServer(formData)
//     );

//     console.log("✅ addNameServer RESPONSE:", response);

//     // 🔥 FETCH UPDATED DOMAIN
//     console.log("📡 Fetching UPDATED domain...");
//     const domainRes = await lastValueFrom(
//       this.domainService.getDomainByDomainId(this.domainId)
//     );

//     this.domain = domainRes.body;

//     console.log("🔥 UPDATED DOMAIN AFTER NS SAVE:", this.domain);

//     // 🔥🔥🔥 CRITICAL FIX — FETCH UPDATED ORGANIZATION
//     console.log("📡 Fetching UPDATED organization...");
//     const orgRes = await lastValueFrom(
//       this.organizationService.getOrganisationDetailsByOrganisationId(this.organisationId)
//     );

//     this.orgDetails = orgRes.body;

//     console.log("🔥 UPDATED ORG AFTER NS SAVE:", this.orgDetails);
//     console.log("🔥 Remaining Free NS (UPDATED):", this.orgDetails?.remainingFreeNameServers);
//     console.log("🔥 Remaining Free Alias (UPDATED):", this.orgDetails?.remainingFreeNameIdentifiers);

//     if (response != null) {

//       console.log("➡️ Updating onboarding step...");
//       await this.updateUserOnboardingStep();

//       console.log("➡️ Saving DNSSEC records...");
//       await this.saveDNSSecRecords();

//       console.log("✅ All backend steps completed");

//       this.toastr.success("Name servers added successfully");

//       // 🔥 FINAL CHECK BEFORE NAVIGATION
//       console.log("🚨 FINAL CHECK BEFORE NAV:");
//       console.log("NS:", this.orgDetails?.remainingFreeNameServers);
//       console.log("Alias:", this.orgDetails?.remainingFreeNameIdentifiers);

//       console.log("🚀 Navigating to rgnt-domains...");

//       await this.router.navigate(['/rgnt-domains'], {
//         queryParams: { domainId: this.domainId }
//       });

//       console.log("✅ Navigation completed");
//     }

//   } catch (error) {
//     console.error("❌ ERROR in onSubmit:", error);
//     this.toastr.error("Address is Reserved");
//   } finally {
//     console.log("🏁 onSubmit END");
//     this.isLoading = false;
//   }
// }


  async updatePriceForDomain(domain){
   
    domain.cost = this.calculateTotalPricewithGst() - this.calculateTDS();
    domain.nsRecordPrice=this.price+this.nsRecordTotalPrice;
    domain.tdsAmountDetected=this.calculateTDS();
    domain.gstAmount = this.calculateGst();
    //console.log(domain)
    this.domainService.updateDomainDetails(domain).subscribe({
      next:(response)=>{
        //console.log("price updated successfully")
        domain.cost=domain.cost-this.price-this.nsRecordTotalPrice-this.calculateGst();
        if(domain.paymentStatus=="Ready For Payment"||domain.paymentStatus=="Payment Not Done" || domain.paymentStatus=="Payment Cancelled" || domain.paymentStatus=="Payment Aborted"){
          lastValueFrom(this.domainService.createInvoice(domain.domainId)).then(response => {
            //console.log("entered")
          }, error => {})
        }
      },error:(error)=>{
        if(error.status===HttpStatusCode.Unauthorized){
          this.router.navigateByUrl("/session-timeout")
        }
      }
    })
  }
 
  getPriceByNsRecordCount(nsRecordCount: number): number | null {
    const sortedData = [...this.priceDetails].sort((a, b) => a.nsRecordCount - b.nsRecordCount);
 
    // Find the closest matching or the highest nsRecordCount
    let closestMatch = null;
    for (const item of sortedData) {
      if (item.nsRecordCount >= nsRecordCount) {
        closestMatch = item;
        break; // Stop iterating once a match or higher value is found
      }
    }
 
    // If no match or higher value is found, use the highest available nsRecordCount
    if (!closestMatch) {
      closestMatch = sortedData[sortedData.length - 1];
    }
 
    return closestMatch ? closestMatch.price : null;
  }
  priceDetails
  freeNSRecord:number=0
  maxNsRecord:number=0
  fetchThePriceDetails(){
    this.domainService.getAllPriceDetails().subscribe({
      next:(response)=>{
        //console.log(response.body)
        this.priceDetails=response.body;
        const priceDetail=this.priceDetails.find(plan => plan.typeForPrice == "nameserver");
        //console.log(priceDetail+"fetchThePriceDetails")
        this.priceforNameServer=priceDetail.price*this.domain.numberOfYears;
        this.freeNSRecord=priceDetail.nsRecordCount;
        this.maxNsRecord=priceDetail.maxNameServer;
        this.gstPercentage=priceDetail.gst;
        //console.log(this.nameServers)
        // if(this.nameServers.length+this.nameServerLength>0){
        // this.updatePrice()
        // }
      },error:(error)=>{
        //console.log(error)
      }
    })
  }
 
  async updateUserOnboardingStep(){
    //console.log('user: '+this.user)
    this.organisationId = this.user.organisationId
    if(!this.user.isOnboardingCompleted){
      this.user.onboardingStepIndex = 3;
    }
    
    //console.log(this.user);
    await lastValueFrom(this.userService.updateUser(this.user)).then(
      response => {
        if(response.status === HttpStatusCode.Ok){
          //console.log('User updated successfully'+response.body);
        }
      },error => {
        //console.error('Error occurred while updating user', error);
      });
  }

  isHostNameExist: boolean = false;
  async validateNameServerByHostNameAndDomainId(hostName, domainId){
    await lastValueFrom(this.nameServerService.
      validateNameServerByHostNameAndDomainId(hostName,domainId)).then(
        response => {
          if(response.status === HttpStatusCode.Ok){
            this.isHostNameExist = response.body;
          }
        },error => {
          if(error.status === HttpStatusCode.Unauthorized){
            this.navigateToSessionTimeOut();
          }else{
            //console.log('error while validating existing hostname');
          }
        }
    )
  }

  hostNameError = '';
  validateHostName(ns: any) {
    const hostNameControl = ns.get('hostName');
    if (!hostNameControl) return;

    const hostName = hostNameControl.value;
    
    if (!hostName) {
        hostNameControl.setErrors(null);
        return;
    }

    //console.log(hostName + " " + this.domainId);

    this.validateNameServerByHostNameAndDomainId(hostName, this.domainId)
        .then(() => {
            //console.log(this.isHostNameExist);
            if (this.isHostNameExist) {
                hostNameControl.setErrors({ duplicateHostName: true });
            } else {
                hostNameControl.setErrors(null);
            }
        })
        .catch(error => {
            //console.error(error);
            hostNameControl.setErrors({ validationError: true });
        });
}

// async validateNameServerDetails() {
//   //if (this.card.heading === 'Name Server Details') {
//       const seenIPs = new Map<string, number>(); // Store IPs with their first occurrence index
//       const seenHostNames = new Map<string, number>(); 
//       let duplicateIps: string[] = [];

//       for (let i = 0; i < this.nameDetails.length; i++) {
//           const item = this.nameDetails[i];
//           const hostName = item.hostName ? item.hostName.trim() : "";
//           const ipAddress = item.ipAddress ? item.ipAddress.trim() : "";
//           const ipServiceProvider = item.ipServiceProvider ? item.ipServiceProvider.trim() : "";
//           const dnsServiceProvider = item.dnsServiceProvider ? item.dnsServiceProvider.trim() : "";

//           // Clear previous errors
//           item.duplicateIPError = "";
//           item.duplicateHostNameError = "";

//           // Skip empty or invalid values
//           if (!hostName || !ipAddress || !ipServiceProvider || !dnsServiceProvider || !this.isValidIP(ipAddress)) {
//               continue;
//           }

//           // Check for duplicate IPs in the form itself
//           if (seenIPs.has(ipAddress)) {
//               const firstIndex = seenIPs.get(ipAddress)!;
//               this.nameDetails[firstIndex].duplicateIPError = "Duplicate IP Address found!";
//               item.duplicateIPError = "Duplicate IP Address found!";
//           } else {
//               seenIPs.set(ipAddress, i);
//           }

//           // Check for duplicate Host Names
//           if (seenHostNames.has(hostName)) {
//               const firstIndex = seenHostNames.get(hostName)!;
//               this.nameDetails[firstIndex].duplicateHostNameError = "Duplicate Host Name Found!";
//               item.duplicateHostNameError = "Duplicate Host Name Found!";
//           } else {
//               seenHostNames.set(hostName, i);
//           }

//           // **Check for duplicate IPs in the database**
//           try {
//               const exists = await this.previewService.validateIpAdress(ipAddress, item.domainId).toPromise();
//               if (exists) {
//                   //console.log(exists);
//                   item.duplicateIPError = "IP Address already used by another domain.";
//                   duplicateIps.push(ipAddress);
//               } else if (exists === false) {
//                   //console.log(exists);
//                   item.duplicateIPError = "";
//               }
//           } catch (error) {
//               item.duplicateIPError = "IP Address is reserved.";
//               duplicateIps.push(ipAddress);
//               //console.log(item.duplicateIPError);
//               //console.error("Error checking IP:", error);
//           }
//       }
//   //}
// }
async validateIPAddress(ipAddress, domainId) {
  try {
    const exists = await lastValueFrom(this.previewService.validateIpAdress(ipAddress, domainId));
    return exists;
  } catch (error) {
    //console.error("Error validating IP address:", error);
    throw error;
  }
}

allowAlphabetsOnly(event: any): void {
  let inputValue = event.target.value;

  // Remove characters that are not alphabets or spaces
  let validValue = inputValue.replace(/[^a-zA-Z0-9\s]/g, '');

  // If the first character is a space, remove it (no leading spaces allowed)
  if (validValue.charAt(0) === ' ') {
    validValue = validValue.slice(1);
  }

  // If a space is entered at the end without any alphabet after it, remove it
  if (validValue.charAt(validValue.length - 1) === ' ' && validValue.length > 1 && !/[a-zA-Z0-9]/.test(validValue.charAt(validValue.length - 2))) {
    validValue = validValue.slice(0, -1);
  }

  // Replace multiple spaces with a single space
  validValue = validValue.replace(/\s+/g, ' ');

  // Update the input field with the valid value
  event.target.value = validValue;
}

alphabetValidator(control: any) {
  const value = control.value?.trim();
  if (!value) {
    return { required: true };  // Return 'required' error if the field is empty
  }
  return null; // Valid input
}
orgDetails:any
async fetchOrganizationDetails(orgId){
  if(orgId!=0&&orgId!=undefined&& orgId!=null){
 this.organizationService.getOrganisationDetailsByOrganisationId(orgId).subscribe({
    next:response=>{
      this.orgDetails=response.body
      //console.log(this.orgDetails+"org details fecthed")
    },
    error:error=>{
      
    }
  })
  }
 
}
// async updateOrganisation(orgDetails: any) {
//    // Assuming orgDetails has a type, using 'any' as a placeholder
//     //console.log("entered update orgDetails")
//     try {
        
//         const response: any = await firstValueFrom(this.organizationService.updateOrganisationDetails(orgDetails));

//         // next:response => { ... } logic
//         this.orgDetails = response.body;
//         //console.log(orgDetails+"-------------------------------")

//     } catch (error) {
//         // error:error => { ... } logic
//         if(error.status === HttpStatusCode.Unauthorized){
//           this.navigateToSessionTimeOut();
//         }
//         // You can handle the error here, e.g., logging it or showing a toast
//         // console.error('Error updating organization details:', error);
//     }
// }

async updateOrganisation(orgDetails: any) {

  // 🔹 Step 1: fetch latest organisation from backend
  const latestOrgResponse: any = await firstValueFrom(
    this.organizationService.getOrganisationDetailsByOrganisationId(this.organisationId)
  );

  const latestOrg = latestOrgResponse.body;

  // 🔹 Step 2: merge latest DB values with current object
  const safeOrg = {
    ...latestOrg,
    ...orgDetails
  };

  // 🔹 Step 3: send merged object to backend
  const response: any = await firstValueFrom(
    this.organizationService.updateOrganisationDetails(safeOrg)
  );

  this.orgDetails = response.body;
}

calculateGst():number{
const total=(this.price+this.domainCost+ this.aliasCost+ this.nsRecordTotalPrice)-(this.domain.rebateAmountOfDomain??0);
const gstDecimal=this.gstPercentage/100;

return total*gstDecimal;
}
calculateTDS():number{
    const total = (this.domainCost + this.aliasCost+this.price+this.nsRecordTotalPrice)-(this.domain.rebateAmountOfDomain??0);
  if(total>this.tdsStartsFrom){
    return total*this.tds
  }else {
    return 0
  };
}
calculateTotalPricewithGst(): number {
  //console.log(this.price + this.domainCost + this.aliasCost+this.nsRecordTotalPrice)
  //console.log(this.domain.rebateAmountOfDomain)
  const total = (this.price + this.domainCost + this.aliasCost+this.nsRecordTotalPrice) - this.domain.rebateAmountOfDomain 
  //console.log("price: " + this.price + ", domainCost: " + this.domainCost + ", aliasCost: " + this.aliasCost);
  //console.log("Total before GST: " + total);
  const gstDecimal = this.gstPercentage / 100;
  //console.log(gstDecimal+"gstDecimal");
  const gstAmount = (total)* gstDecimal;
  //console.log(gstAmount+"gstAmount");
  return total + gstAmount;
}
calculateTotalPricewithoutGst(): number {
  const total = this.domainCost + this.aliasCost+this.price+this.nsRecordTotalPrice;
 
  return total ;   
}
tdsStartsFrom:number=0;
calculateTdsIfItGreaterThanThePrice(): number {
  const total = (this.domainCost + this.aliasCost+this.price+this.nsRecordTotalPrice)-(this.domain.rebateAmountOfDomain??0);
  if(total>this.tdsStartsFrom){
    return total*this.tds
  }else {
    return 0
  };
 
}

showDeducteeDetails: boolean = false; // Initialize to false to start collapsed
rebateAmount:number=0;
  // Function to toggle the visibility
  toggleDeducteeDetails(): void {
    this.showDeducteeDetails = !this.showDeducteeDetails;
  }
  orgDocs:any
//   orgPanNumber:string=''
// async fetchOrgDocs(orgId){
//   const response = await lastValueFrom(this.documentService.getOrgDoucumentsById(orgId));
//   this.orgDocs=response.body;
//   this.orgDocs.some((doc: any) => { // You might want to define a more specific interface for 'doc'
//   if (doc.panNumber !== null && doc.panNumber !== undefined && doc.panNumber !== '') {
//     this.orgPanNumber = doc.panNumber;
//     return true; // Return true to stop the iteration once a non-null panNumber is found
//   }
//   return false; // Continue iteration
// });
//   //console.log(response.body); 
// }

tds:any
getStaticDataForTds(){
  // Assuming 'this.assetService' is where getEmailReqExp is defined
  this.registrationService.getEmailReqExp('tds').subscribe({
    next: (response: string) => { 
      const respo = response[0] as any;
      this.tds = respo.value.trim(); 
    },
    error: (error) => {
      //console.error('Error fetching email regex:', error);
      this.tds = 0; // Or null, depending on your default state
    }
  });
}

costOfDomain:number=0;
costofNameServer:number=0;
costOfRegistrationFee:number=0;
costOfNameIdentifier:number=0;

costItems=[]
totalQuantity:number=0;
grandTotal:number=0;
minimumCombinedIPS:number=0;
populateCostItems(): void {
  this.costItems = [
    { sNo: '01', particulars: 'Domain', pricePerItem: this.costOfDomain, quantity: 1, totalPrice: this.costOfDomain * 1 },
    { sNo: '02', particulars: 'Name Servers', pricePerItem: this.costofNameServer, quantity: 5, totalPrice: this.costofNameServer * 5},
    { sNo: '03', particulars: 'Name Identifiers', pricePerItem: this.costOfNameIdentifier, quantity: 5, totalPrice: this.costOfNameIdentifier * 5 },
    { sNo: '04', particulars: 'Processing Fee', pricePerItem: this.costOfRegistrationFee, quantity: 0, totalPrice: this.costOfRegistrationFee * 1 },
  ];
  this.totalQuantity = this.costItems.reduce((sum, item) => sum + item.quantity, 0);
    this.grandTotal = this.costItems.reduce((sum, item) => sum + item.totalPrice, 0);
}
getAllStaticData() {
  this.registrationService.getAllStaticData().subscribe({
    next: (response: any[]) => { // Add a type annotation for better safety
      //console.log(response);

      // Iterate through the response array and assign values
      response.forEach(item => {
        switch (item.type) { 
          case 'costOfDomain':
            // Convert to number using Number() or parseFloat()
            this.costOfDomain = Number(item.value);
            break;
          case 'costofNameServer':
            this.costofNameServer = Number(item.value);
            break;
          case 'costOfRegistrationFee':
            this.costOfRegistrationFee = Number(item.value);
            break;
          case 'costOfNameIdentifier':
            this.costOfNameIdentifier = Number(item.value);
            break;
          case 'rebateAmount':
            this.rebateAmount = Number(item.value);
            break;
            case 'tdsStartsFrom':
            this.tdsStartsFrom = Number(item.value);
            break;
            case 'minimumCombinedIps':
            this.minimumCombinedIPS = Number(item.value);
            break;
          // Add other cases if you need to assign other values later
        }
        this.populateCostItems();
        
      });

      // You can log the assigned values to verify
      //console.log('Assigned costOfDomain:', this.costOfDomain);
      //console.log('Assigned costofNameServer:', this.costofNameServer);
      //console.log('Assigned costOfRegistrationFee:', this.costOfRegistrationFee);
      //console.log('Assigned costOfNameIdentifier:', this.costOfNameIdentifier);

    },
    error: (error) => {
      //console.error('Error fetching static data:', error);
      if(error.status == HttpStatusCode.Unauthorized){
        this.navigateToSessionTimeOut()
      }
      // Handle error appropriately, e.g., show a user-friendly message
    }
  });
}
formatCurrency(value: number): string {
  // Use toLocaleString for currency formatting
  // 'en-IN' locale for Indian English
  // style: 'currency' to format as currency
  // currency: 'INR' to specify Indian Rupees
  return value.toLocaleString('en-IN', { style: 'currency', currency: 'INR' });
}

async updateDomainBasedOnisCoOperativeBank() {
    const result =await lastValueFrom(this.domainService.updateDomainBasedOnisCoOperativeBank(this.domainId));
      this.domain=result.body;
      // Log the successful result or perform further actions
      //console.log('Domain update successful:', result);

      // You might want to update UI state or show a success message here
      // this.showSuccessMessage('Domain updated successfully!');

    } catch (error) {
      // Catch any errors that occur during the async operation.
      // 'error' could be an HttpErrorResponse, a generic Error, or any other thrown value.
      //console.error('Error updating domain:', error);

      // Provide user feedback, e.g., display an error message
      // this.showErrorMessage('Failed to update domain. Please try again.');

      // You might also want to re-throw the error if it needs to be handled further up the call stack
      // throw error;

    }
    idrbtDetails:any
   async getOrgTaxDetails() {
  try {
    const response = await lastValueFrom(this.organizationService.getOrgTaxDetails());
    this.idrbtDetails = response.body; // assuming the actual data is in response.body
    //console.log(this.idrbtDetails);
  } catch (error) {
    //console.error('Failed to fetch IDRBT details:', error);
  }
}

atLeastOneIpValidator(): ValidatorFn {
  return (group: AbstractControl): ValidationErrors | null => {
    const ip = group.get('ipAddress')?.value;
    const ipv6 = group.get('ipv6Address')?.value;

    if (!ip && !ipv6) {
      return { atLeastOneIpRequired: true };
    }

    return null;
  };
}

// DNS SEC CODE STARTS
   dnssecDetailsList: DnssecDetails[] = [];

  // Called when "Add DNSSEC Details" is clicked
  addDNSSECDtls(): void {
    this.dnssecDetailsList.push(this.getNewDnssecRecord());
  }

  // Called when "Add Additional DS Records" is clicked
  addAdditionalRecords(): void {
    if (this.dnssecDetailsList.length + (this.dbDnsSecDetailsList ?? []).length < 3) {
    this.dnssecDetailsList.push(this.getNewDnssecRecord());
}

}


  removeRecord(index: number): void {
    this.dnssecDetailsList.splice(index, 1);
  }


  // Reusable record creation
  getNewDnssecRecord(): DnssecDetails {
    return {
      id:0,
      keyTag: '',
      algorithmType: '',
      algorithmTypeCode: '',
      digestType: '',
      digestTypeCode:'',
      digest: '',
      domainId:0,
      organisationId:0
    };
  }

  dbDnsSecDetailsList=[]
  async getDnsSecDetailsByDomainId(domainId: number){

  try{
    const response = await lastValueFrom(this.dnsSecService.getDnsSecByDomainId(domainId));
    if(response.status === HttpStatusCode.Ok){
      this.dbDnsSecDetailsList = response.body;
        
      // this.addDnssecDetailsList=[...this.dnssecDetailsList];
      // this.dnsSecDetailsCount = response.body.length;
    }
  }catch(err){

  }

}

  async saveDNSSecRecords() {
    if(this.dnssecDetailsList.length < 1){
      //console.log('No DNS SEC Records added....')
      return;
    }
    try{
      this.dnssecDetailsList.forEach(dnsSec => {
        dnsSec.domainId = this.domainId;
        dnsSec.organisationId = this.organisationId;
      })
      //console.log(this.dnssecDetailsList);
      const response = await lastValueFrom(this.dnsSecService.saveAllDnsSecRecords(this.dnssecDetailsList));
      if(response.status === HttpStatusCode.Created){
        //console.log('DNS SEC records saved : '+response.body);
      }
    }catch(error){
      //console.log(error);
    }
  }

    algorithmTypeOptions = [];

onAlgorithmChange(code: string, dns: DnssecDetails) {
  //console.log(this.algorithmTypeOptions)
  if (!code) {
    dns.algorithmTypeCode = null;
    dns.algorithmType = null;
    return;
  }

  const selected = this.algorithmTypeOptions.find(opt => opt.algorithmCode === code);
  if (selected) {
    dns.algorithmTypeCode = selected.algorithmCode;
    dns.algorithmType = selected.algorithmType;
  }
}

onDigestChange(code: string, dns: DnssecDetails) {
  if (!code) {
    dns.digestTypeCode = null;
    dns.digestType = null;
    return;
  }

  const selected = this.digestTypeOptions.find(opt => opt.digestTypeCode === code);
  if (selected) {
    dns.digestTypeCode = selected.digestTypeCode;
    dns.digestType = selected.digestType;
  }
}
digestTypeOptions = [];

isFormValid(): boolean {
  if (this.dnssecDetailsList.length === 0) {
    return true;
  }

  for (let i = 0; i < this.dnssecDetailsList.length; i++) {
    const dnsSec = this.dnssecDetailsList[i];

    // 1. Key Tag: required & numeric
    if (!dnsSec.keyTag || !/^[0-9]+$/.test(dnsSec.keyTag)) {
      return false;
    }
    const keyTagValue = parseInt(dnsSec.keyTag, 10);
    if (isNaN(keyTagValue) || keyTagValue > 65535) {
      return false;
    }

    // 2. Algorithm Type: must have a code selected
    if (!dnsSec.algorithmTypeCode) {
      return false;
    }

    // 3. Digest Type: must have a code selected
    if (!dnsSec.digestTypeCode) {
      return false;
    }

    // 4. Digest: required
    if (!dnsSec.digest) {
      return false;
    }

    // 5. Digest must be unique
    const duplicate = this.dnssecDetailsList.some(
      (other, j) => j !== i && other.digest?.trim() === dnsSec.digest?.trim()
    );
    if (duplicate) {
      return false;
    }
  }

  return true;
}
  // DNS SEC DODE ENDS

  // component.ts
dnssecInfoText: string = `
  <div style="background-color:#ffe0e0; padding:12px 15px; border-radius:6px; color:#036; font-size:14px; line-height:1.5; max-width:800px;">
    Please give all the following details as provided by the DNSSEC Service Provider. 
    Any mistake may lead to failure in validation of Keys/data and DNSSEC implementation will fail, 
    for which Registrar has no role. The Registrar portal is just a pass-through mechanism from DNSSEC provider to the Registry.
    Required fields:
    <ol style="margin: 0; padding-left: 20px;">
      <li>KeyTag – Manual Entry</li>
      <li>Algorithm – Drop Down</li>
      <li>Digest Type – Drop Down</li>
      <li>
        Digest = 
        <a href="https://example.com" target="_blank" style="color:#007bff; text-decoration:none;">
          format as given by the DNSSEC service provider based on Algorithm
        </a>
      </li>
    </ol>
  </div>
`;


async getDnsAlgorithmType() {
  try {
    const result = await lastValueFrom(this.dnsSecService.getDnsAlgorithmTypes());

      this.algorithmTypeOptions = result.body;
    
  } catch (error) {
    if(error.status===HttpStatusCode.Unauthorized){
      this.navigateToSessionTimeOut();
    }
  }
}
async getDnsDigestType() {
  try {
    const result = await lastValueFrom(this.dnsSecService.getDnsDigestTypes());
    //console.log(result.body);
    this.digestTypeOptions = result.body;
  } catch (error) {
    //console.error('Error fetching DNS digest types:', error);
    if(error.status === HttpStatusCode.Unauthorized){
          this.navigateToSessionTimeOut();
        }
  }
}
 isDigestDuplicate(currentIndex: number): boolean {
  const currentValue = this.dnssecDetailsList[currentIndex].digest?.trim();
  if (!currentValue) return false;

  // Check if any other record has the same digest
  return this.dnssecDetailsList.some((item, idx) => 
    idx !== currentIndex && item.digest?.trim() === currentValue
  );
}
closePasswordModal() {
 //console.log(this.isSigned)
  
  this.modalInstance.hide();  // Hide the modal
  this.tokenPassword = '';
  this.passwordErrorMessage = '';
  this.tokens = [];
  this.certificates = [];
  this.selectedToken = "";
  this.selectedCertificate = "";
}
//checkBoxChecked:boolean=false
// toggleModal(): void {
//   const checkbox = event.target as HTMLInputElement;
//   if (checkbox.checked) { // Only execute when checkbox is selected
//     this.checkBoxChecked = true;
//     this.isLoading = true;
//     this.getDscResponse();
    
//     const modalElement = document.getElementById('passwordModal');
//     if (modalElement) {
//       this.modalInstance = new bootstrap.Modal(modalElement, {
//         backdrop: 'static',  
//         keyboard: false      
//       });
//       this.modalInstance.show(); // Show modal
//     }
//   }
// }
toggleModal(): void {
  const modalElement = document.getElementById('passwordModal');
  if (modalElement) {
    this.modalInstance = new bootstrap.Modal(modalElement, {
      backdrop: 'static',
      keyboard: false
    });
    this.modalInstance.show();
  }
  this.getDscResponse();   // fetch tokens
}
navigateToAuthenticationError() {
  this.router.navigateByUrl("/authentication-error"); // Navigate to the session-timeout route
}
getDscResponse() {
  this.isLoading = true;
  this.http.get(`${this.dscApi}/dsc/getTokenRequest`).subscribe(
    (response: any) => {
      //console.log('Response from getTokenRequest API:', response);
      if (response && response.encryptedData && response.encryptionKeyID) {
        const payload = {
          encryptedRequest: response.encryptedData,
          encryptionKeyID: response.encryptionKeyID
        };
        this.http.post(`${this.embridgeUrl}/DSC/ListToken`, payload).subscribe(
          (embridgeListTokenAPI: any) => {
            //console.log('Response from embridge ListToken API:', embridgeListTokenAPI);
            if (embridgeListTokenAPI) {
              const embridgeListTokenAPIData = embridgeListTokenAPI.responseData;
              this.http.get(`${this.dscApi}/dsc/getTokenList?data=${encodeURIComponent(embridgeListTokenAPIData)}`).subscribe(
                  (response: any) => {
                      //console.log('Response from getTokenList API:', response);
                      if(response.tokenNames != null && response.tokenNames.length != 0){
                        this.tokens = response.tokenNames;
                        this.isLoading = false;
                        this.passwordErrorMessage = '';
                        //this.modalInstance.show();
                        this.toastr.success("Fetched tokens successfully");
                      }
                      else{
                        this.tokens = [];
                        this.isLoading = false;
                        this.passwordErrorMessage = '';
                        this.toastr.error("Failed to fetch tokens");
                        this.toastr.warning("If DSC token is not inserted, please insert your DSC Token");
                      }
                      //console.log('====================================>'+this.selectedToken);
                  },
                  (error) => {
                      //console.error('Failed to get valid tokens.', error);
                      this.isLoading = false;
                      this.tokens = [];
                      this.toastr.warning("If DSC token is not inserted, please insert your DSC Token");
                  }
              );
            }
            else{
              this.isLoading = false;
              this.tokens = [];
            }
          },
          (embridgeListTokenAPIError) => {
            //console.error('Failed to get valid tokens. Error in embridge ListToken API: ', embridgeListTokenAPIError);
            this.passwordErrorMessage = 'Failed to get valid tokens.';
            this.isLoading = false;
            this.toastr.warning(
              "Please check if Embridge is installed and in running state. If not please install Embridge and run it!!!",
              "Warning",
              {
                timeOut: 20000,
                progressBar: true,
                closeButton: true
              }
            );
          }
        );
      } else {
        this.passwordErrorMessage = 'Failed to get valid tokens.';
        this.isLoading = false;
        this.tokens = [];
        this.toastr.warning("If DSC token is not inserted, please insert your DSC Token");
      }
    },
    (error) => {
      //console.error('Error occurred while fetching tokens from the getTokenRequest API:', error);
      this.isLoading = false;
      this.tokens = [];
      this.toastr.warning("If DSC token is not inserted, please insert your DSC Token");
      this.toastr.warning(
        "Please check if Embridge is installed and in running state. If not please install Embridge and run it!!!",
        "Warning",
        {
          timeOut: 20000,
          progressBar: true,
          closeButton: true
        }
      );
    }
  );
}
showPassword = false;
togglePasswordVisibility() {
  this.showPassword = !this.showPassword;
}
onTokenSelect(){
  this.isLoading = true;
  //console.log('Selected Token:', this.selectedToken);
  this.http.get(`${this.dscApi}/dsc/getCertificateRequest?keyStoreDisplayName=${encodeURIComponent(this.selectedToken)}`).subscribe(
    (response: any) => {
      //console.log('Response from getCertificateRequest API:', response);
      if (response && response.encryptedData && response.encryptionKeyID) {
        const payload = {
          encryptedRequest: response.encryptedData,
          encryptionKeyID: response.encryptionKeyID
        };
        this.http.post(`${this.embridgeUrl}/DSC/ListCertificate`, payload).subscribe(
          (embridgeListCertificate: any) => {
            //console.log('Response from embridge ListCertificate API:', embridgeListCertificate);
            if (embridgeListCertificate) {
              const embridgeListCertificateData = {
                encryptedCertificateData: embridgeListCertificate.responseData
              };
              this.http.post(`${this.dscApi}/dsc/getCertificateList`, embridgeListCertificateData).subscribe(
                (response: any) => {
                    //console.log('Response from getCertificateList API:', response);
                    if(response.certificates != null && response.certificates.length != 0){
                      ////console.log(response.certificates[0].emailAddress);
                      //console.log(localStorage.getItem('email'));
                      const storedEmail = localStorage.getItem('email')?.trim().toLowerCase();
                      let emailMatched = false;
                      for (let certificate of response.certificates) {
                        const certificateEmail = certificate.emailAddress.trim().toLowerCase();
                        if(environment.isDSCEnabled){
                          if(certificateEmail === storedEmail){
                          //console.log('Email matches:', certificate.emailAddress);
                            this.certificates = response.certificates;
                            this.isLoading = false;
                            this.passwordErrorMessage = '';
                            this.toastr.success("Fetched certificates successfully");
                          emailMatched = true;
                          break;
                        }
                        else{
                          // //console.error('Emails do not match:', certificateEmail, storedEmail);
                          this.isLoading = false;
                          this.certificates = [];
                          this.navigateToAuthenticationError();
                            
                           break;
                        }
                        }else{
                          // if(certificateEmail === storedEmail){
                          // //console.log('Email matches:', certificate.emailAddress);
                            this.certificates = response.certificates;
                            this.isLoading = false;
                            this.passwordErrorMessage = '';
                            this.toastr.success("Fetched certificates successfully");
                          // emailMatched = true;
                          // break;
                       // }
                        //else{
                          // //console.error('Emails do not match:', certificateEmail, storedEmail);
                          //this.isLoading = false;
                          //this.certificates = [];
                          //this.navigateToAuthenticationError();
                            
                          // break;
                       // }
                        }
                       }
                    }
                      else{
                        this.certificates = [];
                        this.isLoading = false;
                        this.passwordErrorMessage = '';
                        this.toastr.error("Failed to fetch certificates from token");
                      }
                      //console.log(this.certificates);
                  },
                  (error) => {
                      //console.error('Error occurred while calling getCertificateList API:', error);
                      this.isLoading = false;
                      this.certificates = [];
                      this.passwordErrorMessage = '';
                      this.toastr.error("Failed to fetch certificates from token");
                  }
              );
            }
          },
          (embridgeListCertificateAPIError) => {
            //console.error('Error occurred while calling the embridge ListCertificate API:', embridgeListCertificateAPIError);
            this.isLoading = false;
            this.certificates = [];
            this.toastr.warning(
              "Please check if Embridge is installed and in running state. If not please install Embridge and run it!!!",
              "Warning",
              {
                timeOut: 20000,
                progressBar: true,
                closeButton: true
              }
            );
          }
        );  
      } else {
        this.isLoading = false;
        this.certificates = [];
        this.toastr.error("Failed to fetch certificates from token");
      }
    },
    (error) => {
      //console.error('Error occurred while fetching tokens from the getCertificateRequest API:', error);
      this.isLoading = false;
      this.certificates = [];
      this.toastr.error("Failed to fetch certificates from token");
    }
  );
}
buildNameServerSigningJson() {
  const fullDomainName = (this.bankName || '') + (this.domainName || '');
  return {
    organisationId: this.organisationId,
    domainId: this.domainId,
    domainName: fullDomainName,
    nameIdentifiers: this.nameIdentifiersList,
    tenure: this.domain?.numberOfYears,
    nameServers: this.nameServerForm.value.nameServers,
    dnsSecRecords: this.dnssecDetailsList
  };
}
onSign(){
  this.isLoading = true;
    //console.log('Selected Token:', this.selectedCertificate);
   const nameServerSigningJson = this.buildNameServerSigningJson();
console.log("Domain Object:", this.domain);
console.log("Identifiers received:", this.nameIdentifiersList);
console.log("Signing Payload:", nameServerSigningJson);
const jsonString = JSON.stringify(nameServerSigningJson);
console.log("Signing JSON:", jsonString);
const hash = CryptoJS.SHA256(jsonString).toString();   // ✅ Generate hash properly
const signingRequestData = {
  keyId: this.selectedCertificate.keyId,
  keyStoreDisplayName: this.selectedToken,
  keyStorePassPhrase: this.tokenPassword,
  dataType: 'TextPKCS7',
  dataToSign: hash
};
    const encodedSigningRequestData = encodeURIComponent(JSON.stringify(signingRequestData));
    this.http.post(`${this.dscApi}/dsc/getSigningRequest`, signingRequestData).subscribe(
      (response: any) => {
        //console.log('Response from getSigningRequest API:', response);
        if (response && response.encryptedData && response.encryptionKeyID) {
          const payload = {
            encryptedRequest: response.encryptedData,
            encryptionKeyID: response.encryptionKeyID
          };
          this.http.post(`${this.embridgeUrl}/DSC/PKCSSign`, payload).subscribe(
            (embridgePKCSSignResponse: any) => {
              //console.log('Response from embridge PKCSSign API:', embridgePKCSSignResponse);
              if (embridgePKCSSignResponse) {
                const nameServerSigningJson = this.buildNameServerSigningJson();
const payloadToSign = JSON.stringify(nameServerSigningJson);
const embridgePKCSSignResponseData = {
  // user: this.formData.name,
  userMailId: localStorage.getItem('email'),
  // declaration: this.fullText,
  // designation: this.formData.designation,
  // organisation: this.formData.organisationName,
  isSigned: '',
  certificate: JSON.stringify(this.selectedCertificate),
  // 🔥 VERY IMPORTANT
  signedText: payloadToSign,
  payloadHash: hash,  
  
  encryptedSignedData: embridgePKCSSignResponse.responseData,
    organisationId: this.user.organisationId,
    domainId: this.domainId,                // ⭐ REQUIRED
    domainName: nameServerSigningJson.domainName
};
                //console.log('==========================>   '+embridgePKCSSignResponseData.declaration);
                this.http.post(`${this.dscApi}/dsc/saveDomainSignature`, embridgePKCSSignResponseData).subscribe(
                    (response: any) => {
                      this.closePasswordModal();
                        this.isLoading = false;
                      if (response.verificationStatus === "VERIFIED") {
      this.isSigned = true;
      this.signatureVerified = true;
      //this.checkBoxChecked = true;
      this.lastSignedHash = hash;
      this.toastr.success("Signature Verified Successfully");
      this.onButtonClickForSave();
  } else {
      this.isSigned = false;
      this.signatureVerified = false;
      this.toastr.error("Signature Verification Failed");
  }
                        // this.isSigned=true;
                        //this.toastr.success("Signed using DSC successfully");
                        //this.isSigned=true;
                        //console.log('Response from third API:', response);
                       //this.checkBoxChecked=true;
                      
                        //console.log(response);
                      
                        // this.checkBoxChecked=true;
                        // this.router.navigateByUrl('/rgnt-domains');
                    },
                    (error) => {
                      const err = error?.error;
                      console.log(err)
                      if (err.errorCode === 'ERR001') {
                        this.isLoading = false;
                        this.toastr.warning("There is an issue with token, cannot proceed further.");
                      } else if(err.errorCode === 'ERR002'){
                        this.isLoading = false;
                        this.toastr.warning("Please use only the DSC issued by IDRBT. To obtain a DSC, kindly contact: casahyog@idrbt.ac.in, cahelp@idrbt.ac.in");
                      }
                      else {
                        //console.error('Error occurred while calling third API:', error);
                        this.isLoading = false;
                        this.toastr.warning("Make sure the Token PIN entered was right");
                      }                    
                    }
                );
              }
            },
            (embridgePKCSSignAPIError) => {
              //console.error('Error occurred while calling the embridge PKCSSign API:', embridgePKCSSignAPIError);
              this.isLoading = false;
              this.toastr.warning(
                "Please check if Embridge is installed and in running state. If not please install Embridge and run it!!!",
                "Warning",
                {
                  timeOut: 20000,
                  progressBar: true,
                  closeButton: true
                }
              );
            }
          );
        } else {
          this.isLoading = false;
          this.toastr.error("Enter token pin")
        }
      },
      (error) => {
        //console.error('Error occurred while fetching tokens from the getSigningRequest API:', error);
        this.isLoading = false;
        this.toastr.warning("Please ensure the all fields entered are correct");
      }
    );
}



// async updateUserOrgDetailsAndDomainPrice(orgId,domainId){
//   const response = await lastValueFrom(this.domainService.updateUserOrgDetailsAndDomainPrice(orgId,domainId));
// }

}


