import { ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { DomainService } from '../rgnt-domain/service/domain.service';
import { last, lastValueFrom } from 'rxjs';
import { HttpClient, HttpResponse, HttpStatusCode } from '@angular/common/http';
import { ActivatedRoute, NavigationExtras, Router } from '@angular/router';
import { NameServerService } from '../name-server-form/service/name-server.service';
import { ToastrModule, ToastrService } from 'ngx-toastr';
import { DomainInvoiceService } from '../domain-invoices/service/domain-invoices.service';
import { error, param } from 'jquery';
import { environment } from '../environments/environment';
import { OrganisationDetailsService } from '../organisation-details/service/organisation-details.service';
import { DomainApplicationService } from '../domain-application/service/domain-application.service';
import { RegistrationService } from '../registration/service/Registration.service';
import { DnsSecService } from '../name-server-form/service/dns-sec.service';
import { DnssecDetails } from '../model/DnsSecDetails.model';
import { AssetService } from '../asset.service';
import { MatDialog, MatDialogRef } from '@angular/material/dialog';
import { UserDomainService } from '../user-domain-details/service/user-domain.service';
import { Modal } from 'bootstrap';
import { ViewChild, ElementRef } from '@angular/core';


interface AliasData {
  id: number;
  aliasName: string;
  cost: number;
  domainId:number
}
@Component({
    selector: 'app-domain-details',
    templateUrl: './domain-details.component.html',
    styleUrls: ['./domain-details.component.css'],
    standalone: false
})
export class DomainDetailsComponent implements OnInit {

  constructor(private domainService: DomainService, 
    private router: Router, private activatedRouter: ActivatedRoute,
    private nameServerService: NameServerService,private toastr:ToastrService,
     private domainInvoiceService: DomainInvoiceService,private http: HttpClient,
     private organisationService: OrganisationDetailsService,
     private domainApplicationService: DomainApplicationService,
     private registrationService :RegistrationService,
     private dnsSecService: DnsSecService,private userdomainService:UserDomainService,  private dialog: MatDialog,
     private assetService:AssetService
  ){

  }

  domainId: number = 0;
  async ngOnInit(): Promise<void> {
    this.activatedRouter.queryParams.subscribe(param => {
      var domainId = param['domainId'];
      this.domainId = param['domainId'];
    })
    //console.log(this.domainId)
    await this.getAllStaticData();
    await this.getDomainById(this.domainId);
     await this.getNameServerPrice();
    await this.getNameServersByDomainId(this.domainId);
   
    await this.getDnsDigestType();
    await this.getDnsAlgorithmType();
    await this.getAllInvoicesDataByDomainId(this.domainId);
   
    await this.getAliasName(this.domainId);
    this.getDnsSecDetailsByDomainId(this.domainId);
    await this.loadOnboardingDomain();   // 👈 add this
 //this.setAllowedTenures(); 



    
  }

  domainDetail : any;
  disableAddDomain:boolean=false
  enablePurchaseNameServer:boolean=false;
  enablePurchaseNameIdentifier:boolean=false;
  async getDomainById(domainId: number): Promise<any>{
    await lastValueFrom(this.domainService.getDomainByDomainId(domainId)).then(
      response => {
        //console.log(response)
        if(response.status === HttpStatusCode.Ok){
          this.domainDetail = response.body;
          this.getOrgDetailsById(this.domainDetail.organisationId);
          //console.log(this.domainDetail)
       
          
        }
      }, error => {
        if(error.status === HttpStatusCode.Unauthorized){
          this.navigateToSessionTimeout();
        }
      }
    )
    return this.domainDetail;
  }

  aliasList=[]
  async getAliasName(domainId){
    this.domainService.getAllAliasName(domainId).subscribe({
      next:(response)=>{
        this.aliasList=response.body;
        if(this.orgDetails.aliasCountForOrganization>=(this.initialBundleNameIdentifierCount??0)+(this.domainDetail.remainingPurchasedNameIdentifiers??0)
          && (this.domainDetail.paymentStatus=="Payment Under Review" ||this.domainDetail.paymentStatus=="Payment Completed" || this.domainDetail.paymentStatus=="Payment Approved") && (this.orgDetails.remainingFreeNameIdentifiers ?? 0) <= 0){
              this.enablePurchaseNameIdentifier=true
        }
        //console.log(this.aliasList)
      },error:(error)=>{
        if(error.status === HttpStatusCode.Unauthorized){
          this.navigateToSessionTimeout();
        }
      }
    })
  }

  async getNameServersByDomainId(domainId: number){
    await lastValueFrom(this.nameServerService.getNameServersByDomainId(domainId)).then(
      response => {
        if(response.status === HttpStatusCode.Ok){
          this.domainDetail.nameServers = response.body;
          // if(this.domainDetail.nameServers.length < 1){
          //   this.domainDetail.nameServers = [];
          // }
        }
      },error => {
        if(error.status === HttpStatusCode.Unauthorized){
          this.router.navigateByUrl('/session-timeout');
        }
      }
    )
  }

  async navigateToSessionTimeout() {
    this.router.navigateByUrl('/session-timeout');
  }

  role = localStorage.getItem('userRole');
  cancelDomain() {
    //role = localStorage.getItem('userRole');
  
    if (this.role === 'IDRBTADMIN') {
      this.router.navigateByUrl('/rgtr-domains');
    } else {
      this.router.navigateByUrl('/rgnt-domains');
    }
  }
  
  domainedit() {
    if (this.domainDetail.nameServers.length < 1) {
      this.toastr.warning('No name servers to udpate');
      return;
    }
    this.router.navigateByUrl('/DomainEditPage', { state: { domainDetail: this.domainDetail } });
  }

addNameServers(domainId) {

  // 🔴 BLOCK CASE
  if (!this.canAddDetails()) {
    this.toastr.error("Cannot add Name Servers when payment is completed or under review.");
    return;
  }

  // 🔴 SAFETY CHECK
  if (this.disableAddDomain) return;

  // ✅ SINGLE FLOW (no duplicate conditions)
  const navigationExtras: NavigationExtras = {
    state: {
      organisationId: this.domainDetail.organisationId,
      domainId: domainId,
      applicationId: this.domainDetail.applicationId,
      nameServerLength: this.domainDetail.nameServers?.length || 0,
      limitOfNameServers:
        this.domainDetail.remainingPurchasedNameServers ||
        this.orgDetails?.remainingFreeNameServers
    },
    queryParams: {
      domainId: domainId
    }
  };

  this.router.navigate(['/name-server'], navigationExtras);
}


canAddDetails(): boolean {
  return !(
    this.domainDetail?.paymentStatus === 'Payment Completed' ||
    this.domainDetail?.paymentStatus === 'Payment Under Review'
  );
}

  async deleteNameServerById(nameServerId){
    
    let  confirmed = window.confirm('Are you sure, you really want to delete this name server record ?');
   
  if(confirmed){
   await this.deleteNameServerByTheId(nameServerId);
   if(this.domainDetail.nameServers.length>4){
    this.domainDetail.cost=this.domainDetail.cost-environment.cst
    await this.updatePriceForDomain(this.domainDetail);
   }
  
  }
    
}
async deleteNameServerByTheId(id){
  this.nameServerService.deleteNameServer(id).subscribe({
    next:(response)=>{
      this.toastr.success("Deleted Successfully");
      this.getNameServersByDomainId(this.domainId);
    },error:(error)=>{
      //console.log(error)
    }
  })
}
async updatePriceForDomain(domain){
     this.domainService.updateDomainDetails(domain).subscribe({
       next:(response)=>{
         //console.log("price updated successfully")
         if(domain.paymentStatus=="Ready For Payment"||domain.paymentStatus=="Payment Not Done"){
           lastValueFrom(this.domainService.createInvoice(domain.domainId)).then(response => {
            this.getAllInvoicesDataByDomainId(domain.domainId)
           }, error => {})
         }
       },error:(error)=>{
         if(error.status===HttpStatusCode.Unauthorized){
           this.router.navigateByUrl("/session-timeout")
         }
       }
     })
   }
invoiceData : any

async getAllInvoicesDataByDomainId(domainId : number){
  await lastValueFrom(this.domainInvoiceService.getAllInvoiceDetailsByDomainId(domainId)).then(
   (response) => {
     if(response.status === HttpStatusCode.Ok){
      this.invoiceData = response.body;
      //console.log(this.invoiceData)
     

     }

   }, (error) =>{
      if(error.status == HttpStatusCode.Unauthorized){
         this.router.navigateByUrl("/session-timeout")
      }

   });
}





 isPurchaseNameServerModalOpen: boolean = false;
purchaseNameServer() {
  if (
    this.domainDetail?.paymentStatus === 'Payment Completed' ||
    this.domainDetail?.paymentStatus === 'Payment Under Review'
  ) {
    this.toastr.error("Cannot purchase Name Servers when payment is completed or under review.");
    return;
  }

 this.openPurchaseNameServerModal();
}
purchaseNameIdentifier() {
   if (
    this.domainDetail?.paymentStatus === 'Payment Completed' ||
    this.domainDetail?.paymentStatus === 'Payment Under Review'
  ) {
    this.toastr.error("Cannot purchase Name Identifiers when payment is completed or under review.");
    return;
  }
  
 this.openPurchaseNameIdentifierModal();
}
openPurchaseNameServerModal() {
  const modal = document.getElementById('purchaseNameServerModal');
  if (modal) {
     this.isPurchaseNameServerModalOpen = true;
    modal.style.display = 'block';
  } else {
  } 

}
isPurchaseNameIdentifierModalOpen: boolean = false;
openPurchaseNameIdentifierModal() {
  const modal = document.getElementById('purchaseNameIdentifierModal');
  if (modal) {
    this.isPurchaseNameIdentifierModalOpen = true;
    modal.style.display = 'block';
  } else {
  } 

}
numNameServersToPurchase: number = 0;
closePurchaseNameServerModal() {
  const modal = document.getElementById('purchaseNameServerModal'); 
  if (modal) {
     this.isPurchaseNameServerModalOpen = false;
    modal.style.display = 'none';
  }     
} 

numNameIdentifiersToPurchase: number = 0;
closePurchaseNameIdentifierModal() {
  const modal = document.getElementById('purchaseNameIdentifierModal'); 
  if (modal) {
     this.isPurchaseNameIdentifierModalOpen = false;
    modal.style.display = 'none';
  }     
} 
async confirmPurchaseNameServer() {
 // const modal = document.getElementById('purchaseNameServerModal');    
  // if (modal) {        
  //   modal.style.display = 'none';
  //   this.router.navigate(['/name-server'], {
  //     state: {      
 
  //       organisationId: this.domainDetail.organisationId,
  //       domainId: this.domainDetail.domainId,
  //       applicationId: this.domainDetail.applicationId,
  //       numNameServersToPurchase: this.numNameServersToPurchase,
       
  //       nameServerLength: this.domainDetail.nameServers ? this.domainDetail.nameServers.length : 0,
  //     },  
  //     queryParams: {
  //       domainId: this.domainDetail.domainId
  //     }
  //   });
  // }


  if(this.numNameServersToPurchase>0){
      const deptCode = "dr";
   
   //console.log(this.orgDetails);
   let amountPayable = 0;
 
   if(this.orgDetails.remainingFreeNameServers<=0){

       amountPayable = (this.priceforNameServer * this.numNameServersToPurchase);
      //  console.log(amountPayable)
   }
  //  return
   amountPayable=(amountPayable-(this.calculateTDS(amountPayable)))+(amountPayable*(this.gst/100));
   
  //  const url = "https://registrar.idrbt.ac.in/#/payment-response";
    //const url = "https://registraruat.idrbt.ac.in/api/dr/domain/paymentResponse";
   
    //SBI api path for regsitrar.idrbt.ac.in build
    //const url = `${environment.paymentURL}/dr/domain/paymentResponse`;
   
    //sbi api path for oracle migration build
    //const url = 'http://172.27.143.131:9008/dr/domain/paymentResponse';
    const url = environment.paymentUrl;
    //const url = 'https://registrarorc.idrbt.ac.in/payment/dr/domain/paymentResponse';
    //console.log(url);
    const otherDetails = this.domainDetail.domainId;
    // const otherDetails = domain.domainId+'^'+localStorage.getItem('jwtToken');
    // const paymentData = `${deptCode},${amountPayable},${returnUrl}`;
    // const hash = btoa(paymentData); // Encode data in Base64
 
    // const apiUrl = 'https://dev-serpmnt.idrbt.ac.in/pay1/ps/testPayment';
    const apiUrl = 'https://serpmnt.idrbt.ac.in/pay1/ps/payment';
    // const apiUrl = "http://localhost:18000/ps/testPayment";
    // const nameServers = await this.getNameServersOfDomain(domain.domainId);
    // if(nameServers.length<=0){
    //   this.tostr.warning("Please Add name servers for the domain before payment")
    //   return
    // }
  //  if(this.isOnboardingDomainPaid==false && (this.onBoardingDomainId!=domain.domainId)){
  //   this.tostr.warning("Please pay your onboarding domain first")
  //   return
  //  }
   
    //console.log(amountPayable)
    //console.log(this.numNameServersToPurchase)
    this.domainDetail.countOfNameServerToBePurchased = this.numNameServersToPurchase;
    this.updateDomainDetails(this.domainDetail);
      const transactionData = {
      transactionId: null,
      orderId:'',
      paymentTransactionId: '',
      amount: amountPayable,
      transactionStatus: 'Transaction Initiated',
      domainId: this.domainDetail.domainId,
      organisationId: this.domainDetail.organisationId,
      paymentFor:"NameServer"
    };
 
   //save transaction inititaion to transactions_table
    await this.saveTransaction(transactionData);
 
    await this.updateOngoingTransactionForDomain(this.domainDetail, this.savedTransaction.transactionId);
    //  await this.updatePaymentSatus(domain, 'Payment Completed');
    this.http.post<{ redirectUrl: string }>(apiUrl, { deptCode: deptCode, amount: amountPayable, returnUrl: url, otherDetails: otherDetails})
  .subscribe({
    next: response => {
      if (response.redirectUrl) {
        //console.log("Redirecting to Angular page...");
     
        //  this.disableAddDomain=false;
        //  this.enablePurchaseNameServer=false;
          this.closePurchaseNameServerModal();
       
        //  return;
        window.location.href = response.redirectUrl;
      }
    },
    error: error => {
    }
  });
  }
 
}

async confirmPurchaseNameIdentifier() {

  if(this.numNameIdentifiersToPurchase>0){
      const deptCode = "dr";
   
   let amountPayable = 0;
  
   if(this.orgDetails.aliasCountForOrganization>=this.initialBundleNameIdentifierCount){
       amountPayable = (this.priceForNI * this.numNameIdentifiersToPurchase);
   }
   amountPayable=(amountPayable-(this.calculateTDS(amountPayable)))+(amountPayable*(this.gst/100));
    
  
    const url = environment.paymentUrl;
    //const url = 'https://registrarorc.idrbt.ac.in/payment/dr/domain/paymentResponse';
    //console.log(url);
    const otherDetails = this.domainDetail.domainId;


    // https://serpmnt.idrbt.ac.in/pay1/ps/payment

    const apiUrl = ' https://serpmnt.idrbt.ac.in/pay1/ps/payment';

  //  const apiUrl = 'https://dev-serpmnt.idrbt.ac.in/pay1/ps/testPayment';
   
    //console.log(amountPayable)
    //console.log(this.numNameServersToPurchase)
    this.domainDetail.countOfNameIdentifierToBePurchased = this.numNameIdentifiersToPurchase;
    this.updateDomainDetails(this.domainDetail);
      const transactionData = {
      transactionId: null,
      orderId:'',
      paymentTransactionId: '',
      amount: amountPayable,
      transactionStatus: 'Transaction Initiated',
      domainId: this.domainDetail.domainId,
      organisationId: this.domainDetail.organisationId,
      paymentFor:"NameIdentifier"
    };
  
   //save transaction inititaion to transactions_table
    await this.saveTransaction(transactionData);
     //console.log(transactionData)

    await this.updateOngoingTransactionForDomain(this.domainDetail, this.savedTransaction.transactionId);
    //  await this.updatePaymentSatus(domain, 'Payment Completed');
    this.http.post<{ redirectUrl: string }>(apiUrl, { deptCode: deptCode, amount: amountPayable, returnUrl: url, otherDetails: otherDetails})
  .subscribe({
    next: response => {
      if (response.redirectUrl) {
          this.closePurchaseNameIdentifierModal();
        
        //  return;
        window.location.href = response.redirectUrl;
      }
    },
    error: error => {
    }
  });
  }
  
}
 allowPositiveNumbersOnly(event: KeyboardEvent) {
    const charCode = (event.which) ? event.which : event.keyCode;

    // Allow numbers (0-9)
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
      event.preventDefault(); // Prevent input if not a number
    }

    // Prevent negative sign (-) if it's the first character
    // If you want to disallow '-' anywhere, remove the `event.target.value.length === 0` check
    if (event.key === '-' && (event.target as HTMLInputElement).value.length === 0) {
      event.preventDefault();
    }
  }

  calculateTDS(amountPayable):number{
    const total = amountPayable;
  if(total>this.tdsStartsFrom){
    return total*this.tds
  }else {
    return 0
  };
}
tdsStartsFrom:number=0;
tds:number=0
async 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 'tds':
            // Convert to number using Number() or parseFloat()
            this.tds = Number(item.value);
            break;
            case 'tdsStartsFrom':
            this.tdsStartsFrom = Number(item.value);
            break;
          // Add other cases if you need to assign other values later
        }
        // this.populateCostItems();
        
      });

    },
    error: (error) => {
      //console.error('Error fetching static data:', error);
      if(error.status == HttpStatusCode.Unauthorized){
        this.router.navigateByUrl("/session-timeout")
      }
      // Handle error appropriately, e.g., show a user-friendly message
    }
  });
}

  // 🚀 Method to handle paste events
  onPaste(event: ClipboardEvent) {
    event.preventDefault(); // Prevent default paste behavior
    const pastedText = event.clipboardData?.getData('text');
    if (pastedText) {
      // Remove any non-numeric characters and negative sign if at the beginning
      let cleanedText = pastedText.replace(/[^0-9]/g, ''); // Remove non-digits
      if (cleanedText.startsWith('-')) { // Ensure no leading minus sign
        cleanedText = cleanedText.substring(1);
      }
      // Update ngModel value programmatically
      const inputElement = event.target as HTMLInputElement;
      const start = inputElement.selectionStart || 0;
      const end = inputElement.selectionEnd || 0;
      const currentValue = inputElement.value;

      const newValue = currentValue.substring(0, start) + cleanedText + currentValue.substring(end);

      // Ensure the new value is a valid positive number
      if (newValue === '' || /^\d+$/.test(newValue)) {
        this.numNameServersToPurchase = newValue === '' ? null : parseInt(newValue, 10);
        inputElement.value = newValue; // Update input field
        // Manually dispatch input event for ngModel to pick up changes immediately
        inputElement.dispatchEvent(new Event('input'));
      }
    }
  }
  orgDetails: any;
  async getOrgDetailsById(orgId: string) {
    this.organisationService.getOrganisationDetailsByOrganisationId(Number(orgId)).subscribe({
      next: (response) => {
        if (response.status === HttpStatusCode.Ok) {
          this.orgDetails = response.body;
          //console.log(this.orgDetails)
          if (
            this.domainDetail &&
            typeof this.domainDetail.paymentStatus !== 'undefined' &&
            this.orgDetails &&
            typeof this.orgDetails.remainingFreeNameServers !== 'undefined'
          ) {
            if (
              this.domainDetail.paymentStatus != 'Payment Completed' &&
              this.domainDetail.paymentStatus != 'Payment Under Review' &&
              this.domainDetail.paymentStatus != 'Payment Approved' &&
              this.domainDetail.paymentStatus != 'Payment Rejected'
            ) {
              if (this.orgDetails.remainingFreeNameServers > 0) {
                this.numNameServersToPurchase = this.orgDetails.remainingFreeNameServers;
              } else {
                this.disableAddDomain = false;
                this.enablePurchaseNameServer = false;
              }
            } else {
              if (this.domainDetail.remainingPurchasedNameServers > 0 && this.orgDetails.remainingFreeNameServers == 0) {
                this.numNameServersToPurchase = this.domainDetail.remainingPurchasedNameServers;
              } else {
                if(this.orgDetails.remainingFreeNameServers>0){
                   this.numNameServersToPurchase = this.orgDetails.remainingFreeNameServers;
                     this.enablePurchaseNameServer = false;
                     this.disableAddDomain=false;
                }else{
                this.disableAddDomain = true;
                this.enablePurchaseNameServer = true;
                }
              
              }
            }
          }
        }
      },
      error: (error) => {
        if (error.status === HttpStatusCode.Unauthorized) {
          this.router.navigateByUrl('/session-timeout');
        }
        if (error.status === HttpStatusCode.NotFound) {
          this.toastr.error('Organisation details not found.');
        }
      }
    });
  }
  priceDetails: any;
  priceforNameServer: number = 0
  maxNameServers: number = 0;
  maxNameIdentifiers:number = 0;
  initialBundleNameIdentifierCount:number =0;
  gst:number=0;
  priceForNI:number =0;
  async getNameServerPrice(){
   this.domainService.getAllPriceDetails().subscribe({
      next:(response)=>{
        this.priceDetails=response.body;
        const priceDetail=this.priceDetails.find(plan => plan.typeForPrice == "nameserver");
        const priceForNameIdentifier=this.priceDetails.find(plan => plan.typeForPrice == "alias");
        this.priceforNameServer=priceDetail.price*this.domainDetail.numberOfYears;
        this.initialBundleNameIdentifierCount=priceForNameIdentifier.nsRecordCount;
        this.priceForNI=priceForNameIdentifier.price*this.domainDetail.numberOfYears;
        this.maxNameServers = priceDetail.maxNameServer;
        this.maxNameIdentifiers = priceDetail.maxAlias;
        this.gst=priceDetail.gst;
      },error:(error)=>{
      }
    })
  }
 

  async sendDataToNixi(nameServer) {
    let nameServerArray = [];
     if(this.domainDetail.status === 'Inactive'){
        this.toastr.error('The domain of this Entity is not active yet. please approve the domain to approve name servers.');
        return;
      }
    nameServerArray[0]= nameServer;
    //nameServerArray[0].organisationId = this.domainDetail.organisationId;
    this.nameServerService.sendNameServerToNixi(nameServerArray, this.domainDetail.domainId).subscribe({
      next: (response) => {
        if (response.status === HttpStatusCode.Ok) {
          this.toastr.success('Name server data sent to Registry successfully.');
          this.getNameServersByDomainId(this.domainId);
        }
      },
      error: (error) => {
        if (error.status === HttpStatusCode.Unauthorized) {

          this.router.navigateByUrl('/session-timeout');


        } else {
          this.toastr.error("The request to send name server to registry couldn't be processed at the moment. please try again later");
        }
      }
    });
  }
 async updateDomainDetails(domain: any) {
  try {
    const response = await lastValueFrom(this.domainService.updateDomainDetails(domain));

    if (response.status === HttpStatusCode.Ok) {
      // this.domainDetail = response.body;
      // return this.domainDetail;
    this.domainDetail= await this.getDomainById(domain.domainId);
      // this.toastr.success('Domain details updated successfully.');
    } else {
      return null
      // this.toastr.error('Failed to update domain details.');
    }
  } catch (error: any) {
    if (error.status === HttpStatusCode.Unauthorized) {
      this.router.navigateByUrl('/session-timeout');
    } else {
      // this.toastr.error('Error updating domain details.');
    }
  }
}
  savedTransaction:any = null;
