import { Component, OnInit } from '@angular/core';
import { DomainService } from '../rgnt-domain/service/domain.service';
import { ActivatedRoute, Router } from '@angular/router';
import { HttpClient, HttpStatusCode } from '@angular/common/http';
import { DomainApplicationDetailsService } from './service/domain-application-details.service';
import { ToastrService } from 'ngx-toastr';
import { forkJoin, last, lastValueFrom } from 'rxjs';
import { Domain } from '../model/domain.model';
import { error } from 'jquery';
import { DocumentUploadService } from '../document-upload/service/document-upload.service';
import { DomSanitizer } from '@angular/platform-browser';
import { ContactDetailsFormService } from '../contact-details-form/service/contact-details-form.service';
import { ContactDocumentUploadService } from '../contact-document-upload/service/contact-document-upload.service';
import { Organization } from '../model/organization.model';
import { OrganisationDetailsService } from '../organisation-details/service/organisation-details.service';
import { Modal } from 'bootstrap';
import { AssetService } from '../asset.service';
import { UserService } from '../user/service/user.service';
import { environment } from '../environments/environment';
import { UserDomainService } from '../user-domain-details/service/user-domain.service';
import { Location } from '@angular/common';

@Component({
    selector: 'app-domain-application-details',
    templateUrl: './domain-application-details.component.html',
    styleUrls: ['./domain-application-details.component.css'],
    standalone: false
})
export class DomainApplicationDetailsComponent implements OnInit{

  formData = {
      name: '',
      fatherName: '',
      age: '',
      organisationName: '',
      designation: '',
      authOrganisationName: '',
      agree: false,
    };
    ageError: boolean = false;
    
    private apiEnvUrl = environment.apiURL
  
    tokenPassword = '';
    validationError : string = '';
    passwordErrorMessage = '';
    isPasswordModalOpen = false;
    isLoading : boolean = false;
    tokens: any[] = [];
    certificates: any[] = [];
    
    dataTypes: string[] = [
      'TextPKCS7',
      'TextPKCS1',
      'XML',
      'Sha256HashPKCS7',
      'Sha256HashPKCS1',
      'TextPKCS7ATTACHED'
    ];
    selectedToken: any = "";
    selectedCertificate: any = "";
    selectedDataType: string = '';
  
    embridgeUrl = 'https://localhost.emudhra.com:26769';
    dscApi =  environment.apiURL;
  

  role: string = localStorage.getItem('userRole')
  
  constructor(private route: ActivatedRoute,
    private domainService: DomainService,
    private userDomainService: UserDomainService,
     private oreganizationService:DomainApplicationDetailsService,
     private toastrService: ToastrService,
     private documentService:DocumentUploadService,
     private sanitizer:DomSanitizer,
    private router: Router,
    private location: Location,
    private orgService:OrganisationDetailsService,
        private contactDetailsService: ContactDetailsFormService,  private http: HttpClient,private contactDocumentsService:ContactDocumentUploadService,
      public assetService:AssetService,private userService:UserService,
    ) {
    
  }
  domainId: number; 
  isLoadingData:boolean=false;
  async ngOnInit(): Promise<void> {
    this.route.queryParams.subscribe(param => {
      var domainId = param['domainId'];
      this.domainId = param['domainId'];
    })
    //console.log(this.domainId)
    await this.getDomainApplicationDetails(this.domainId);
    this.setNsStatusOptions();
    
  }
  
  domainsList: any;
  async getDomainApplicationDetails(domainId:number) {
   
    //console.log("Datal",domainId)
    this.isLoadingData=true;
    this.domainService.getDomainByDomainId(domainId).subscribe({
      next: (res) => {
        //console.log(res)
        if (res.status === HttpStatusCode.Ok) {
          this.domainsList = res.body;
         //console.log("domain data received:",res);
        this.getOrganizationDetails(this.domainsList.organisationId);
        } else {
          this.isLoadingData=false;
          //console.log("Unexpected status code:", res.status);
         
        }
      },
      error: (error) => {
        this.isLoadingData=true;
       if(error.status==HttpStatusCode.Unauthorized){
        this.navigateToSessionTimeOut();
       }
      }
    });
  }
  navigateToSessionTimeOut(){
    this.router.navigateByUrl("/session-timeout");
  }

  organizationsList:any;
  async getOrganizationDetails(organisationId:number) {
   
    //console.log("Datal",organisationId)
    await this.getUsersList(organisationId);
    this.oreganizationService.getOrganizationByDomainId(organisationId).subscribe({
      next: (res) => {
        //console.log(res)
        if (res.status === HttpStatusCode.Ok) {
          //console.log(res.body)
          this.organizationsList = res.body;
          //console.log(this.organizationsList,organisationId)
          this.onPincodeChange()
          this.getOrgDocuments(organisationId);

          } else {
          this.isLoadingData=false;
        }
      },
      error: (error) => {
      }
    });
  }

  domain : Domain = new Domain()