async saveTransaction(transactionData: any) {
  await lastValueFrom(this.domainApplicationService.saveTransaction(transactionData)).then(
    response => {
      if(response.status === HttpStatusCode.Created) {
        this.savedTransaction = response.body;
      }
    }
  )
}

async updateOngoingTransactionForDomain(domain, trxnId){
  domain.transactionId = trxnId;
  await lastValueFrom(this.domainService.updateDomainDetails(domain)).then(
    response => {
      if(response.status === HttpStatusCode.Ok) {
        
      }
    }
  )
}
isEditMode = false;

toggleEditMode() {
  this.isEditMode = !this.isEditMode;
  this.getDnsSecDetailsByDomainId(this.domainId);
}
dnssecDetailsList: any[];
dnsSecDetailsCount: number = 0;
async getDnsSecDetailsByDomainId(domainId: number){

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

  }

}
isDnsSecModelOpen:boolean=false;
addDnssecDetailsList=[]

openModelForAddDns(){
  if(this.dnssecDetailsList.length<3){
  document.getElementById("addDnsSec").click();
  this.addDNSSECDtls();
  }

}
MAX_DNSSEC_RECORDS=3
addDNSSECDtls() {
  const totalRecords = this.dnssecDetailsList.length + this.addDnssecDetailsList.length;


  // Check if the total number of records is less than the maximum allowed.
  if (totalRecords < this.MAX_DNSSEC_RECORDS) {
    //console.log('Adding new DNSSEC record...');
    this.addNewDnsSecRecord();
  } else {
  }
}
  addNewDnsSecRecord(): void {
    this.addDnssecDetailsList.push(this.getNewDnssecRecord());
  }

  // Called when "Add Additional DS Records" is clicked
  addAdditionalRecords(): void {
  this.addDnssecDetailsList.push(this.getNewDnssecRecord());
}
  removeRecord(index: number): void {
    this.addDnssecDetailsList.splice(index, 1);
  }
    getNewDnssecRecord(): DnssecDetails {
    return {
      id:0,
      keyTag: '',
      algorithmType: '',
      algorithmTypeCode: '',
      digestType: '',
      digestTypeCode:'',
      digest: '',
      domainId:0,
      organisationId:0
    };
  }
  algorithmTypeOptions = [];