  async updateDomain() {
    const statuses = [
  this.billingOfficerStatus,
  this.adminStatus,
  this.technicalOfficerStatus,
  this.orgBoardStatus,
 // this.orgGstStatus,
  this.orgLicenceStatus
  //this.orgPanStatus
];
const isAnyStatusInvalid = statuses.some(
  status => status !== this.approved && status !== this.Rejected
);

if (isAnyStatusInvalid) {
  this.toastrService.warning("Please verify all the docs");
  return;
}
     
      if(this.domainsList.paymentStatus=="Payment Not Done"){
      if(this.billingOfficerStatus==this.approved&&this.adminStatus==this.approved&&this.technicalOfficerStatus==this.approved&&
        this.orgBoardStatus==this.approved &&this.orgLicenceStatus==this.approved){
        }
      }
      if(this.domainsList.paymentStatus==="Payment Approved" 
        && this.domainsList.status === 'Inactive'){
          await this.createInvoiceforDomain(this.domainId);
         document.getElementById("btnpaymentApproval").click();
         return
      }
        if (this.organizationsList?.pincode == null || (String(this.organizationsList.pincode)?.trim() === '')) {
      // this.toastrService.error("Pincode cannot be empty");
      return;
    }else if(this.organizationsList?.pincode.length<=5){
      // this.toastrService.error("Please enter valid pincode");
      return;
    }
    if(this.organizationsList?.address == null || (this.organizationsList?.address?.trim()==='')||this.organizationsList.address.length<=5){
      return;
    }
    if(this.pincodeError!=''){
      return
    }
    this.domainsList.modifiedByEmailId= localStorage.getItem('email');
    this.domainsList.modifiedDateTime= new Date();
    const response = await lastValueFrom(this.oreganizationService.updateDomain(this.domainId, this.domainsList));
            try{
              if (response.status === HttpStatusCode.Ok) {
                this.toastrService.success("Domain data updated successfully.");
                await  this.createInvoiceforDomain(this.domainId);
            } else if (response.status === HttpStatusCode.NotFound) {
                this.toastrService.error("Domain not found.");
            } else {
                this.toastrService.error("Unexpected error during update.");
            }
            }catch(error){

            if (error.status === HttpStatusCode.InternalServerError) {
                 this.toastrService.error('Could not process your request at the moment, please try again later or contact registrar');
            } else {
                 this.toastrService.error('Could not process your request at the moment, please try again later or contact registrar');
            }
        }
       
          
}

async onPaymentStatusChange() {

  this.setNsStatusOptions();
 
}

nsStatusOptions: string[] = [];
status:string[]=[];

isNsStatusDisabled: boolean = true;  

setNsStatusOptions() {

  if (this.domainsList.paymentStatus) {
    this.isNsStatusDisabled = false; 
  } else {
    this.isNsStatusDisabled = true;   
  }
}

cancelDomain(){
   this.location.back();
}

async submitDomainToNIXIOnPaymentApproval(){
  if(this.domainsList.bankName.length < 3){
    document.getElementById('closetheNixiApproval')?.click();
    document.getElementById('btnDomainApproval')?.click();
    return;
  }
  this.domainsList.isUpdatedInNIXI = true;
  this.domainsList.nsRecordStatus="Approved"
  this.domainsList.status="Active"
  this.domainsList.applicationStatus ='Approved';
  this.domainsList.domainApprovalToNIXIGivenBy = localStorage.getItem('email');
  const response = await lastValueFrom(this.oreganizationService.updateDomain(this.domainId, this.domainsList));
                try{
              if (response.status === HttpStatusCode.Ok) {
                //console.log('Domain update successful.');

                  //this.domain = response.body;
                await this.getDomainApplicationDetails(this.domainId);
                //console.log(this.domainsList);
                if (this.domainsList.eppResponseComment &&
                  this.domainsList.eppResponseComment.includes("DNSSEC Failed")) {
                  this.toastrService.warning(
                    "The Registrant's domain was not created in Registry(NIXI) due to invalid DNSSEC details, Application Status marked to Incomplete"
                  );
                }
                else{
                  this.toastrService.success("Domain data updated successfully.");
                }
                await  this.createInvoiceforDomain(this.domainId);
                window.location.reload();
            } else if (response.status === HttpStatusCode.NotFound) {
                this.toastrService.error("Domain not found.");
            } else {
                this.toastrService.error("Unexpected error during update.");
            }
            }catch(error){

            if (error.status === HttpStatusCode.InternalServerError) {
                 this.toastrService.error('Could not process your request at the moment, please try again later or contact registrar');
            } else {
                 this.toastrService.error('Could not process your request at the moment, please try again later or contact registrar');
            }
        }
}

async submitDomainToNIXIOnDoubleVerificationApproval(){

  if(this.domainsList.twoLetterDomainDocumentApprovalStatus !== this.approved){
    this.toastrService.error('The 2 letter Domain Board Approval Document is yet to be review by you. pls review and approve');
    return;
  }
  this.domainsList.isUpdatedInNIXI = true;
  this.domainsList.nsRecordStatus="Approved"
  this.domainsList.status="Active"
  this.domainsList.applicationStatus ='Approved';
  const response = await lastValueFrom(this.oreganizationService.updateDomain(this.domainId, this.domainsList));
            try{
              if (response.status === HttpStatusCode.Ok) {
                  //this.domain = response.body;
                await this.getDomainApplicationDetails(this.domainId);
                //console.log(this.domainsList);
                if (this.domainsList.eppResponseComment &&
                  this.domainsList.eppResponseComment.includes("DNSSEC Failed")) {
                  this.toastrService.warning(
                    "The Registrant's domain was not created in Registry(NIXI) due to invalid DNSSEC details, Application Status marked to Incomplete"
                  );
                }else if (this.domainsList.eppResponseComment &&
                  this.domainsList.eppResponseComment.includes("Registry Reserved Domain")) {
                  this.toastrService.warning(
  'Data management policy violation of NIXI registry - Domain ' +
    this.domainsList.bankName +
    this.domainsList.domainName +
    ' matches a regular expression restricted by NIXI policy. This domain name is registry reserved. Please contact NIXI.',
  'Warning',
  {
    timeOut: 0,          // no auto-dismiss
    extendedTimeOut: 0,  // prevent hover fade-out
    tapToDismiss: true,  // dismiss only when clicked
    closeButton: true    // adds a close (×) button
  }
);

                }
                else{
                  this.toastrService.success("Domain data updated successfully.");
                }
                await  this.createInvoiceforDomain(this.domainId);
                //window.location.reload();
            } else if (response.status === HttpStatusCode.NotFound) {
                this.toastrService.error("Domain not found.");
            } else {
                this.toastrService.error("Unexpected error during update.");
            }
            }catch(error){

            if (error.status === HttpStatusCode.InternalServerError) {
                 this.toastrService.error('Could not process your request at the moment, please try again later or contact registrar');
            } else {
                 this.toastrService.error('Could not process your request at the moment, please try again later or contact registrar');
            }
        }
}

paymentModel:any;
approvePaymentStatus(){
   const modalElement1 = document.getElementById('viewThePaymentReciept');
   if (modalElement1) {
    const modal = new Modal(modalElement1);
    modal.hide();
  }
  document.getElementById("closeButtonForPayment").click();

  //appovePaymentStatus
  this.domainsList.paymentStatus="Payment Approved";
  this.domainsList.paymentApprovedOrRejectedBy = localStorage.getItem('email');
  this.oreganizationService.updateDomain(this.domainId, this.domainsList).subscribe({
    next: (response) => {
        if (response.status === HttpStatusCode.Ok) {
          // this.toastrService.success("Payment Status updated to paid");
          document.getElementById("closeButtonForPayment").click();
          
        } else if (response.status === HttpStatusCode.NotFound) {
          this.toastrService.error("Domain not found.");
      } else {
          this.toastrService.error("Unexpected error during update.");
      }
      },error:(error)=>{
        //console.log(error)
      }
    })

   const modalElement = document.getElementById('paymentApprovalPopup');
  if (modalElement) {
    const modal = new Modal(modalElement);
    modal.show();
  }
  
}



rejectPaymentStatus(){
if(this.domainsList.paymentStatus=="Payment Approved") {
  this.toastrService.warning("Already Approved Payment");
}else{
  if(this.domainsList.paymentStatus="Payment Completed"){
    this.domainsList.paymentStatus="Payment Rejected";
    this.domainsList.paymentApprovedOrRejectedBy = localStorage.getItem('email');
    //this.domainsList.applicationStatus = this.assetService.paymentYetToBeDone;
    this.domainsList.isUpdatedInNIXI = false;
    this.oreganizationService.updateDomain(this.domainId, this.domainsList).subscribe({
      next: (response) => {
  
          if (response.status === HttpStatusCode.Ok) {
            this.toastrService.success("Payment Rejected");
            document.getElementById("closeButtonForPayment").click();
          } else if (response.status === HttpStatusCode.NotFound) {
            this.toastrService.error("Domain not found.");
        } else {
            this.toastrService.error("Unexpected error during update.");
        }
        },error:(error)=>{
  
        }
      })
   

  }
  this.closePasswordModal();
}

}
gstDoc:any
panDoc:any
licenseDoc:any
boardResolutionDoc:any;
boardApprovalDoc:any;
BoardApprovalDocImage: any;
entireOrgDocsObj:any;
panDocPdf:any;
gstDocPdf:any;
paymentRecieptPdf:any;
licenceDocPdf:any
boardResolutionDocPdf:any
orgGstStatus;
twoLetterDomainDocumentStatus;
orgPanStatus;
orgLicenceStatus;
orgBoardStatus;
orgGSTDocComment;
orgPanDocComment;
orgLicenceDocComment;
orgBoardDocComment;
 async getOrgDocuments(orgId){
  this.documentService.getOrgDoucumentsById(orgId).subscribe({
    next: (response) => {
      //console.log("hello")
      this.entireOrgDocsObj=response.body;
     
      this.entireOrgDocsObj.forEach(doc => {
        //console.log(doc.comment);
          if (doc.organisationGstinNumber && doc.organisationGstinNumber.trim() !== '') { 
            this.orgGstStatus = doc.documentStatus; 
            this.organisationGstinNumber=doc.organisationGstinNumber;
            this.orgGSTDocComment = doc.comment;
          }
          if (doc.panNumber && doc.panNumber.trim() !== '') { 
            this.orgPanStatus = doc.documentStatus; 
            this.orgPanNumber=doc.panNumber;
            this.orgPanDocComment = doc.comment;
          }
          if (doc.licenseNumber && doc.licenseNumber.trim() !== '') { 
            this.orgLicenceStatus = doc.documentStatus; 
             this.orgLicenseNumber=doc.licenseNumber;
             this.orgLicenceDocComment = doc.comment;
          }
          if(doc.boardResolutionDocument){
            this.orgBoardStatus=doc.documentStatus;
            this.orgBoardDocComment = doc.comment;
          }
          // ... similar checks for other document types
        });
      this.getContactOfficerDocuments(orgId);
    
    },error:(error)=>{
      this.isLoadingData=false;
    }
})
}
modalTitle:string='';
BoardDocImage:boolean;
OrgGstDocImage:boolean;
OrgLicenceImage:boolean;
OrgPanImage:boolean;
 organisationGstinNumber;
  orgLicenseNumber;
  orgPanNumber;
viewDocuments(docType){
  this.modalTitle=docType
  if(docType=='GSTIN'){
    this.gstDoc = this.extractDocument(this.entireOrgDocsObj, 'organisationGstinDocument');
    if (this.gstDoc?.size > 0 && this.gstDoc.get('fileName').endsWith('.pdf')) {
      this.displayPdf(this.gstDoc.get('document'), "organisationGstinDocument"); 
      this.OrgGstDocImage=false
      document.getElementById("gstModal")?.click();
    } else if (this.gstDoc.size > 0) { 
      this.OrgGstDocImage=true
      this.gstDoc = this.extractDocumentImage(this.entireOrgDocsObj, 'organisationGstinDocument'); 
      document.getElementById("gstModal")?.click();
    }
   
  }else if(docType=='PAN'){
    this.panDoc = this.extractDocument(this.entireOrgDocsObj, 'panDocument');
     
    if (this.panDoc?.size > 0 && this.panDoc?.get('fileName').endsWith('.pdf')) {
      this.displayPdf(this.panDoc.get('document'), "panDocument"); // Corrected documentField
      this.OrgPanImage=false;
      document.getElementById("panModal")?.click();
    } else if (this.panDoc.size > 0) { 
      this.panDoc = this.extractDocumentImage(this.entireOrgDocsObj, 'panDocument');
      this.OrgPanImage=true;
      document.getElementById("panModal")?.click(); 
    }
  }else if(docType=='LICENCE'){
    this.licenseDoc = this.extractDocument(this.entireOrgDocsObj, 'licenseDocument');
    if (this.licenseDoc?.size > 0 && this.licenseDoc.get('fileName').endsWith('.pdf')) {
      this.displayPdf(this.licenseDoc.get("document"), "licenseDocument"); // Corrected documentField
      this.OrgLicenceImage=false;
      document.getElementById("licenceModal")?.click(); 
    } else if (this.licenseDoc.size > 0) { 
      this.licenseDoc = this.extractDocumentImage(this.entireOrgDocsObj, 'licenseDocument'); 
      this.OrgLicenceImage=true;
      document.getElementById("licenceModal")?.click(); 
    }
  } else if (docType == 'Domain Board Approval') {
      //console.log("entered the board approval doc")
      this.boardApprovalDoc = this.extractBoardDocument(this.domainsList?.twoLetterDomainDocumentProof,
        this.domainsList?.twoLetterDomainDocumentFileName);
        if(this.boardApprovalDoc?.size > 0 && this.boardApprovalDoc?.get('fileName').endsWith('.pdf')) {
          this.displayPdf(this.boardApprovalDoc.get("document"), "boardApprovalDocument"); // Corrected documentField
          this.BoardApprovalDocImage=false;
          document.getElementById("boardApprovalModal")?.click(); 
        } else if (this.boardApprovalDoc.size > 0) { 
          this.BoardApprovalDocImage=true;
          this.boardApprovalDoc = this.boardApprovalDoc.get('document'); 
          document.getElementById("boardApprovalModal")?.click(); 
        }
    }
  else{
    this.boardResolutionDoc = this.extractDocument(this.entireOrgDocsObj, 'boardResolutionDocument');
    if (this.boardResolutionDoc?.size > 0 && this.boardResolutionDoc.get('fileName').endsWith('.pdf')) {
      this.displayPdf(this.boardResolutionDoc.get("document"), "boardResolutionDocument"); // Corrected documentField
      this.BoardDocImage=false;
      document.getElementById("boardModal")?.click(); 
    } else if (this.boardResolutionDoc.size > 0) { 
      //console.log("entered the else")
      this.BoardDocImage=true;
      this.boardResolutionDoc = this.extractDocumentImage(this.entireOrgDocsObj, 'boardResolutionDocument'); 
      document.getElementById("boardModal")?.click(); 
    }
  }
}
private extractDocument(orgDocs: any, documentField: string): Map<string, any> {
  //console.log(documentField)
  const foundDoc = orgDocs.find(doc => !!doc[documentField]);

  if (foundDoc) {
    return new Map([
      ['fileName', foundDoc.fileName], 
      ['document', foundDoc[documentField]]
    ]);
  } else {
    return new Map(); 
  }
}
private extractDocumentImage(orgDocs: any, documentField: string): any {
  const foundDoc = orgDocs.find(doc => !!doc[documentField]);

  if (foundDoc) {
    return foundDoc[documentField]; 
  } else {
    return null; 
  }
}

boardApprovalDocPdf: any
displayPdf(binaryData,docName) {
  if (typeof binaryData === 'string') { 
    // If data is a Base64 string
    const binaryString = atob(binaryData); 
    const len = binaryString.length;
    const bytes = new Uint8Array(len);
    for (let i = 0; i < len; i++) {
      bytes[i] = binaryString.charCodeAt(i);
    }
    const blob = new Blob([bytes], { type: 'application/pdf' });
    
    // const arrayBuffer = new Uint8Array(binaryData);
  
    if(docName=="organisationGstinDocument"){
     // const blob = new Blob([arrayBuffer], { type: 'application/pdf' });
     const pdfUrl = URL.createObjectURL(blob);
      this.gstDocPdf = this.sanitizer.bypassSecurityTrustResourceUrl(pdfUrl); 
    }
    if(docName=="panDocument"){
      const pdfUrl = URL.createObjectURL(blob);
      this.panDocPdf = this.sanitizer.bypassSecurityTrustResourceUrl(pdfUrl); 
    }
    if(docName=="licenseDocument"){
      const pdfUrl = URL.createObjectURL(blob);
      this.licenceDocPdf = this.sanitizer.bypassSecurityTrustResourceUrl(pdfUrl); 
    }
    if(docName=="boardResolutionDocument"){
      const pdfUrl = URL.createObjectURL(blob);
      this.boardResolutionDocPdf = this.sanitizer.bypassSecurityTrustResourceUrl(pdfUrl); 
    }
    if(docName=="boardApprovalDocument"){
        const pdfUrl = URL.createObjectURL(blob);
        this.boardApprovalDocPdf = this.sanitizer.bypassSecurityTrustResourceUrl(pdfUrl); 
      }
} 
}
private approved="Approved";
approveOrgDocs(OrgDoc){
  //console.log(this.documentComment)
  //console.log(OrgDoc)
  // if(OrgDoc=='PAN'){
  //   this.orgPanStatus=this.approved
  //   this.changeDocStatus(OrgDoc,this.orgPanStatus,this.domainsList.organisationId,this.documentComment);
  // }else
     if(OrgDoc=='LICENCE'){
this.orgLicenceStatus=this.approved
this.changeDocStatus(OrgDoc,this.orgLicenceStatus,this.domainsList.organisationId,this.documentComment);
  }else if(OrgDoc=='BOARD'){
this.orgBoardStatus=this.approved
this.changeDocStatus(OrgDoc,this.orgBoardStatus,this.domainsList.organisationId,this.documentComment);
  }
  else if(OrgDoc == "DomainBoardDoc"){
     this.updateDomainBoardApprovalDocStatus(this.approved, this.documentComment);
  }
  if(this.billingOfficerStatus==this.approved&&this.adminStatus==this.approved&&this.technicalOfficerStatus==this.approved&&
    this.orgBoardStatus==this.approved&&this.orgLicenceStatus==this.approved){
     this.paymentButtonDisabled=false;

    }
}

async updateDomainBoardApprovalDocStatus(status, documentComment){
  this.domainsList.twoLetterDomainDocumentApprovalStatus = status;
  this.twoLetterDomainDocumentStatus = status;
  this.domainsList.twoLetterDomainDocumentStatusComment = documentComment;
    await lastValueFrom(this.userDomainService.updateTwoLetterDomainDocumentInfo(this.domainsList.domainId,documentComment, status)).then((response) => {
      //if (response.status === HttpStatusCode.Ok) {
      if(response.status === HttpStatusCode.Ok){
        if(status === this.approved){ 
          this.toastrService.success('Document Approved');
        }else{
          this.toastrService.success('Dcoument Rejected')
        }
      } 
    });
}

domainsListOfOrg: any;
async getAllDomainsByOrganisationId(organisationId: number) {
  await lastValueFrom(this.domainService.getAllDomainsByOrgId(organisationId)).then((response) => {
    if (response.status === HttpStatusCode.Ok) {
      this.domainsListOfOrg = response.body;
    }
  })
}

async updateAllUnApproveDomainsStatusesToIncompleteOfAnOrganisation(organisationId: number) {
  await this.getAllDomainsByOrganisationId(organisationId);
  this.domainsListOfOrg.forEach((domain) => {
    if(domain.applicationStatus !== this.assetService.Approved 
      || domain.applicationStatus !== this.assetService.Incomplete) {
        domain.applicationStatus = this.assetService.Incomplete;
      this.updateDomainApplicationStatus(domain);
    }
  });
}

async updateDomainApplicationStatus(domain){
  await lastValueFrom(this.domainService.updateDomainDetails(domain)).then((response) => {
  })
}