onAlgorithmChange(code: string, dns: DnssecDetails) {
  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 = [];

   async saveDNSSecRecords() {
    this.dnssecDetailsList =[...this.addDnssecDetailsList];
    if(this.dnssecDetailsList.length < 1){
      //console.log('No DNS SEC Records added....')
      return;
    }
    try{
       this.formSubmitted = true;
       if (this.isFormValid()) {
      this.dnssecDetailsList.forEach(dnsSec => {
        dnsSec.domainId = this.domainId;
        dnsSec.organisationId = this.domainDetail.organisationId;
      })
      const response = await lastValueFrom(this.dnsSecService.saveAllDnsSecRecords(this.dnssecDetailsList));
      if(response.status === HttpStatusCode.Created){
        await this.getDnsSecDetailsByDomainId(this.domainId);
        //this.dnssecDetailsList=response.body
        if(this.domainDetail.status=="Active"){
              this.updateDnsSec();
        }
      
       this.closeDnsAddModal()
      }
    }
    }catch(error){
    }
  }

  clearAddDnsList(){
    // document.getElementById("closeAddDnsSec").click();
    this.addDnssecDetailsList=[]
  
  }

  clearError(){
    this.addNameIdentifierErrorMsg='';
    document.getElementById('closeButtonForPaymentOfNameIdentifier').click();
    window.location.reload();
  }

 formSubmitted: boolean = false; 
isFormValid(): boolean {

  // Combine both lists (existing + new)
  const allRecords = [
    ...(this.dnssecDetailsList || [])
    // ...(this.addDnssecDetailsList || [])
  ];

  if (allRecords.length === 0) {
    return true;
  }

  //console.log(allRecords);
  
  for (let i = 0; i < allRecords.length; i++) {
    const dnsSec = allRecords[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 uniqueness check across both lists
    const duplicateIndex = allRecords.findIndex(
      (other, j) => j !== i && other.digest?.trim() === dnsSec.digest?.trim()
    );
    if (duplicateIndex !== -1) {
      return false;
    }

  }

  return true;
}

isUpdateFormValid(): boolean {

  const allRecords = [
    ...(this.dnssecDetailsList || []),
    ...(this.addDnssecDetailsList || [])
  ];

  if (allRecords.length === 0) {
    return true;
  }

  
  for (let i = 0; i < allRecords.length; i++) {
    const dnsSec = allRecords[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;
    }
    //console.log(`  - Digest Type is valid.`);

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

    // 5. Digest uniqueness check across both lists
    const duplicateIndex = allRecords.findIndex(
      (other, j) => j !== i && other.digest?.trim() === dnsSec.digest?.trim()
    );
    if (duplicateIndex !== -1) {
     
      return false;
    }

  }

  return true;
}

  closeDnsAddModal(){
    document.getElementById('addDnsSec').click()
     this.formSubmitted = false;
    this.clearAddDnsList();
    this.getDnsSecDetailsByDomainId(this.domainId);
  }

  async updateDnsSec(){
    if(this.dnssecDetailsList.length < 1){
      return;
    }
    try{
      //console.log(this.isFormValid())
       this.formSubmitted = true;
       if (this.isUpdateFormValid()) {
      this.dnssecDetailsList.forEach(dnsSec => {
        dnsSec.domainId = this.domainId;
        dnsSec.organisationId = this.domainDetail.organisationId;
      })
      //console.log(this.dnssecDetailsList);
      const response = await lastValueFrom(this.dnsSecService.updateAllDnsSecRecords(this.dnssecDetailsList));
      // if(response.status === HttpStatusCode.Created){
        this.isEditMode=false
      if(response.status === HttpStatusCode.NoContent){
        this.toastr.warning('DNSSEC validation failed. Please verify your DNSSEC configuration data and resubmit with correct information.');
      }else if(response.status === HttpStatusCode.Ok){
        this.toastr.success('DNS SEC Details udpated successfully.')
      } 
    }
    }catch(error){
    }
  }

 async getDnsAlgorithmType() {
  try {
    const result = await lastValueFrom(this.dnsSecService.getDnsAlgorithmTypes());
    //console.log(result.body);
    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();
        }
  }
}
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 sendDnsSecToNixi(dnsSec: DnssecDetails) {
  if (this.domainDetail.status === 'Inactive') {
    this.toastr.error('The domain of this Entity is not active yet. Please approve the domain to approve DNSSEC.');
    return;
  }

  try {
    const response = await lastValueFrom(
      this.dnsSecService.sendDnsSecToNixi(dnsSec, this.domainDetail.domainId)
    );

    if (response.status === HttpStatusCode.Ok) {
      this.toastr.success('DNSSEC data sent to Registry successfully.');
      this.getDnsSecDetailsByDomainId(this.domainId);
    }
  } catch (error: any) {
    if (error.status === HttpStatusCode.Unauthorized) {
      this.router.navigateByUrl('/session-timeout');
    } else {
      this.toastr.error("The DNSSEC details are invalid to submit to Registry.");
    }
  }
}


isDigestDuplicate(currentIndex: number, fromAddList: boolean = false): boolean {
  const list = fromAddList ? this.addDnssecDetailsList : this.dnssecDetailsList;
  const currentValue = list[currentIndex]?.digest?.trim();
  if (!currentValue) return false;

  // Combine both lists
  const allRecords = [
    ...(this.dnssecDetailsList || []),
    ...(this.addDnssecDetailsList || [])
  ];

  return allRecords.some((item, idx) => 
    // We need to avoid comparing with itself (so check by reference, not just index)
    item !== list[currentIndex] && item.digest?.trim() === currentValue
  );
}


addIdentifiers(){

  // BLOCK ONLY THESE 2 CASES
  if (
    this.domainDetail.paymentStatus === "Payment Completed" ||
    this.domainDetail.paymentStatus === "Payment Under Review"
  ) {
    this.toastr.error("Cannot add Name Identifiers when payment is completed or under review.");
    return;
  }

  // KEEP YOUR EXISTING LOGIC (NO CHANGE)
  if(
    (
      this.domainDetail.paymentStatus=="Payment Not Done" ||
      this.domainDetail.paymentStatus=="Payment Failed" ||
      this.domainDetail.paymentStatus=="Payment Cancelled" ||
      this.domainDetail.paymentStatus=="Ready For Payment" ||
      this.orgDetails.aliasCountForOrganization < 5 ||
      this.domainDetail.remainingPurchasedNameIdentifiers > 0 ||
      this.orgDetails.remainingFreeNameIdentifiers > 0
    ) 
    && this.aliasList.length < this.maxNameIdentifiers
  ){
    document.getElementById("addNameIdentifier").click();
  }
}

addNameIdentifiers:string='';
NameIdentifier:string=this.assetService.nameIdentifiers;
addNameIdentifierErrorMsg
async addNameIdentifierss(): Promise<void> {
  if (!this.addNameIdentifiers) return; // Add null checks
  this.validateSpaceAndDomainName("update");
  if(this.addNameIdentifierErrorMsg!=""){
    return
  }
  const reserverdAlia = await this.getAliasByAliasName(this.addNameIdentifiers);
  console.log("reserverd Aliad"+"+++++++++++++++++++++++++++++"+reserverdAlia)


  if (reserverdAlia) {
    console.log("This alias is already taken");
    this.addNameIdentifierErrorMsg = "This "+ this.NameIdentifier + " is already taken";
    return;
  }
else {
    this.addNameIdentifierErrorMsg = '';

  }

}

validateSpaceAndDomainName(addOrUpdate){
  if(addOrUpdate=='add'){
    if (!this.addNameIdentifiers || this.addNameIdentifiers.includes(' ')) {
      this.addNameIdentifierErrorMsg = "Domain name cannot be empty or contain spaces";
      return;
    }
   
  }else if(addOrUpdate=='update'){
      if (!this.addNameIdentifiers || this.addNameIdentifiers.includes(' ')) {
      this.addNameIdentifierErrorMsg = "Domain name cannot be empty or contain spaces";
      return;
    }
  }
 

}
async getAliasByAliasName(aliasName: string): Promise<boolean> {
  if (!aliasName) {
    return false; // Returning a boolean as expected
  }

  try {
    const response = await lastValueFrom(this.domainService.getAliasName(aliasName));
    return response.body !== null; // Returns true if body exists, false otherwise
  } catch (error) {
    return false; // Handle errors by returning false
  }
}

async validateNameIdentifier(nameIdentifier: string) {
  console.log(nameIdentifier);
  
  // Check if domain starts with a digit
  if (/^\d/.test(nameIdentifier)) {
    this.addNameIdentifierErrorMsg = this.NameIdentifier+' cannot start with a digit';
  }else if(await this.getAliasByAliasName(nameIdentifier)){
    this.addNameIdentifierErrorMsg = 'This Name Identifier '+nameIdentifier+' is already taken';
  }
  else if(nameIdentifier.length === 0 || nameIdentifier == null || nameIdentifier.trim() === ''){
    this.addNameIdentifierErrorMsg = 'Name identifier is required'
  }
  // Check if domain is less than 3 characters
  else if (nameIdentifier.length < 2) {
    this.addNameIdentifierErrorMsg = this.NameIdentifier+' must be at least 2 characters long';
  } else {
    // Updated regex to validate the domain structure
    const regex = /^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)?$/;
 
    if (!regex.test(nameIdentifier)) {
      this.addNameIdentifierErrorMsg = 'Please enter a valid '+this.NameIdentifier;
    } else {
      this.addNameIdentifierErrorMsg = '';  // Reset error message if valid
    }
  }
 
}
nameIdentifiersList=[];
aliasData :AliasData={
  id: 0,
  aliasName: '',
  cost: 0,
  domainId: 0
}
  async saveAliasNameForDomain() {
    console.log("-> Starting saveAliasNameForDomain function.");
    console.log("Initial domainDetail.aliasPrice:", this.domainDetail.aliasPrice); // Initial Check
    await this.addNameIdentifierss();
    console.log("Name identifier to save (this.addNameIdentifiers):", this.addNameIdentifiers);

    await this.validateNameIdentifier(this.addNameIdentifiers);
    const beforeSave = this.domainDetail;
    
    if (this.addNameIdentifierErrorMsg == '') {
      console.log("Validation successful. Proceeding with alias saving.");
      
      // Initialize alias data
      this.aliasData.aliasName = this.addNameIdentifiers;
      this.aliasData.domainId = this.domainId;
      console.log("Alias data initialized:", this.aliasData);

      // Log the state before the conditional logic
      console.log("Current state - orgDetails.aliasCountForOrganization:", this.orgDetails.aliasCountForOrganization);
      console.log("Current state - domainDetail.remainingPurchasedNameIdentifiers:", this.domainDetail.remainingPurchasedNameIdentifiers);
      console.log("Current state - orgDetails.remainingFreeNameIdentifiers:", this.orgDetails.remainingFreeNameIdentifiers);

      // Main IF block
      if (this.orgDetails.aliasCountForOrganization > 5 && ((this.domainDetail.remainingPurchasedNameIdentifiers ?? 0) < 1) && (this.orgDetails.remainingFreeNameIdentifiers ?? 0) < 1) {
        console.log("--- IF Block: Condition met (Org > 5 aliases AND no purchased/free identifiers left). Alias will be paid.");
        this.aliasData.cost = this.priceForNI;
        console.log("New alias cost set to priceForNI:", this.aliasData.cost);
        this.orgDetails.aliasCountForOrganization += 1;
        console.log("orgDetails.aliasCountForOrganization incremented to:", this.orgDetails.aliasCountForOrganization);
      } else {
        console.log("--- ELSE Block: Checking sub-conditions for free/purchased identifiers.");
        
        // ELSIF 1: Free identifiers available
        if ((this.orgDetails.remainingFreeNameIdentifiers ?? 0) > 0) {
          console.log("---- ELSIF 1: remainingFreeNameIdentifiers > 0. Using a FREE identifier.");
          this.orgDetails.aliasCountForOrganization += 1;
          this.orgDetails.remainingFreeNameIdentifiers = Math.max(
            0,
            (this.orgDetails.remainingFreeNameIdentifiers ?? 0) - 1
          );
          this.domainDetail.countOfFreeNameIdentifiersUsed += 1;
          this.aliasData.cost = 0;
          console.log("orgDetails.remainingFreeNameIdentifiers decremented to:", this.orgDetails.remainingFreeNameIdentifiers);
          console.log("aliasData.cost set to 0.");
          
        // ELSIF 2: Purchased identifiers available
        } else if ((this.domainDetail.remainingPurchasedNameIdentifiers ?? 0) > 0) {
          console.log("---- ELSIF 2: remainingPurchasedNameIdentifiers > 0. Using a PURCHASED identifier.");
          this.domainDetail.remainingPurchasedNameIdentifiers -= 1;
          this.orgDetails.aliasCountForOrganization += 1;
          this.aliasData.cost = this.priceForNI;
          console.log("domainDetail.remainingPurchasedNameIdentifiers decremented to:", this.domainDetail.remainingPurchasedNameIdentifiers);
          console.log("aliasData.cost set to priceForNI:", this.aliasData.cost);

        // ELSIF 3: Organization < 5 aliases OR free identifiers available (This condition looks redundant, but is being logged as written)
        } else if (this.orgDetails.aliasCountForOrganization < 5 || (this.orgDetails.remainingFreeNameIdentifiers ?? 0) > 0) {
          console.log("---- ELSIF 3: Org < 5 aliases OR remainingFreeNameIdentifiers > 0. Using a FREE identifier (This path likely means a free identifier is available).");
          this.orgDetails.aliasCountForOrganization += 1;
          this.orgDetails.remainingFreeNameIdentifiers = Math.max(
            0,
            (this.orgDetails.remainingFreeNameIdentifiers ?? 0) - 1
          );
          this.domainDetail.countOfFreeNameIdentifiersUsed += 1;
          this.aliasData.cost = 0;
          console.log("orgDetails.remainingFreeNameIdentifiers decremented to:", this.orgDetails.remainingFreeNameIdentifiers);
          console.log("aliasData.cost set to 0.");
          
        // FINAL ELSE: New paid alias
        } else {
          console.log("---- FINAL ELSE: No free/purchased available. This is a NEW PAID alias.");
          this.orgDetails.aliasCountForOrganization += 1;
          this.aliasData.cost = this.priceForNI;
          
          // !!! LOG POINT: aliasPrice being calculated/updated inside the payment logic !!!
          const oldAliasPrice = (this.domainDetail.aliasPrice ?? 0);
          this.domainDetail.aliasPrice = oldAliasPrice + this.aliasData.cost;
          console.log("!!! aliasPrice UPDATE (Inside FINAL ELSE): Old Price:", oldAliasPrice, "+ New Cost:", this.aliasData.cost, "= New Price:", this.domainDetail.aliasPrice);
          
          console.log("aliasData.cost set to priceForNI:", this.aliasData.cost);
          console.log("domainDetail.aliasPrice updated to:", this.domainDetail.aliasPrice);
        }
      }

      this.nameIdentifiersList[0] = this.aliasData;
      console.log("Name identifiers list prepared for API:", this.nameIdentifiersList);

      const response = await lastValueFrom(this.domainService.saveAliasForDomain(this.domainId, this.nameIdentifiersList))
      console.log("<- API call successful. Response received:", response);
      
      console.log("Updating local data after successful save.");
      await this.getAliasName(this.domainId);
      // await this.updateOrgDetails(this.orgDetails);
      
      // !!! LOG POINT: aliasPrice being updated AFTER API call !!!
      console.log("!!! aliasPrice UPDATE (After API Call): beforeSave.aliasPrice:", beforeSave.aliasPrice, "+ this.priceForNI:", this.priceForNI);
      // if()
      // this.domainDetail.aliasPrice = beforeSave.aliasPrice + this.priceForNI; 
      
      console.log("domainDetail.aliasPrice updated post-save to:", this.domainDetail.aliasPrice);
      // await this.updateDomainDetails(this.domainDetail);

      // Payment Status Check Block
      console.log("Checking payment status for post-save actions. Current status:", this.domainDetail.paymentStatus);
      const pendingStatuses = ['Ready For Payment', 'Payment Rejected', 'Payment Failed', 'Payment Cancelled', 'Payment Aborted', 'Unknown Status', 'Payment Not Done'];
      
      if (!pendingStatuses.includes(this.domainDetail.paymentStatus)) {
        console.log("Payment status is NOT pending. Clearing error.");
        this.clearError();
      }
      
      if (pendingStatuses.includes(this.domainDetail.paymentStatus)) {
        console.log("Payment status IS pending. Initiating payment validation/processing.");
        await this.validateAndPayOnUpdate(this.domainDetail);
        this.clearError();
      }
      
      console.log("Cleaning up input fields.");
      this.addNameIdentifiers = '';
      this.nameIdentifiersList = [];
    }
    error: (error) => {
      console.error("An error occurred during alias saving:", error);
    }
    console.log("<- saveAliasNameForDomain function finished.");
  }