  async rejectOrgDocs(OrgDoc) {
     if (OrgDoc == 'LICENCE') {
      this.orgLicenceStatus = "Rejected"
      this.paymentButtonDisabled = true;
      this.changeDocStatus(OrgDoc, this.orgLicenceStatus, this.domainsList.organisationId, this.documentComment);
      this.updateAllUnApproveDomainsStatusesToIncompleteOfAnOrganisation(this.domainsList.organisationId);
      this.toastrService.success("The Entity's domain status has been changed to Incomplete for non-approved applications");
    } else if (OrgDoc == 'BOARD') {
      this.orgBoardStatus = "Rejected"
      this.paymentButtonDisabled = true;
      this.changeDocStatus(OrgDoc, this.orgBoardStatus, this.domainsList.organisationId, this.documentComment);
      this.updateAllUnApproveDomainsStatusesToIncompleteOfAnOrganisation(this.domainsList.organisationId);
      this.toastrService.success("The Entity's domain status has been changed to Incomplete for non-approved applications");
    } 
    else if(OrgDoc == "DomainBoardDoc"){
       this.paymentButtonDisabled = true;
      await this.updateDomainBoardApprovalDocStatus(this.Rejected, this.documentComment);
      await this.updateAllUnApproveDomainsStatusesToIncompleteOfAnOrganisation(this.domainsList.organisationId);
       this.toastrService.success("The Entity's domain status has been changed to Incomplete for non-approved applications");
    }

  }

updateApplicationStatus(applicationStatus:string){
  //console.log(applicationStatus)
  this.domainsList.applicationStatus=applicationStatus;
  this.domainService.updateDomainDetails(this.domainsList).subscribe({
    next:(response)=>{
      //console.log(response)
      if(response.status==HttpStatusCode.Ok){
        this.toastrService.success("Application Status updated to "+applicationStatus);
      }
    },error:(error)=>{
    }
  })

}



changeDocStatus(DocType,Status,OrgId, comment){
  //console.log(comment)
  this.documentService.approveOrRejectOrgDocsWithComment(DocType,Status,OrgId, comment).subscribe({
    next:(response)=>{
      this.toastrService.success("Document "+Status)
      if(DocType==='PAN'){
        document.getElementById("panDocViewModalClose").click();
      }else if(DocType==='LICENCE'){
        document.getElementById("licenseDocViewModalClose").click();
      }else if(DocType==='BOARD'){
        document.getElementById("boardDocViewModalClose").click();
      }else if(DocType ==='GST'){
        document.getElementById("gstDocViewModalClose").click();
      }
      this.getOrgDocuments(OrgId);
      this.documentComment = '';
    },error:(eror)=>{

    }
  }
  )
}
async navigateToRegistrantOfficersApprove(value : string){
  //console.log(this.domainsList.bankName)
  let email=''
  if(value=='Administrative'){
    email=this.contactRoleEmailMap.get("Administrative Officer");
    sessionStorage.setItem('docEmail',email);
  }else if(value == 'Technical'){
    email=this.contactRoleEmailMap.get("Technical Officer");
    sessionStorage.setItem('docEmail',email);
    //console.log(this.contactRoleEmailMap.get("Technical Officer"))
  }else if(value == 'Billing'){
    email=this.contactRoleEmailMap.get("Billing Officer");
    sessionStorage.setItem('docEmail',email);
  }
  sessionStorage.setItem('contactType',value);
  sessionStorage.setItem('orgIdForDoc',this.domainsList.organisationId);
  // this.router.navigate(['/verify-documents'], { queryParams: { organisationId: this.domainsList.organisationId, contactUserType: value, email:email} });
  //this.router.navigate(['/rgtr-rgnt-ofd'], { queryParams: { data: this.domainsList.organisationId } })

  this.router.navigateByUrl('/verify-documents')
}

adminStatus:string;
technicalOfficerStatus:string;
billingOfficerStatus:string;
contactOfficerDetails:any


private Rejected='Rejected'
contactDetails
  getContactOfficerDocuments(organisationId: number): void {
    this.contactDetailsService.getContactOfficersDetails(organisationId)
    .subscribe({
      next: (response) => {
        if (response.status === HttpStatusCode.Ok) {
        this.createContactRoleEmailMap(response.body);
          this.contactDocumentsService.getDocStatusOfOfficers(organisationId,this.contactRoleEmailMap)
          .subscribe({
            next:(response)=>{
              const allStatus= response[0].split(",")
         this.adminStatus=allStatus[0];
         this.technicalOfficerStatus=allStatus[1];
         this.billingOfficerStatus=allStatus[2];
              if(this.adminStatus===this.Rejected||this.technicalOfficerStatus===this.Rejected||this.billingOfficerStatus===this.Rejected){
                this.paymentButtonDisabled=true;
              }  
               this.changeStatusOfpayment();
            }
          })
         this.isLoadingData=false;
        
        }
      },
      error: (error) => {
        this.isLoadingData=false
        if (error.status === HttpStatusCode.Unauthorized) {
          // Your logic for Unauthorized error here
        }
      }
    });
}
contactRoleEmailMap = new Map<string, string>();
createContactRoleEmailMap(contactDetailsList) {
  this.contactRoleEmailMap.clear(); // Clear the map before populating it
  // in this  contactDetailsList take only the first administrative officer, technical officer and billing officer
  // Only keep the first occurrence of each officer role: Administrative Officer, Technical Officer, Billing Officer
  const rolesToKeep = ["Administrative Officer", "Technical Officer", "Billing Officer"];
  const seenRoles = new Set<string>();
  contactDetailsList = contactDetailsList.filter((contactDetail) => {
    if (
      contactDetail &&
      rolesToKeep.includes(contactDetail.contactRole) &&
      !seenRoles.has(contactDetail.contactRole)
    ) {
      seenRoles.add(contactDetail.contactRole);
      return true;
    }
    return false;
  });
  if (contactDetailsList && Array.isArray(contactDetailsList)) {
    contactDetailsList.forEach((contactDetail) => {
      if (contactDetail && (contactDetail.isActive === true || contactDetail.isActive === null)) {
        if (contactDetail.contactRole && contactDetail.emailId) {
          this.contactRoleEmailMap.set(contactDetail.contactRole, contactDetail.emailId);
        }
      }
    });
  }
 
}
paymentButtonDisabled=true;
changeStatusOfpayment(){
  //console.log(this.domainsList.paymentStatus)
  // if(this.domainsList.paymentStatus=="Unpaid"){
    //console.log(this.billingOfficerStatus==this.approved,this.adminStatus==this.approved,this.technicalOfficerStatus==this.approved,
      //this.orgBoardStatus==this.approved,this.orgGstStatus==this.approved,this.orgLicenceStatus==this.approved,this.orgPanStatus==this.approved)
    if(this.billingOfficerStatus==this.approved&&this.adminStatus==this.approved&&this.technicalOfficerStatus==this.approved&&
      this.orgBoardStatus==this.approved&&this.orgLicenceStatus==this.approved){
       //this.paymentButtonDisabled=false;
      // this.domainsList.paymentStatus="Ready for payment";
      //  this.toastrService.success(
      //   "This domain's payment status is changed to Ready for payment", 
      //   "Success", 
      //   { timeOut: 5000 } 
      // );

      // }
  }
  
  
}
openReciptasPdf:boolean
async viewThePaymentReceipt(paymentReciept,fileName){
  //console.log(fileName)
if(fileName?.endsWith('.pdf')){
  
  await this.displayPaymentPdf(paymentReciept);
  this.openReciptasPdf=true
}else{
  this.openReciptasPdf=false
}
  
  
  document.getElementById("viewThePaymentRecipt").click();
}
async displayPaymentPdf(binaryData) {
  if (typeof binaryData === 'string') { 
    // If data is a Base64 string
    const binaryString = atob(binaryData); 
    const len = binaryString.length;
    const bytes = new Uint8Array(len);
    for (let i = 0; i < len; i++) {
      bytes[i] = binaryString.charCodeAt(i);
    }
    const blob = new Blob([bytes], { type: 'application/pdf' });
    const pdfUrl = URL.createObjectURL(blob);
    this.paymentRecieptPdf = this.sanitizer.bypassSecurityTrustResourceUrl(pdfUrl); 
} 
}

updateDomainStatus(nsRecordStatus){
  //console.log(nsRecordStatus)
if(nsRecordStatus=='OnHold'||nsRecordStatus=='Rejected'||nsRecordStatus=='Inprogress'){
  this.domainsList.status='Inactive'
  if(nsRecordStatus=='Rejected'){
     this.domainsList.applicationStatus='Rejected'
  }else{
  this.domainsList.applicationStatus='Under Review'
  }
}else
if(nsRecordStatus=='Approved'){
  this.domainsList.status='Active'
  this.domainsList.applicationStatus='Approved'
}
}

async createInvoiceforDomain(domainId : number){
  this.domainService.createInvoice(domainId).subscribe({
    next :(response)=>{
      if(response.status == HttpStatusCode.Ok){

      }
  },
  error: (error) => {
  }
 });
   

}
onEmailInput(event: any) {
  const email = event.target.value;
  
  // Validate the email using the regex pattern for general structure
  this.validateEmail(event);

  // Ensure TLD is between 2 and 4 characters
  const tld = this.getTLD(email);
  if (tld && tld.length > 4) {
    // Prevent further typing if TLD length exceeds 4
    event.preventDefault();
  }
}

// Extract TLD from email address
getTLD(email: string): string | null {
  const parts = email.split('.');
  return parts.length > 1 ? parts.pop() : null;
}
orgEmailError = '';

// Validate email and set error message accordingly
validateEmail(event: any) {
  const email = event.target.value.trim();
  const emailRegex = /^[a-zA-Z][a-zA-Z0-9_.]*@[a-zA-Z0-9.]+\.[a-zA-Z]{2,4}$/;

  // Check if email matches the regex
  if (email && !emailRegex.test(email)) {
    this.orgEmailError = 'Please enter a valid email';
  } else {
    this.orgEmailError = ''; // Clear any previous error
  }
}
cityOptions: Array<{ name: string; district: string; state: string }> = [];
loading = false;
pincodeError: string = ''; 
 fetchCityState(pincode: string): void {
  this.loading = true;
  this.pincodeError = ''; // Clear the error at the beginning of each validation

  // Check if the input pincode is empty
  if (pincode === '') {
    this.clearCityAndState();
    this.pincodeError = 'Pincode is required.'; // Show 'pincode required' message
    this.loading = false;
    return;
  }

  // Check if the pincode is not exactly 6 digits
  if (!/^\d{6}$/.test(pincode)) {
    this.pincodeError = 'Pincode must be exactly 6 digits.'; // Show pattern error
    this.clearCityAndState();
    this.loading = false;
    return;
  }

  // Proceed with API call if pincode is valid
  if (pincode !== '160034') {
    this.orgService.getPinCodeData(pincode).subscribe(
      (response: any) => {
        this.loading = false;

        if (response.body.length>0) {
          const places = response.body;

          this.cityOptions = places.map((place: any) => ({
            name: place.city + ', ' + place.district,
            district: place.district,
            state: place.state,
        }));

          if (this.cityOptions.length > 0) {
            this.organizationsList.city = this.cityOptions[0].name || '';
            this.organizationsList.state = this.cityOptions[0].state || '';
            this.organizationsList.district = this.cityOptions[0].district || '';
            this.enableCityDropdown();
          } else {
            this.clearCityAndState();
          
          }
        } else {
          this.clearCityAndState();
          this.pincodeError = 'Invalid pincode.';
        }
      },
      (error) => {
        this.loading = false;
        this.clearCityAndState();
        this.pincodeError = 'Error fetching data. Please try again later.';
      }
    );
  } else if (pincode === "160034") {
    // Hardcoded case for pincode 160034 (Chandigarh)
    this.cityOptions = [{ name: 'Chandigarh', district: 'Chandigarh', state: 'Chandigarh' }];
    this.organizationsList.city = this.cityOptions[0].name || '';
    this.organizationsList.state = this.cityOptions[0].state || '';
    this.organizationsList.district = this.cityOptions[0].district || '';
    this.pincodeError = ''; // No error message for this hardcoded case
  }
}

StdCodes;
stdCodesbasedOnState:any;
loadStdCodes(state: string): void {
  //console.log(this.StdCodes);
  this.stdCodesbasedOnState = this.StdCodes?.filter(item => item.state === state);
}

enableCityDropdown(): void {
  // Enable city form control programmatically
  this.loadStdCodes(this.organizationsList.state); // Assuming you want to load stdCodes based on state
}

clearCityAndState(): void {
  this.cityOptions = [];
  this.organizationsList.city = '';
  this.organizationsList.state = '';
  this.organizationsList.district = '';
  this.stdCodesbasedOnState = null;
}
styleForCityAndState:boolean=false

onPincodeChange(): void {
  const pincode = this.organizationsList.pincode; // Directly access pincode

  // Validate if the pincode is a valid 6-digit number
  if (pincode && /^\d{6}$/.test(pincode)) {
    this.styleForCityAndState = false; // Hide error style
    this.fetchCityState(pincode);
    
  } else {
    this.styleForCityAndState = true; // Show error style
    this.clearCityAndState(); // Clear city and state dropdowns
    this.pincodeError = pincode ? 'Pincode must be exactly 6 digits.' : 'Pincode is required.'; // Show respective error message
  }
}


navigateToReviewPage(){
  this.router.navigate(['dcmnt-pvw'], { queryParams: { domainId: this.domainsList.domainId } });

}

getStatusColor(status: string): string {
    switch (status) {
      case this.assetService.Approved:
        return '#00CC00'; // Green
      case this.assetService.Submitted:
        return '#FF6A18'; // Orange
      case this.assetService.Incomplete:
        return '#FF0000';
        case this.assetService.Rejected:
        return '#FF0000'; 
         case this.assetService.Resubmitted:
        return '#17a2b8';
      default:
        return 'black'; // Default text color
    }
  }
preventConsecutiveSpacesAndSpecialChar(event: Event, address: any): void {
  const inputElement = event.target as HTMLInputElement;
  const value = inputElement.value;

  // Prevent leading spaces (if space is the first character)
  if (value.startsWith(' ')) {
    inputElement.value = value.trim();  // Remove leading spaces if any
    return; // Prevent the space
  }

  // Prevent consecutive spaces (if space is typed after a space)
  if (value[value.length - 1] === ' ' && value[value.length - 2] === ' ') {
    inputElement.value = value.trim();  // Trim extra spaces if any
    return; // Prevent consecutive spaces
  }

  // Block special characters at the first position (if input is empty)
  if (/^[^a-zA-Z0-9]/.test(value)) {
    inputElement.value = value.replace(/^[^a-zA-Z0-9]/, '');  // Remove special character at the start
  }

  // Check for special character at the start of the input and set error accordingly
  if (/^[^a-zA-Z0-9]/.test(value)) {
    address.control.setErrors({ startWithSpecialChar: true });
  } else {
    address.control.setErrors(null); // Clear error if the value is valid
  }
}