async updateOrgDetails(orgDetails){
  const orgDetailResp = await lastValueFrom(this.organisationService.updateOrganisationDetails(orgDetails)).then(
    resp=>{
      this.orgDetails=resp.body;
    }
  )
}

  async deleteDnsSecOnRegistrarAction(isdeleteApproved: boolean, dns: any) {
    if (isdeleteApproved) {
      const confirm = window.confirm('Are you sure you want to delete this DNSSEC record?');
      if (confirm) {
        try {
          const response: HttpResponse<any> = await lastValueFrom(this.dnsSecService.deleteDnsSecById(dns.id));
          if (response.status === HttpStatusCode.Ok) {
            const isDeleted: boolean = response.body;
            if (isDeleted) {
              this.toastr.success('DNSSEC record deleted successfully.');
              await this.getDnsSecDetailsByDomainId(this.domainId);
            } else {
              this.toastr.error("Your request to delete DNSSEC record couldn't be processed at the moment, please try again later .");
            }
          }
        } catch (error: any) {
          if (error.status === HttpStatusCode.Unauthorized) {
            await this.navigateToSessionTimeout();
          } else if (error.status === HttpStatusCode.InternalServerError) {
            this.toastr.error("Your request to delete DNSSEC record couldn't be processed at the moment, please try again later .");
          }
        }
      } else {
        this.toastr.info('DNSSEC record deletion cancelled.');
      }
    } else {
      //if delete rejected, reset the deleted request flag to false
      await this.rejectDeleteRequest(false, dns);
      await this.getDnsSecDetailsByDomainId(this.domainId);
    }
    
  }

  async rejectDeleteRequest(deleteRequest: boolean, dns: any) {
    if (deleteRequest === false) {
      await lastValueFrom(this.dnsSecService.sendDeleteRequest(deleteRequest, dns.id)).then(
          response => {
            if (response.status === HttpStatusCode.Ok) {
                 this.toastr.success('DNSSEC delete request rejeted.');

              this.getDnsSecDetailsByDomainId(this.domainId);
            }
          }
        )
    }
  }
  async sendDeleteRequest(deleteRequest, dns){
    if (deleteRequest === true) {
        await lastValueFrom(this.dnsSecService.sendDeleteRequest(deleteRequest, dns.id)).then(
          response => {
            if (response.status === HttpStatusCode.PartialContent) {
                 this.toastr.success('DNSSEC delete request sent successfully.');
              this.getDnsSecDetailsByDomainId(this.domainId);
            }
          }
        )
    }else{
      const confirm = window.confirm('Are you sure you want to delete this DNSSEC record?');
      if (confirm) {
        try {
          const response: HttpResponse<any> = await lastValueFrom(this.dnsSecService.deleteDnsSecById(dns.id));
          if (response.status === HttpStatusCode.Ok) {
            const isDeleted: boolean = response.body;
            if (isDeleted) {
              this.toastr.success('DNSSEC record deleted successfully.');
              await this.getDnsSecDetailsByDomainId(this.domainId);
            } else {
              this.toastr.error("Your request to delete DNSSEC record couldn't be processed at the moment, please try again later .");
            }
          }
        } catch (error: any) {
          if (error.status === HttpStatusCode.Unauthorized) {
            await this.navigateToSessionTimeout();
          } else if (error.status === HttpStatusCode.InternalServerError) {
            this.toastr.error("Your request to delete DNSSEC record couldn't be processed at the moment, please try again later .");
          }
        }
      } else {
        this.toastr.info('DNSSEC record deletion cancelled.');
      }
    }
    
  }

  async validateAndPayOnUpdate(domain){
    try{
      const response = await lastValueFrom(this.domainApplicationService.validateAndPayOnUpdate(domain));
      if(response.status === HttpStatusCode.PartialContent){
        // return response.body;
      }else{
        return null;
      }
    }catch(error){
      if(error.status === HttpStatusCode.Unauthorized){
        this.navigateToSessionTimeout();
      }
    }
    return null;
  }

  async deleteOrRequestDeleteForNameIdentifier(nameIdentifier) {
  const confirmDelete = window.confirm('Are you sure you want to delete this name identifier - ' + nameIdentifier.aliasName + '?');

  if (confirmDelete) {
    try {
      const response: HttpResponse<any> = await lastValueFrom(
        this.domainService.softDeleteNameIdentifier(nameIdentifier.aliasId) 
      );

      if (response.status === HttpStatusCode.Ok) {
        this.toastr.success('NameIdentifier deleted successfully.');
        await this.getAliasName(this.domainId);
        await this.getOrgDetailsById(this.domainDetail.organisationId);
        await this.getAllInvoicesDataByDomainId(this.domainId)
      } else if (response.status === HttpStatusCode.NotFound) {
         this.toastr.warning('NameIdentifier not found or already deleted.');
      } else {
        this.toastr.error('Could not delete NameIdentifier at the moment. Please try again later.');
      }

    } catch (error) {
      console.error('Error deleting NameIdentifier:', error);
      this.toastr.error('Could not delete NameIdentifier at the moment. Please try again later.');
    }
  } else {
    this.toastr.info('Name Identifier deletion cancelled.');
  }
}


  async deleteNsRec(ns){
    if(this.domainDetail?.nameServers.length>2){
      try{
      const deletedNs = lastValueFrom(this.nameServerService.deleteNameServer(ns.nameServerId))
      if(deletedNs){
        this.toastr.success("Deleted ns successfully");
      }
    }catch{

    }
    }else{
      this.toastr.warning("Cannot delete as two name server is mandatory for domain")
    }
    
  }

  async deleteNsOnRegistrarAction(isdeleteApproved: boolean, ns: any) {
    console.log(ns)
    // return
    if (isdeleteApproved) {
      const confirm = window.confirm('Are you sure you want to delete this Name Server record?');
      if (confirm) {
        try {
          console.log(ns.nameServerId)
          const response: HttpResponse<any> = await lastValueFrom(this.nameServerService.deleteNameServer(ns.nameServerId));
          console.log(response.body)
          if (response.status === HttpStatusCode.Ok) {
            const isDeleted: boolean = response.body;
            if (isDeleted) {
              this.toastr.success('Name Server record deleted successfully.');
              await this.getNameServersByDomainId(this.domainId);
            } else {
              this.toastr.error("Your request to delete Name Server record couldn't be processed at the moment, please try again later .");
            }
          }
        } catch (error: any) {
          if (error.status === HttpStatusCode.Unauthorized) {
            await this.navigateToSessionTimeout();
          } else if (error.status === HttpStatusCode.InternalServerError) {
            this.toastr.error("Your request to delete Name Server record couldn't be processed at the moment, please try again later .");
          }
        }
      } else {
        this.toastr.info('Name Server record deletion cancelled.');
      }
    } else {
      //if delete rejected, reset the deleted request flag to false
      await this.rejectDeleteRequestForNameServer(false, ns);
      await this.getNameServersByDomainId(this.domainId);
    }
    
  }

  async rejectDeleteRequestForNameServer(deleteRequest: boolean, dns: any) {
    if (deleteRequest === false) {
      // need to add this method for nameServer
      await lastValueFrom(this.nameServerService.sendDeleteRequest(deleteRequest, dns.nameServerId)).then(
          response => {
            if (response.status === HttpStatusCode.Ok) {
                 this.toastr.success('Name Server delete request rejeted.');

              this.getNameServersByDomainId(this.domainId);
            }
          }
        )
    }
  }