 getUniqueDistricts(): string[] {
  return Array.from(new Set(this.cityOptions.map(city => city.district)));
}

async updateOrgDetails(){
    //console.log(this.organizationsList)
    if (this.organizationsList.pincode == null || (String(this.organizationsList.pincode)?.trim() === '')) {
      this.toastrService.error("Pincode cannot be empty");
      return;
    }else if(this.organizationsList.pincode.length<=5){
      this.toastrService.error("Please enter valid pincode");
      return;
    }
    if(this.organizationsList.address == null || (this.organizationsList.address?.trim()==='')||this.organizationsList.address.length<=5){
      return;
    }
    if(this.organizationsList.organisationEmail == null || (this.organizationsList.organisationEmail?.trim()==='')){
      this.toastrService.error("Entity email cannot be empty");
      return;
    }
    if(this.pincodeError !=''){
      // this.toastrService.error("Entity email cannot be empty");
      return;
    }
   await lastValueFrom(this.orgService.updateOrganisationDetails(this.organizationsList)).then(
    response => {
      if(response.status === HttpStatusCode.Created){
        this.toastrService.success('Entity details updated successfully.');
        //this.getDomainDetails(this.domainsList.domainId);   
    }
    });
  }

  documentComment: string = '';
  commentModalType='';
  approvalComment(orgDocType: string){
    this.commentModalType = orgDocType;

//console.log(this.approveTheDocsDisabled)

    if(orgDocType==='PAN'){
      if(!this.approveTheDocsDisabled){
         document.getElementById("panDocViewModalClose").click();
         setTimeout(() => {
          document.getElementById("approveComment").click();
         }, 10);
         
      }else{
        this.toastrService.warning("Registrant has not completed the onboarding")
      }
      
      }else if(orgDocType==='LICENCE'){
        if(!this.approveTheDocsDisabled){
           document.getElementById("licenseDocViewModalClose").click();
          setTimeout(() => {
          document.getElementById("approveComment").click();
         }, 10);
        }else{
        this.toastrService.warning("Registrant has not completed the onboarding")
      }
      }else if(orgDocType==='BOARD'){
        if(!this.approveTheDocsDisabled){
        document.getElementById("boardDocViewModalClose").click();
       setTimeout(() => {
          document.getElementById("approveComment").click();
         }, 10);
        }else{
        this.toastrService.warning("Registrant has not completed the onboarding")
      }
    } else if (orgDocType === 'GST') {
      if (!this.approveTheDocsDisabled) {
        document.getElementById("gstDocViewModalClose").click();
        setTimeout(() => {
          document.getElementById("approveComment").click();
        }, 10);
      } else {
        this.toastrService.warning("Registrant has not completed the onboarding")
      }
      
      }else if (orgDocType === 'DomainBoardDoc') {
      if (!this.approveTheDocsDisabled) {
        document.getElementById("domainBoardDocViewModalClose").click();
        setTimeout(() => {
          document.getElementById("approveComment").click();
        }, 10);
      } else {
        this.toastrService.warning("Registrant has not completed the onboarding")
      }
      
      }

      
  }

  rejectionComment(orgDocType: string){
    this.commentModalType = orgDocType;
    if(orgDocType==='PAN'){
      if(!this.approveTheDocsDisabled){
         document.getElementById("panDocViewModalClose").click();
         setTimeout(() => {
          document.getElementById("rejectComment").click();
         }, 10);
         
      }else{
        this.toastrService.warning("Registrant has not completed the onboarding")
      }
      
      }else if(orgDocType==='LICENCE'){
        if(!this.approveTheDocsDisabled){
           document.getElementById("licenseDocViewModalClose").click();
          setTimeout(() => {
          document.getElementById("rejectComment").click();
         }, 10);
        }else{
        this.toastrService.warning("Registrant has not completed the onboarding")
      }
      }else if(orgDocType==='BOARD'){
        if(!this.approveTheDocsDisabled){
        document.getElementById("boardDocViewModalClose").click();
       setTimeout(() => {
          document.getElementById("rejectComment").click();
         }, 10);
        }else{
        this.toastrService.warning("Registrant has not completed the onboarding")
      }
    } else if (orgDocType === 'GST') {
      if (!this.approveTheDocsDisabled) {
        document.getElementById("gstDocViewModalClose").click();
        setTimeout(() => {
          document.getElementById("rejectComment").click();
        }, 10);
      } else {
        this.toastrService.warning("Registrant has not completed the onboarding")
      }
    }else if (orgDocType === 'DomainBoardDoc') {
      if (!this.approveTheDocsDisabled) {
        document.getElementById("domainBoardDocViewModalClose").click();
        setTimeout(() => {
          document.getElementById("rejectComment").click();
        }, 10);
      } else {
        this.toastrService.warning("Registrant has not completed the onboarding")
      }
    }
  }