async sendDeleteRequestForNameServer(deleteRequest, ns){
    const nameServers = this.domainDetail.nameServers;
    if (deleteRequest === true) {
      if (nameServers.length > 2) {
    // Count the number of name servers where registrarApprovalForDeletion is false
    const countNotApproved = nameServers
  .filter(ns => ns.registrarApprovalForDeletion === false || ns.registrarApprovalForDeletion === null)
  .length;
    console.log(countNotApproved)
  // return
    if (countNotApproved <= 2) {
      // Show toastr message
        this.toastr.error('Minimum two approved name servers are required for the domain');
      return; // stop further processing
    }
    const countSentToNixi = nameServers.filter(ns => ns.isnameServerSentToNixi === true).length;
    console.log(countSentToNixi)
    if (countSentToNixi <=2) {
      this.toastr.error('At least three approved name servers are required to send delete request to registrar');
      return;
    }
  }else{
      this.toastr.error('Minimum two name servers are required for the domain');
      return;
  }
        await lastValueFrom(this.nameServerService.sendDeleteRequest(deleteRequest, ns.nameServerId)).then(
          response => {
            if (response.status === HttpStatusCode.PartialContent) {
                 this.toastr.success('Name Server delete request sent successfully.');
              this.getNameServersByDomainId(this.domainId);
            }
          }
        )
    }else{
      if(this.domainDetail.nameServers.length>2){
          const confirm = window.confirm('Are you sure you want to delete this Name Server record?');

      if (confirm) {
        try {
          const response= await lastValueFrom(this.nameServerService.deleteNameServer(ns.nameServerId));
          console.log(response)
          if (response.status === HttpStatusCode.Ok) {
            const isDeleted: boolean = response.body;
            if (isDeleted) {
              this.toastr.success('Name Server record deleted successfully.');
              await this.getNameServersByDomainId(this.domainId);
              if(this.orgDetails!=null && this.orgDetails!=undefined){
                // console.log(this.orgDetails?.organisationId);
                 await this.getOrgDetailsById(this.orgDetails?.organisationId);
              }
              if(this.domainId!=null && this.domainId!=0 && this.domainId!=undefined){
                  await this.getAllInvoicesDataByDomainId(this.domainId);
              }
             
            } else {
              this.toastr.error("Your request to delete Name Server record couldn't be processed at the moment, please try again later .");
            }
          }
        } catch (error: any) {
          console.log(error)
          if (error.status === HttpStatusCode.Unauthorized) {
            await this.navigateToSessionTimeout();
          } else if (error.status === HttpStatusCode.InternalServerError) {
            this.toastr.error("Your request to delete Name Server record couldn't be processed at the moment, please try again later .");
          }
        }
      } else {
        this.toastr.info('Name Server record deletion cancelled.');
      }
      }else{
        this.toastr.warning("Minimum 2 name server are required for the domain");
      }
      
    }
    
  }



  isEditing: boolean = false;
editableDomainName: string = '';
chosenDomainName: string = '';
tenures: number[] = [1,2,3,4,5,6,7,8,9,10];
selectedTenure: number = 0;

domainNameError: string = '';

validateDomainName(): boolean {
  // Clear previous error
  this.domainNameError = '';

  // Required check
  if (!this.chosenDomainName || this.chosenDomainName.trim() === '') {
    this.domainNameError = 'Domain name is required.';
    return false;
  }

  // Min length check
  if (this.chosenDomainName.length < 2) {
    this.domainNameError = 'Domain name must be at least 2 characters.';
    return false;
  }

  // Max length check
  if (this.chosenDomainName.length > this.domainMaxLength) {
    this.domainNameError = 'Domain name must not exceed '+this.domainMaxLength +' characters.';
    return false;
  }

  // Pattern check
  const pattern = /^[a-z]+([a-z0-9-]*[a-z0-9])?$/;
  if (!pattern.test(this.chosenDomainName)) {
    this.domainNameError = 'Domain name must start with a lowercase letter, can include digits or hyphens, and cannot end with a hyphen.';
    return false;
  }

  return true;
}

domainMaxLength:number = 0;
getMaxDomainLength() {
  this.userdomainService.getDomainMaxLength('domainMaxLength').subscribe({
    next: (response) => {
      // this.userDomainForm.get('zone')?.setValidators([Validators.required, Validators.maxLength(response[0].value)]);
       const resp = response;
      resp.forEach((element: any) => {
        if (element.type === 'domainMaxLength') {
          this.domainMaxLength = element.value;
        }
      });
    },
    error: (error) => {
      if (error.status === HttpStatusCode.Unauthorized) {
        this.router.navigateByUrl('/session-timeout')
      }
    }
  });
}