  usersList=[];
  approveTheDocsDisabled:boolean=true
 async getUsersList(organisationId: number) {
      if (isNaN(organisationId) || organisationId < 1) {
        //console.error('Invalid organisationId:', organisationId);
        return;
      }
      await lastValueFrom(this.userService.getAllUsers(organisationId)).then(
        (response) => {
          if (response.status === HttpStatusCode.Ok) {
           // this.usersList = response.body;
            this.usersList = response.body.filter((user: any) => {
            // Check if userRoles exists and is an array
              if (!user.userRoles || !Array.isArray(user.userRoles)) {
                return false; // Skip if userRoles is missing or not an array
              }

              // Check if any of the user's roles is 'Super Admin'
              const hasSuperAdminRole = user.userRoles.some((role: any) => {
                return role.roleName === 'Super Admin';
              });

              // Check the deletion status
              const isNotDeleted = (user.isDeleted === false || user.isDeleted === null);

              return hasSuperAdminRole && isNotDeleted;
            });
            this.approveTheDocsDisabled= !(response.body.some(user => user.isOnboardingCompleted === true));
            //console.log(this.approveTheDocsDisabled,"approve docs disabled")
          }
        },
        (error) => {
          if (error.status === HttpStatusCode.Unauthorized) {
            // this.isLoadingData=false;
            // this.navigateToSessionTimeout();
          }
        }
      );
    }

    //get dsc
    chosenPaymentStatus: string = '';
    getDscResponse(paymentStatus: string) {
    this.chosenPaymentStatus = paymentStatus;
    this.isLoading = true;
    this.http.get(`${this.dscApi}/dsc/getTokenRequest`).subscribe(
      (response: any) => {
        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.openPasswordModal();
                          this.toastrService.success("Fetched tokens successfully");
                        }
                        else{
                          this.tokens = [];
                          this.isLoading = false;
                          this.passwordErrorMessage = '';
                          this.toastrService.error("Failed to fetch tokens");
                          this.toastrService.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.toastrService.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.tokens = [];
              this.toastrService.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.toastrService.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.toastrService.warning("If DSC token is not inserted, please insert your DSC Token");
        this.toastrService.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
          }
        );
      }
    );
  }

   openPasswordModal() {
    this.validationError = '';
    this.isPasswordModalOpen = true;
  }

  closePasswordModal() {
    this.isPasswordModalOpen = false;
    this.tokenPassword = '';
    this.passwordErrorMessage = '';
    this.tokens = [];
    this.certificates = [];
    this.dataTypes = [];
    this.selectedCertificate = "";
    this.selectedToken = "";
    //this.router.navigateByUrl('dsc-guide');
  }

  markPaymentAsCompleted = false;

  async onSubmit(){
    this.isLoading = true;
   //console.log('Selected Token:', this.selectedCertificate);
    const signingRequestData = {
      keyId: this.selectedCertificate.keyId,
      keyStoreDisplayName: this.selectedToken,
      keyStorePassPhrase: this.tokenPassword,
      dataType: 'TextPKCS7',
      dataToSign: "I " + this.formData.name + " son/daughter of " + this.formData.fatherName 
                  + " aged " + this.formData.age + " years, hereby undertake that I am working with " 
                  + this.formData.organisationName + " as " + this.formData.designation 
                  + " and I am authorized to sign the legal documents on behalf of " + this.formData.authOrganisationName
    };
    const encodedSigningRequestData = encodeURIComponent(JSON.stringify(signingRequestData));
    //await this.getDomainByUserMailIdAndOnboardingStatus();
    this.http.get(`${this.dscApi}/dsc/getSigningRequest?signingRequestData=${encodeURIComponent(encodedSigningRequestData)}`).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.errorMessage=='0 slots found'){
                this.isLoading = false;
         //       //console.log(response);
                this.toastrService.error("Please Insert The DSC");
                return
              }
              if (embridgePKCSSignResponse) {
                const embridgePKCSSignResponseData = {
                  user: this.formData.name,
                  userMailId: localStorage.getItem('email'),
                  declaration: "I " + this.formData.name + " son/daughter of " + this.formData.fatherName 
                                + " aged " + this.formData.age + " years, hereby undertake that I am working with " 
                                + this.formData.organisationName + " as " + this.formData.designation 
                                + " and I am authorized to sign the legal documents on behalf of " + this.formData.authOrganisationName,
                  fatherName: this.formData.fatherName,
                  fatherAge: this.formData.age,
                  designation: this.formData.designation,
                  organisation: this.formData.organisationName,
                  isSigned: '',
                  certificate: JSON.stringify(this.selectedCertificate),
                  signedText: '',
                  encryptedSignedData: embridgePKCSSignResponse.responseData
                };
                this.http.post(`${this.dscApi}/dsc/getSignedResponse`, embridgePKCSSignResponseData).subscribe(
                    (response: any) => {
                         if(this.chosenPaymentStatus === 'Approve'){
                          this.approvePaymentStatus();
                         }else{
                          this.rejectPaymentStatus();
                         }
                        this.closePasswordModal();
             //           //console.log('Response from third API:', response);
                        this.isLoading = false;
               //         //console.log(response);
                        this.toastrService.success("Signed using DSC successfully");
                    },
                    (error) => {
                      const err = error?.error;
                      console.log(err)
                      if (err.errorCode === 'ERR001') {
                        this.isLoading = false;
                        this.toastrService.warning("There is an issue with token, cannot proceed further.");
                      } else if(err.errorCode === 'ERR002'){
                        this.isLoading = false;
                        this.toastrService.warning("Please use only the DSC issued by IDRBT. To obtain a DSC, kindly contact: casahyog@idrbt.ac.in, cahelp@idrbt.ac.in");
                      }
                      else {
                        this.isLoading = false;
                        this.toastrService.warning("Make sure the Token PIN entered was right");
                      }                     
                    }
                );
              }
            },
            (embridgePKCSSignAPIError) => {
              this.isLoading = false;
              this.toastrService.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.toastrService.error("Enter token pin")
        }
      },
      (error) => {
        this.isLoading = false;
        this.toastrService.warning("Please ensure the all fields entered are correct");
      }
    );
  }

   showPassword = false;
  togglePasswordVisibility() {
  this.showPassword = !this.showPassword;
}
navigateToAuthenticationError() {
  this.router.navigateByUrl("/authentication-error"); 
}