@ViewChild('domainModal') domainModal!: ElementRef;
isDomainAvailable: boolean = true;

changeInDomainName: boolean = false; // spelling same as your code


setDomainName() {
  // ✅ use domainName (NOT bankName)
  this.chosenDomainName = this.domainDetail.bankName;

  // keep tenure
 // this.selectedTenure = this.domainDetail.numberOfYears;
}

async onKeyupDomainName(){

  if(this.domainNameError){
    this.toastr.error(this.domainNameError);
    return;
  }

  // ✅ SAME DOMAIN → no API call
  if(this.chosenDomainName === this.domainDetail.bankName) {
    this.isDomainAvailable = true;
    this.changeInDomainName = false;

    const modal = new Modal(this.domainModal.nativeElement);
    modal.show(); // ✅ show here

    return;
  }

  // ✅ Alias check (keeping your logic)
  const alreadyPresent = await this.getAliasByAliasName(this.chosenDomainName);

  if(alreadyPresent){
    this.isDomainAvailable = false;

    const modal = new Modal(this.domainModal.nativeElement);
    modal.show(); // ✅ show result

    return;
  }

  this.changeInDomainName = true;

  try {
    const response = await lastValueFrom(
      this.userdomainService.checkDomainCombination(
        this.chosenDomainName,
        this.domainDetail.domainName,
        "",
        ""
      )
    );

    this.isDomainAvailable = response;

  } catch (error) {
    this.toastr.error("Error checking domain");
    this.isDomainAvailable = false;
  }

  // ✅ SHOW MODAL AFTER RESULT
  const modal = new Modal(this.domainModal.nativeElement);
  modal.show();
}

async updateDomainNameAndTenure() {

  if (!this.isDomainAvailable) {
    this.toastr.error("Domain not available");
    return;
  }

  if (!this.isEditAllowed()) {
    this.toastr.error("Editing not allowed");
    return;
  }



  // ✅ Save existing nameServers
  const existingNameServers = this.domainDetail?.nameServers;

  this.domainDetail.bankName = this.chosenDomainName;
 // this.domainDetail.numberOfYears = this.selectedTenure;

  await this.updateDomainDetails(this.domainDetail);

  // ✅ Restore nameServers (IMPORTANT FIX)
  this.domainDetail.nameServers = existingNameServers;

  this.toastr.success("Updated successfully");

  document.getElementById('closeDomainName')?.click();

  this.isEditing = false;
}

isEditAllowed(): boolean {
  const appStatus = this.domainDetail?.applicationStatus;
  const payStatus = this.domainDetail?.paymentStatus;

  return appStatus !== 'Approved' &&
         !['Payment Completed', 'Payment Under Review', 'Payment Approved', 'Payment Rejected'].includes(payStatus);
}

fileName: string = '';
 selectedFile: File | null = null;
  dialogRef!: MatDialogRef<any>;
  selectedFileName: string = 'No File Selected';
fileType: string = '';

onFileSelected(event: Event): void {
  const input = event.target as HTMLInputElement;
  if (input.files && input.files.length > 0) {
    this.selectedFile = input.files[0];
    this.selectedFileName = input.files[0].name;
    //console.log(`File selected: ${this.selectedFile.name}`);
    this.fileType = this.selectedFile.type;
    this.fileName = this.selectedFileName;
  }
}


selectedDocFile = {
  fileName: '',
  fileSize: 0,
  organisationId: 0,
  file: null,
  contactType: 'Domain'
};
docFileName: string = '';
onDocFileSelected(event: any) {
  const file: File = event.target.files[0];
  //console.log("Selected file:", file);

  if (file) {

    const allowedTypes = ['image/jpeg', 'image/jpg', 'application/pdf'];

    if (!allowedTypes.includes(file.type)) {
      this.toastr.error('Only JPG, JPEG, and PDF files are allowed.');
      this.selectedDocFile.file = null;
      this.docFileName = '';
      event.target.value = ''; // reset the input field
      return;
    }
    

    const maxSize = environment.maxFileSizeMB * 1024 * 1024; // e.g. 2 MB in bytes
    if (file.size <= maxSize) {
      this.selectedDocFile = {
        ...this.selectedDocFile, // keep existing fields
        file: file,
        fileName: file.name,
        fileSize: file.size
      };
      this.docFileName = file.name;
      //console.log('Selected file:', this.selectedDocFile);
    } else {
      this.toastr.error(
        `File size exceeds the maximum limit of ${environment.maxFileSizeMB} MB.`
      );
      this.selectedDocFile.file = null;
      this.docFileName = '';
      event.target.value = ''; // reset the input field
    }
  } else {
    this.selectedDocFile.file = null;
    this.docFileName = '';
  }
}


convertFileToBase64(file: File): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result as string);
    reader.onerror = error => reject(error);
  });
}

  isLoadingData:boolean=false;

  async getDomainDetails(domainId:number) {
    //this.isLoadingData=true;
     //console.log("Datal",domainId)
     await lastValueFrom(this.domainService.getDomainByDomainId(domainId)).then(
        (res) => {
         if (res.status === HttpStatusCode.Ok) {
           this.domainDetail= res.body;
       
         } else {
           //console.log("Unexpected status code:", res.status);
          this.isLoadingData=false
         }
       },
       (error) => {
         this.isLoadingData=false
         //console.error("Error fetching domain data:", error);
       }
     );
   }



   
   onboardingDomain: any;

   async loadOnboardingDomain() {
  const domains = await lastValueFrom(
    this.domainService. getAllDomainsByOrgId(this.domainDetail.organisationId)
  );

  this.onboardingDomain = domains.body.find(d => d.isOnboardingDomain === true);
}


validateTenure(): boolean {

  // If onboarding domain → allow anything (1–10)
  if (this.domainDetail.isOnboardingDomain) {
    return true;
  }

  // If no onboarding found → allow (safe fallback)
  if (!this.onboardingDomain) {
    return true;
  }

 this.tenures = [1,2,3,4,5,6,7,8,9,10];


  return true;
}


setAllowedTenures() {


  if (!this.domainDetail) return;
  // ✅ Onboarding domain → full range
  if (this.domainDetail.isOnboardingDomain) {
    this.tenures = [1,2,3,4,5,6,7,8,9,10];
    return;
  }

  // ✅ Other domains → restrict based on onboarding
  if (this.onboardingDomain) {
    const max = this.onboardingDomain.numberOfYears;

    this.tenures = Array.from({ length: max }, (_, i) => i + 1);
  } else {
    // fallback
    this.tenures = [1,2,3,4,5,6,7,8,9,10];
  }

  if (this.selectedTenure > this.tenures[this.tenures.length - 1]) {
  this.selectedTenure = this.tenures[this.tenures.length - 1];
}
}

}