onTokenSelect(){
    this.isLoading = true;
    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) => {
              if (embridgeListCertificate) {
                const embridgeListCertificateData = {
                  encryptedCertificateData: embridgeListCertificate.responseData
                };
                this.http.post(`${this.dscApi}/dsc/getCertificateList`, embridgeListCertificateData).subscribe(
                  (response: any) => {
                    if (response.certificates != null && response.certificates.length != 0) {
                      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){
                        this.certificates = response.certificates;
                        this.isLoading = false;
                        this.passwordErrorMessage = '';
                        this.toastrService.success("Fetched certificates successfully");
                            emailMatched = true;
                            break;
                          }
                          else{
                           this.isLoading = false;
                           this.certificates = [];
                            this.navigateToAuthenticationError();
                           break;
                          }
                        }else{
                          //  if(certificateEmail === storedEmail){
                        this.certificates = response.certificates;
                        this.isLoading = false;
                        this.passwordErrorMessage = '';
                        this.toastrService.success("Fetched certificates successfully");
                        }
                      }
                    }
                    else {
                      this.certificates = [];
                      this.isLoading = false;
                      this.passwordErrorMessage = '';
                      this.toastrService.error("Failed to fetch certificates from token");
                    }
                    },
                    (error) => {
                        this.isLoading = false;
                        this.certificates = [];
                        this.passwordErrorMessage = '';
                        this.toastrService.error("Failed to fetch certificates from token");
                    }
                );
              }
            },
            (embridgeListCertificateAPIError) => {
              this.isLoading = false;
              this.certificates = [];
              this.toastrService.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.toastrService.error("Failed to fetch certificates from token");
        }
      },
      (error) => {
        this.isLoading = false;
        this.certificates = [];
        this.toastrService.error("Failed to fetch certificates from token");
      }
    );
  }
async updateDomainBasedOnisCoOperativeBank() {
    const result =await lastValueFrom(this.domainService.updateDomainBasedOnisCoOperativeBankWithInvoice(this.domainId));
      this.domain=result.body;
      this.toastrService.success("Updated Successfully")

    } catch (error) {
      this.toastrService.success("please try after some time")

    }

    async markPaymentCompleted(event: any, domain: any) {
  const isChecked = event.target.checked;

  if (isChecked) {
    const confirmAction = window.confirm("Are you sure you want to mark payment as completed? This action cannot be undone.");
    if (confirmAction) {
      try {
        domain.paymentStatus = 'Payment Completed';
        domain.markPaymentCompleted = true;
        const response = await lastValueFrom(this.domainService.updateDomainDetails(domain));
        if(response.status === HttpStatusCode.Ok){
          this.toastrService.success("Payment marked as completed successfully");
        }
      }
      catch (error) {
        event.target.checked = false; 
        this.toastrService.error("please try after some time");
      }
    } else {
      event.target.checked = false; 
      this.toastrService.info("Action cancelled. Payment status remains as " + domain.paymentStatus);
    }
  } else {
    domain.markPaymentCompleted = false;
  }
}

private extractBoardDocument(boardDocument: any, fileName: string): Map<string, any> {
    //console.log(documentField)
    if (boardDocument && fileName) {
      return new Map([
        ['fileName', fileName], 
        ['document', boardDocument]
      ]);
    } else {
      return new Map(); 
    }
  }


}