import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { DomainService } from './service/domain.service';
import { firstValueFrom, lastValueFrom } from 'rxjs';
import { HttpStatusCode } from '@angular/common/http';
import { NavigationExtras, Router } from '@angular/router';
import { UserService } from '../user/service/user.service';
import { LoginService } from '../login/service/login.service';
import { UserDomainService } from '../user-domain-details/service/user-domain.service';
import { DocumentUploadService } from '../document-upload/service/document-upload.service';
import { Domain } from '../model/domain.model';
import { AssetService } from '../asset.service';
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';
import { ToastrService } from 'ngx-toastr';
import { Modal } from 'bootstrap';
import { User } from '../model/user.model';
import { environment } from '../environments/environment';
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { NameServerService } from '../name-server-form/service/name-server.service';
import { DomainApplicationService } from '../domain-application/service/domain-application.service';
import { MatDialog } from '@angular/material/dialog';
import { TemplateRef } from '@angular/core';
import { MatDialogRef } from '@angular/material/dialog';
import { timeout } from 'rxjs/operators';
import * as docx from 'docx-preview';
import jsPDF from 'jspdf';
import html2canvas from 'html2canvas';



// import { DomainApplicationService } from './service/domain-application.service';

@Component({
    selector: 'app-rgnt-domain',
    templateUrl: './rgnt-domain.component.html',
    styleUrls: ['./rgnt-domain.component.css'],
    standalone: false
})
export class RgntDomainComponent implements OnInit {

  @ViewChild('documentRenderContainer', { static: true }) documentRenderContainer!: ElementRef;
  @ViewChild('scrollableWrapper', { static: true }) scrollableWrapper!: ElementRef;

  isScrollBottomReached = false;
  isCheckboxChecked = false;

  @ViewChild('decScrollWrapper') decScrollWrapper!: ElementRef;
  @ViewChild('decRenderContainer') decRenderContainer!: ElementRef;

  hasReadToBottom: boolean = false;
  isDecCheckboxApproved: boolean = false;
  isDocFetching: boolean = false;
  tokenPassword = '';
passwordErrorMessage = '';
isPasswordModalOpen = false;
isLoading = false;

tokens: any[] = [];
certificates: any[] = [];

selectedToken: any = "";
selectedCertificate: any = "";

showPassword = false;

embridgeUrl = 'https://localhost.emudhra.com:26769';
dscApi = environment.apiURL;

dataTypes: string[] = [
    'TextPKCS7',
    'TextPKCS1',
    'XML',
    'Sha256HashPKCS7',
    'Sha256HashPKCS1',
    'TextPKCS7ATTACHED'
  ];

 validationError : string = '';

  // openDeclarationVerificationModal(): void {
  //   // 1. Re-initialize state parameters to secure state tracking on successive invocation clicks
  //   this.hasReadToBottom = false;
  //   this.isDecCheckboxApproved = false;
  //   this.undertakingAccepted = false; //[cite: 198]
    
  //   // 2. Explicitly clear previous HTML elements out of the viewport view frame element container
  //   if (this.decRenderContainer?.nativeElement) {
  //     this.decRenderContainer.nativeElement.innerHTML = '';
  //   }

  //   // 3. Trigger modal target window visibility via standard manual compilation operations
  //   ($('#declarationDocModal') as any).modal('show');

  //   // 4. Fire background endpoint streaming content management download pipeline tasks
  //   this.getAndRenderDeclarationBlob();
  // }

  openDeclarationVerificationModal(): void {

    // RESET FLAGS
    this.hasReadToBottom = false;

    this.isDecCheckboxApproved = false;

    this.isDscSignedSuccessfully = false;

    this.undertakingAccepted = false;

    // CLEAR DOC CONTAINER
    if (this.decRenderContainer?.nativeElement) {
      this.decRenderContainer.nativeElement.innerHTML = '';
    }

    // OPEN MODAL
    ($('#declarationDocModal') as any).modal('show');

    // LOAD DOCUMENT
    this.getAndRenderDeclarationBlob();
}

  getAndRenderDeclarationBlob(): void {
    this.isDocFetching = true;
     this.hasReadToBottom = false;
    // 1. Retrieve the Bearer token from localStorage
    const token = localStorage.getItem('jwtToken');

    // 2. Configure the HttpHeaders with the Bearer token
    const headers = new HttpHeaders({
      'Authorization': `Bearer ${token}`
    });

    // 3. Set up query parameters dynamically from the existing component state
    const currentDomainId = this.domainId ; 
    const designation = this.user?.designation ;
    const userName = this.user?.userName ;
    const contactType = null; 
    const domainApiUrl = environment.apiURL + '/dr/domain';
    // 4. Construct the URL with query parameters matching your specification
    const documentUrl = `${domainApiUrl}/generateUndertaking?domainId=${currentDomainId}&desg=${designation}&name=${userName}&contactType=${contactType}`;
    
    // 5. Execute the POST request with the headers configuration and binary blob response type
    this.http.post(documentUrl, null, { headers: headers, responseType: 'blob' }).subscribe({
      next: (blob: Blob) => {
        const renderOptions = {
          className: "docx-rendered-page",
          inWrapper: false, 
          breakPages: true
        };
        
        docx.renderAsync(blob, this.decRenderContainer.nativeElement, undefined, renderOptions)
          .then(() => {
            console.log("Declaration form dynamically structured safely.");
            this.isDocFetching = false;
            
            // Safety Check: If the parsed binary format layout is small enough that no scroll bar manifests, auto-unlock 
            setTimeout(() => {
              const element = this.decScrollWrapper?.nativeElement;
              if (element && element.scrollHeight <= element.clientHeight) {
                this.hasReadToBottom = true;
              }
            }, 250);
          });
      },
      error: (error) => {
        console.error("Error downloading stream binary declaration docx chunk data:", error);
        this.toastr.error("Failed to extract backend contract declaration stream framework context maps.");
        this.isDocFetching = false;
      }
    });
  }

  onDeclarationContainerScroll(event: Event): void {
    const scrollElement = event.target as HTMLElement;
    
    // Exact distance assessment matching logic using precise coordinate bounding properties with fractional zoom safety margins
    const lowerViewingLimitOffset = scrollElement.scrollTop + scrollElement.clientHeight;
    const absoluteTotalHeightBound = scrollElement.scrollHeight;
    const mechanicalScaleBuffer = 8; 

    if (absoluteTotalHeightBound - lowerViewingLimitOffset <= mechanicalScaleBuffer) {
      this.hasReadToBottom = true;
    }
  }

//   onUndertakingCheckboxChange(event: any): void {

//   if (event.target.checked) {

//     this.openPasswordModal();

//     this.getDscResponse();

//   } else {

//     this.isDscSignedSuccessfully = false;

//     this.undertakingAccepted = false;
//   }
// }

onUndertakingCheckboxChange(event: any): void {

  if (event.target.checked) {

    // RESET EVERYTHING
    this.isDscSignedSuccessfully = false;

    this.isDecCheckboxApproved = false;

    this.undertakingAccepted = false;

    // OPEN DSC MODAL
    this.openPasswordModal();

    // LOAD DSC TOKENS
    this.getDscResponse();

  } else {

    // RESET EVERYTHING
    this.isDscSignedSuccessfully = false;

    this.isDecCheckboxApproved = false;

    this.undertakingAccepted = false;
  }
}

executeDeclarationAcceptance(): void {

  if (!this.isDscSignedSuccessfully) {

    this.toastr.warning(
      'Please complete DSC signing first'
    );

    return;
  }

  this.undertakingAccepted = true;

  localStorage.setItem(
    'undertakingAccepted',
    'true'
  );

  this.toastr.success(
    'Undertaking accepted successfully'
  );

  this.safelyCloseDeclarationModal();
}

  // executeDeclarationAcceptance(): void {
  //   if (this.isDecCheckboxApproved) {
  //     this.undertakingAccepted = true; //[cite: 198]
  //     localStorage.setItem('undertakingAccepted', 'true');
  //     this.toastr.success('Undertaking accepted successfully.'); //[cite: 307]
  //     this.safelyCloseDeclarationModal();
  //   }
  // }

 



  safelyCloseDeclarationModal(): void {
    ($('#declarationDocModal') as any).modal('hide');
    $('body').removeClass('modal-open'); //[cite: 340]
    $('.modal-backdrop').remove(); //[cite: 340]
  }

  // downloadDeclarationPdf(): void {
  //    const token = localStorage.getItem('jwtToken');

  //   // 2. Configure the HttpHeaders with the Bearer token
  //   const headers = new HttpHeaders({
  //     'Authorization': `Bearer ${token}`
  //   });

  //   // 3. Set up query parameters dynamically from the existing component state
  //   const currentDomainId = this.domainId ; 
  //   const designation = this.user?.designation ;
  //   const userName = this.user?.userName ;
  //   const contactType = null; 
  //   const domainApiUrl = environment.apiURL + '/dr/domain';
  //   // 4. Construct the URL with query parameters matching your specification
  //   const documentUrl = `${domainApiUrl}/generateUndertaking?domainId=${currentDomainId}&desg=${designation}&name=${userName}&contactType=${contactType}`;
    
  //   // 5. Execute the POST request with the headers configuration and binary blob response type
  //   this.http.post(documentUrl, null, { headers: headers, responseType: 'blob' }).subscribe({
  //    next: (blob: Blob) => {
  //           const fileURL = URL.createObjectURL(blob);

  //           const tab = window.open(fileURL, '_blank');

  //           if (!tab || tab.closed || typeof tab.closed === 'undefined') {
  //           alert('Please disable your popup blocker to view the brochure.');
  //           }

  //           setTimeout(() => URL.revokeObjectURL(fileURL), 10000);
  //       },
  //       error: (err) => {
  //           this.handleDownloadError(err);
  //       }
  //       });
  //   }

  //   private handleDownloadError(err: any): void {
  //       console.error('Download error:', err);

  //       if (err.error instanceof Blob) {
  //       const reader = new FileReader();
  //       reader.onload = () => {
  //           const errorBody = JSON.parse(reader.result as string);
  //           alert(`Error: ${errorBody.message || 'File not found'}`);
  //       };
  //       reader.readAsText(err.error);
  //       } else {
  //       alert('An unexpected error occurred while downloading the brochure.');
  //       }
  //   }

//   async downloadDeclarationPdf(): Promise<void> {
// this.isLoading = true
//   try {

//     this.isDocFetching = true;

//     // Load declaration if empty
//     if (this.decRenderContainer?.nativeElement.innerHTML === '') {

//       this.getAndRenderDeclarationBlob();

//       await new Promise(resolve => setTimeout(resolve, 3000));
//     }

//     const element = this.decRenderContainer.nativeElement;

//     // ✅ Important
//     element.style.width = '800px';
//     element.style.maxWidth = '800px';
//     element.style.overflow = 'visible';

//     // ✅ Capture full declaration
//     const canvas = await html2canvas(element, {
//       scale: 2,
//       useCORS: true,
//       scrollY: 0,
//       scrollX: 0
//     });

//     const pdf = new jsPDF('p', 'mm', 'a4');
//     const pdfWidth = 210;
//     const pdfHeight = 297;
//     const margin = 5;
//     const usableWidth = pdfWidth - (margin * 2);
//     const usableHeight = pdfHeight - (margin * 2);
//     const imgWidth = usableWidth;
//     const imgHeight =
//       (canvas.height * imgWidth) / canvas.width;
//     // ✅ Calculate one PDF page height in canvas pixels
//   const pageCanvasHeight =
//   (canvas.width * usableHeight) / usableWidth;
//     let renderedHeight = 0;
//     let pageNumber = 0;
//     while (renderedHeight < canvas.height) {
//       // ✅ Create temporary page canvas
//       const pageCanvas = document.createElement('canvas');
//       pageCanvas.width = canvas.width;
//       pageCanvas.height = Math.min(
//         pageCanvasHeight,
//         canvas.height - renderedHeight
//       );

//       const pageCtx = pageCanvas.getContext('2d');

//       if (pageCtx) {

//         pageCtx.drawImage(
//           canvas,
//           0,
//           renderedHeight,
//           canvas.width,
//           pageCanvas.height,
//           0,
//           0,
//           canvas.width,
//           pageCanvas.height
//         );
//       }

//       const pageImgData = pageCanvas.toDataURL('image/png');

//       const pageImgHeight =
//         (pageCanvas.height * imgWidth) / pageCanvas.width;

//       if (pageNumber > 0) {
//         pdf.addPage();
//       }

//       pdf.addImage(
//         pageImgData,
//         'PNG',
//         margin,
//         margin,
//         imgWidth,
//         pageImgHeight,
//         '',
//         'FAST'
//       );

//       // renderedHeight += pageCanvasHeight;
//    renderedHeight += pageCanvasHeight;

//       pageNumber++;
//     }

//     pdf.save('Declaration_Form.pdf');

//     this.toastr.success(
//       'Declaration PDF downloaded successfully'
//     );

//     this.isDocFetching = false;

//   } catch (error) {

//     console.error('PDF Download Error:', error);

//     this.toastr.error(
//       'Failed to download declaration PDF'
//     );

//     this.isDocFetching = false;
//   }
// }

async downloadDeclarationPdf(): Promise<void> {

  this.isLoading = true;

  try {

    this.isDocFetching = true;

    // Load declaration if empty
    if (this.decRenderContainer?.nativeElement.innerHTML === '') {

      this.getAndRenderDeclarationBlob();

      await new Promise(resolve => setTimeout(resolve, 3000));
    }

    const element = this.decRenderContainer.nativeElement;

    element.style.width = '800px';
    element.style.maxWidth = '800px';
    element.style.overflow = 'visible';

    const canvas = await html2canvas(element, {
      scale: 2,
      useCORS: true,
      scrollY: 0,
      scrollX: 0
    });

    const pdf = new jsPDF('p', 'mm', 'a4');

    const pdfWidth = 210;
    const pdfHeight = 297;
    const margin = 5;

    const usableWidth = pdfWidth - (margin * 2);
    const usableHeight = pdfHeight - (margin * 2);

    const imgWidth = usableWidth;

    const pageCanvasHeight =
      (canvas.width * usableHeight) / usableWidth;

    let renderedHeight = 0;
    let pageNumber = 0;

    while (renderedHeight < canvas.height) {

      const pageCanvas = document.createElement('canvas');

      pageCanvas.width = canvas.width;

      pageCanvas.height = Math.min(
        pageCanvasHeight,
        canvas.height - renderedHeight
      );

      const pageCtx = pageCanvas.getContext('2d');

      if (pageCtx) {

        pageCtx.drawImage(
          canvas,
          0,
          renderedHeight,
          canvas.width,
          pageCanvas.height,
          0,
          0,
          canvas.width,
          pageCanvas.height
        );
      }

      const pageImgData = pageCanvas.toDataURL('image/png');

      const pageImgHeight =
        (pageCanvas.height * imgWidth) / pageCanvas.width;

      if (pageNumber > 0) {
        pdf.addPage();
      }

      pdf.addImage(
        pageImgData,
        'PNG',
        margin,
        margin,
        imgWidth,
        pageImgHeight,
        '',
        'FAST'
      );

      renderedHeight += pageCanvasHeight;

      pageNumber++;
    }

    pdf.save('Declaration_Form.pdf');

    this.toastr.success(
      'Declaration PDF downloaded successfully'
    );

    // ✅ ADD HERE
    this.isLoading = false;

    this.isDocFetching = false;

  } catch (error) {

    console.error('PDF Download Error:', error);

    this.toastr.error(
      'Failed to download declaration PDF'
    );

    // ✅ ADD HERE
    this.isLoading = false;

    this.isDocFetching = false;
  }
}

  displayedColumns: string[] = [
    // 'checkbox',
    'domainId',
    'status',
    'domainName',
    'bankName',
   // 'organizationName',
    // 'numberOfYears',
    // 'registrationDate',
    //'renewalDate',
   // 'submissionDate',
    'applicationStatus',
    'paymentStatus',
    'nsRecordStatus',
    'tenure',
    //'viewNameServers',
    'resubmitComment',
    'payment',
    'uploadReceipt',
    'viewReceipt',
    'delete',
  //  'restore'
  ]; // Matches matColumnDef values

  domainsList: any[];
  domainsDataSource: MatTableDataSource<any>;
  // organisationId=  parseInt(localStorage.getItem('organisationId'));
  isEditing: boolean = false;
  undertakingAccepted: boolean = false;
  isDscSignedSuccessfully: boolean = false;
    @ViewChild('paymentDialog') paymentDialog!: TemplateRef<any>;
    selectedFile: File | null = null;
   dialogRef!: MatDialogRef<any>;
    selectedFileName: string = 'No File Selected';
    isLoadingData: boolean = false;
  organisationId: number = 0;
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;
  role: string = localStorage.getItem('userRole');
  userEmailId = localStorage.getItem('email');
  searchText: String = '';
  constructor(
    private domainService: DomainService,
    private route: ActivatedRoute,
    public assetService:AssetService,
    private router: Router, private userService: UserService, private toastr: ToastrService,
    private http: HttpClient, private nameserverService:NameServerService, 
    private toastrService: ToastrService,
    private sanitizer: DomSanitizer,
    private dialog: MatDialog,private domainApplicationService:DomainApplicationService, 
    private userDomainService: UserDomainService) {
    this.domainsDataSource = new MatTableDataSource<any>();
  }
  addButtonDisabled: boolean = true;
  modalTitle:string='';
  
 domainId:number;
  async ngOnInit(): Promise<void> {
     this.route.queryParams.subscribe(param => {
      var domainId = param['domainId'];
      this.domainId = param['domainId'];
    localStorage.setItem('isBoxVisible', 'false');
    const accepted = localStorage.getItem('undertakingAccepted');

this.undertakingAccepted = accepted === 'true';
     })

    ////console.log(this.role)
    ////console.log(this.userEmailId)
    ////console.log(this.organisationId);
    // if(this.role !== 'IDRBTADMIN'){

    //   ////console.log('exe')

    await this.getLoggedInUserDetails();
    await this.fetchOrgIdAndDomainsOfit();
    this.getOrganisationByUserMailIdAndOnboardingStatus();
    

    // }else{
    //////console.log('exe 1')
    //this.getAllDomainsList(this.userEmailId);
    //}
  }
  domain_each: Domain;
  usersList=[];
  async getDomainApplicationDetails(domainId: number) {
  try {
    //this.isLoadingData = true;
    //console.log("Datal", domainId)
    const res = await lastValueFrom(this.domainService.getDomainByDomainId(domainId));

    if (res.status === HttpStatusCode.Ok) {
      this.domain_each = res.body;
      //console.log("domain data received:", this.domainsList);
      this.fileName = this.domain_each.paymentReceiptName??'';
      this.setNsStatusOptions();
      //console.log("domain data received:", res);

      setTimeout(() => {
       // this.getOrganizationDetails(this.domain.organisationId);
      }, 0);

    } else {
      //console.log("Unexpected status code:", res.status);
      this.isLoadingData = false;
    }
  } catch (error: any) {
    if (error.status === HttpStatusCode.Unauthorized) {
      this.router.navigateByUrl('/session-timeout');
    }
    this.isLoadingData = false;
    //console.error("Error fetching domain data:", error);
  }
}



  hasSuperAdminRole(): boolean {
    return this.user?.userRoles
      ? this.user.userRoles.some(role => role.roleName === 'Super Admin'
        || role.roleName === 'Administrative Officer')
      : false;
  }
  user: User
  isSuperAdmin: boolean = false;
  async getLoggedInUserDetails() {
    try {
      const response = await lastValueFrom(
        this.userService.getUserByEmailId(localStorage.getItem('email'))
      );

      this.user = response.body;
      this.isSuperAdmin = this.hasSuperAdminRole();

    } catch (error) {
      console.error("Error fetching logged-in user:", error);
    }
  }
  loggedInUser: any = null;
  async fetchOrgIdAndDomainsOfit() {
    this.isLoadingData = true;
    if (this.userEmailId == null || this.userEmailId == '') {
      this.isLoadingData = false;
      this.navigateToSessionTimeout();
      return
    }
    await lastValueFrom(this.userService.getUserByEmailId(this.userEmailId)).then(
      (response) => {
        this.loggedInUser = response.body;
        ////console.log(response)
        this.organisationId = response.body.organisationId;
        if (this.organisationId > 0) {
          console.log("Organisation ID:", this.organisationId);
          this.getAllDomainsListByOrgId(this.organisationId);
        } else {
          this.isLoadingData = false;
          this.domainsList = [];
        }
      },
      (error) => {
        if (error.status === HttpStatusCode.Unauthorized) {
          this.isLoadingData = false;
          this.navigateToSessionTimeout();
        }
      }
    );
    await this.getOrganisationByUserMailIdAndOnboardingStatus();
    //console.log(this.onBoardingDomain)

  }

  loggedInUserMailId: string = localStorage.getItem('email');
  //    onBoardingDomain: any = null;
  //    async getOrganisationByUserMailIdAndOnboardingStatus(){
  //      //console.log('executed');
  //      this.userDomainService
  //        .getDomainDataByOnboardingStatus(this.loggedInUserMailId,
  //         true).subscribe({
  //        next:response => {     
  //          //if(response.status === HttpStatusCode.Ok){
  //            //console.log('Domain details:', response);
  //            this.onBoardingDomain = response.body;
  //            if (this.onBoardingDomain.domainId != null) {
  //             if (this.loggedInUser.isOnboardingCompleted == true) {
  //               console.log('exe')
  //               this.router.navigateByUrl('rgnt-domains');
  //             } else if (this.onBoardingDomain.userMailId == this.loggedInUser.userId
  //               && this.loggedInUser.isOnboardingCompleted == false
  //             ) {
  //               //console.log('exe')
  //               let navigationExtras: NavigationExtras = {
  //                 state: {
  //                   domainId: this.onBoardingDomain.domainId,
  //                   applicationId: this.onBoardingDomain.applicationId,
  //                   organisationId: this.onBoardingDomain.organisationId
  //                 }
  //               }
  //               setTimeout(() => {
  //                 this.router.navigateByUrl('/onboarding-stepper', navigationExtras);
  //               },100)
  //               this.router.navigateByUrl('/onboarding-stepper', navigationExtras);
  //             }
  //           }
  //            this.router.navigateByUrl('/rgnt-domains');
  //          //}
  //        },error: error => {
  //          if(error.status === HttpStatusCode.NotFound){
  //            //console.error('Domain not found');
  //        }}
  //      })
  //  }
  // onBoardingOrganisation: any = null;
  async getOrganisationByUserMailIdAndOnboardingStatus() {
    console.log(this.loggedInUser.isOnboardingCompleted);

    if (this.loggedInUser.isOnboardingCompleted == true) {
      console.log('exe')
      this.router.navigateByUrl('rgnt-domains');
    } else if (this.loggedInUser.isOnboardingCompleted == false
    ) {
      //console.log('exe')
      let navigationExtras: NavigationExtras = {
        state: {
          // domainId: this.onBoardingOrganisation.domainId,
          // applicationId: this.onBoardingOrganisation.applicationId,
          organisationId: this.organisationId
        }
      }
      setTimeout(() => {
        this.router.navigateByUrl('/onboarding-stepper', navigationExtras);
      }, 100)
      //         this.router.navigateByUrl('/onboarding-stepper', navigationExtras);
      //       }
      //     }
      //      this.router.navigateByUrl('/rgnt-domains');
      //    //}
      //  },error: error => {
      //    if(error.status === HttpStatusCode.NotFound){
      //      //console.error('Domain not found');
      //  }}
      // })
    }
  }
async getNameServersOfDomain(domainId: number): Promise<any[]> {
   const response=await firstValueFrom(this.nameserverService.getNameServersByDomainId(domainId));
   return response.body;
}
 openModal() {
    $('#paymentModal').modal('show'); // Bootstrap jQuery method
  }

  async getCurrentDomainToPay(domain: any) {
    this.domain_each = domain;
   //console.log(this.domain)
    try {
      const result = await lastValueFrom(this.nameserverService.getNameServersByDomainId(domain.domainId));
      // Process the result here
     //console.log("Nameservers:", result);
      if(result?.body?.length>0){
        this.openModal();
      }else{
        this.toastr.warning("Please add name servers")
      }
      return result; // Or do whatever you want with the result
  
    } catch (error) {
      // Handle errors here
      this.toastr.warning("Please add name servers for the domain and pay")
     //console.error("Error fetching nameservers:", error);
      throw error; // Or return a default value, or handle the error in another way.
    }
  }

  async getAllDomainsListByOrgId(orgId: number) {
    //console.log(orgId)
    await lastValueFrom(this.domainService.getAllDomainsByOrgId(orgId)).then(
      (response) => {
        if (response.status === HttpStatusCode.Ok) {
          this.domainsList = response.body;
          //this.getOrganisationByUserMailIdAndOnboardingStatus();
          //console.log(this.domainsList)
          this.domainsDataSource.data = this.domainsList;
            if(this.domainsList.length!==0){
         const onboardingDomain = this.domainsList.find(domain => domain.isOnboardingDomain === true);
          this.onBoardingDomainId = onboardingDomain.domainId;
          if (onboardingDomain) {
           if(onboardingDomain.paymentStatus=='Payment Completed'||onboardingDomain.paymentStatus=='Payment Under Review'||onboardingDomain.paymentStatus=='Payment Approved'){
            this.isOnboardingDomainPaid=true;
           }
          } else {
            this.isOnboardingDomainPaid=false;
          }
        }
          //console.log("poiuyt"+this.domainsList.length)
          if (this.domainsList.length == 1 && this.domainsList[0].applicationStatus != this.assetService.Approved) {
            this.addButtonDisabled = true
          } else {
            this.addButtonDisabled = false
          }
          setTimeout(() => {
            this.domainsDataSource.sort = this.sort;
            this.domainsDataSource.paginator = this.paginator;
          }, 0);
          this.isLoadingData = false;
        }
      },
      (error) => {
        if (error.status === HttpStatusCode.Unauthorized) {
          this.isLoadingData = false;
          this.navigateToSessionTimeout();
        }
      }
    );
  }

  async getAllDomainsList(userId: string) {
    await lastValueFrom(this.domainService.getAllDomains(userId)).then(
      (response) => {
        if (response.status === HttpStatusCode.Ok) {
          this.domainsList = response.body;
          //console.log(this.domainsList)
          this.domainsDataSource.data = this.domainsList;
          setTimeout(() => {
            this.domainsDataSource.sort = this.sort;
            this.domainsDataSource.paginator = this.paginator;
          }, 0);
        }
      },
      (error) => {
        if (error.status === HttpStatusCode.Unauthorized) {
          this.navigateToSessionTimeout();
        }
      }
    );
  }

  navigateToDomainDetails(domainId: number) {
    this.router.navigate(['/domain-details'], { queryParams: { domainId: domainId } });
  }

  navigateToSessionTimeout() {
    this.router.navigateByUrl('/session-timeout');
  }

  // navigateToAddDomain() {
  //   // if(this.domainsList.length==1 && this.domainsList[0].applicationStatus!=this.assetService.Approved){
  //   //   // this.toastr.warning("please")
  //   // }else{'
  //   if (this.hasSuperAdminRole()) {
  //     this.router.navigateByUrl('/add-domain');
  //     this.assetService.getPreviousUrl();
  //   } else {
  //     this.toastr.warning("only super admin has access")
  //   }

  //   // }
  // }

  navigateToAddDomain() {

  // ✅ Step 1: Role check (existing)
  if (!this.hasSuperAdminRole()) {
    this.toastr.warning("only super admin has access");
    return;
  }

  // ✅ Step 2: New validation (domain status)
  const hasPendingDomain = this.domainsList?.some(domain =>
    domain.status !== 'Active' && domain.status !== 'Approved'
  );

  if (hasPendingDomain) {
    this.toastr.warning(
      'You cannot add a new domain until your previous domain becomes active.'
    );
    return;
  }

  // ✅ Step 3: Navigation + KEEP THIS LINE
  this.router.navigateByUrl('/add-domain');
  this.assetService.getPreviousUrl(); // ✅ preserved
}

  applyFilter() {
    const filterValue = (event.target as HTMLInputElement).value.trim().toLowerCase(); // Get the filter text

    this.domainsDataSource.filterPredicate = (data: any, filter: string) => {

      const displayedColumnsValues = this.displayedColumns.map(column => {
        if (column === 'registrationDate' || column === 'renewalDate') {
          // For date columns, format the date to 'MMM d, y, h:mm a' format
          const dateValue = data[column];
          return this.formatDate(new Date(dateValue));
        } else if (column === 'domainName') {
          const domainName = data.domainName?.toString().toLowerCase() || "";
          const bankName = data.bankName?.toString().toLowerCase() || "";
          // //console.log(domainName+bankName)
          return bankName + domainName; // Combine for filtering
        } else {
          // For non-date columns, return the column value
          return data[column];
        }
      });

      // Perform a case-insensitive search across the columns
      return displayedColumnsValues.some(value =>
        value?.toString().toLowerCase().includes(filter)
      );
    };

    // Apply the filter value to the data source
    this.domainsDataSource.filter = filterValue;

    // Reset paginator to the first page after filtering
    if (this.domainsDataSource.paginator) {
      this.domainsDataSource.paginator.firstPage();
    }
  }
  formatDate(date: Date): string {
    const options: Intl.DateTimeFormatOptions = {
      month: 'short',  // 'Jan', 'Feb', etc.
      day: 'numeric',  // '30', '1', etc.
      year: 'numeric', // '2025', '2026', etc.
      hour: 'numeric', // '3', '12', etc.
      minute: 'numeric', // '46', '30', etc.
      hour12: true, // AM/PM format
    };

    return date.toLocaleString('en-US', options); // Format as 'Jan 30, 2025, 3:46 PM'
  }



  getFilteredDomains(): void {
    const filters = JSON.parse(localStorage.getItem('filters') || '{}'); // Retrieve filters from localStorage

    // Make sure that if the filters are empty, it handles properly
    if (!filters.organisationName && !filters.nsRecordStatus && !filters.status) {
      // If there are no filters applied, fetch all data (you might want to have a fallback here)
      this.getAllDomainsList(this.userEmailId);
      return;
    }

    this.domainService.getFilteredData(filters).subscribe(
      (response) => {
        // Check if the response has data
        if (response.body && response.body.length > 0) {
          this.domainsList = response.body;
          this.domainsDataSource.data = this.domainsList;
          this.domainsDataSource.paginator = this.paginator;
          this.domainsDataSource.sort = this.sort;
          this.noDataFound = false; // Hide "No results" message if data is found
        } else {
          // If no data is found, clear the table and show "No results" message
          this.domainsList = []; // Ensure the data list is empty
          this.domainsDataSource.data = this.domainsList; // Set the data source to empty
          this.noDataFound = true; // Set the flag to true to show "No results" message
        }
      },
      (error) => {
        //console.error('Error fetching filtered domains:', error);
        this.noDataFound = true; // In case of error, show "No results" message
      }
    );
  }


  filters = {
    userId: '',
    domainName: '',
    organisationName: '',
    nsRecordStatus: '',
    status: '',
    submissionDate: ''
  };

  resetFilters(): void {
    this.filters = {
      userId: '',
      domainName: '',
      organisationName: '',
      nsRecordStatus: '',
      status: '',
      submissionDate: ''
    };
    this.getFilteredDomains();
  }

  filterButton() {
    // Assuming you have a filter object with values (e.g., from input fields)
    const filters = {
      organisationName: this.filters.organisationName, // The value entered by the user
      nsRecordStatus: this.filters.nsRecordStatus,    // The value entered by the user
      status: this.filters.status,                     // The value entered by the user
    };

    // Store the filters in localStorage as a JSON string
    localStorage.setItem('filters', JSON.stringify(filters));

    // Clear the noDataFound flag and fetch filtered data
    this.noDataFound = false;
    this.getFilteredDomains(); // Fetch the filtered data
  }

  noDataFound: boolean = false;

  clearButton() {

    localStorage.removeItem('filters');

    this.filters.organisationName = '';
    this.filters.nsRecordStatus = '';
    this.filters.status = '';
    this.filters.domainName = '';

    this.getFilteredDomains();
  }

  get displayedColumnsWithExpand(): string[] {
    return ['expand', ...this.displayedColumns];

  }

  isExpanded(domain: Domain): boolean {
    return this.expandedElement === domain;
  }
  expandedElement: any | null;
  additionalDomainDataSource = new MatTableDataSource<string>([]);
  toggle(domain: Domain): void {
    if (this.expandedElement === domain) {
      this.expandedElement = null;
      this.additionalDomainDataSource.data = []; // Clear alias list when collapsing
    } else {
      this.expandedElement = domain;
      this.getAdditionalDomainName(domain.domainId);
    }
  }

  trackByDomainId(index: number, item: any): number {
    return item.domainId;
  }
  additionalDomainList
  async getAdditionalDomainName(domainId) {
    this.domainService.getAllAliasName(domainId).subscribe({
      next: (response) => {
        this.additionalDomainList = response.body;
        this.additionalDomainDataSource.data = this.additionalDomainList; // Set alias data source
        //console.log(this.additionalDomainList);
      },
      error: (error) => {
        if (error.status === HttpStatusCode.Unauthorized) {
          this.navigateToSessionTimeout();
        }
      }
    });
  }

  aliasData: any = {};
  async getAliasByName(aliasName: string) {
    this.domainService.getAliasName(aliasName).subscribe({
      next: (response) => {
        if (response.status === HttpStatusCode.Ok) {
          this.aliasData = response.body;
          // Handle the response as needed
          //console.log('Alias details:', response.body);
        }
      },
      error: (error) => {
        if (error.status === HttpStatusCode.Unauthorized) {
          this.navigateToSessionTimeout();
        }
      }
    });
  }
  
  async getAliasByAliasName(aliasName: string): Promise<boolean> {
    if (!aliasName) {
      //console.log(aliasName);
      return false; // Returning a boolean as expected
    }

    try {
      const response = await lastValueFrom(this.domainService.getAliasName(aliasName));
      //console.log(response)
      return response.body !== null; // Returns true if body exists, false otherwise
    } catch (error) {
      //console.error("Error fetching alias:", error);
      return false; // Handle errors by returning false
    }
  }
// openReceiptModal() {
//   const modal = document.getElementById('exampleModalCenter');
//   if (modal) {
//     (window as any).$(modal).appendTo('body').modal('show');
//   }
// }
goToUploadReceipt() {
  this.router.navigate(['/rgnt-entity-app-details']);
}

 isOnboardingDomainPaid:boolean=false;
  onBoardingDomainId:number;

  @ViewChild('aliasModal') aliasModal: ElementRef;
  async saveAliasChanges() {
    const chkalias = await this.getAliasByAliasName(this.aliasData.aliasName);

    if (chkalias) {
      this.aliasUpdateErrorMsg = "This Name Identifier is already taken";
      return;
    } else {
      this.aliasUpdateErrorMsg = '';
    }
    let alias = this.aliasData;
    this.domainService.updateAlias(alias).subscribe({
      next: (response) => {
        if (response.status === HttpStatusCode.Ok) {
          this.toastr.success('Name Identifier updated successfully');
          // Close the modal after successful update
          document.getElementById('closeAliasModalButton')?.click();
          const modal = new Modal(this.aliasModal.nativeElement);
          modal.hide();
          // Optionally, you can refresh the alias list or perform any other action
          this.getAdditionalDomainName(alias.domainId);
        }
      },
      error: (error) => {
        if (error.status === HttpStatusCode.Unauthorized) {
          this.navigateToSessionTimeout();
        }
      }
    });
  }

  aliasUpdateErrorMsg: string = '';
  validateDomain(domain: string) {
    //console.log(domain);

    // Check if domain starts with a digit
    if (/^\d/.test(domain)) {
      this.aliasUpdateErrorMsg = this.assetService.nameIdentifiers + ' cannot start with a digit';
    }
    // Check if domain is less than 3 characters
    else if (domain.length < 2) {
      this.aliasUpdateErrorMsg = this.assetService.nameIdentifiers + ' 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(domain)) {
        this.aliasUpdateErrorMsg = 'Please enter a valid ' + this.assetService.nameIdentifiers;
      } else {
        this.aliasUpdateErrorMsg = '';  // Reset error message if valid
      }
    }
  }
  savedTransaction:any = null;
async saveTransaction(transactionData: any) {
  await lastValueFrom(this.domainApplicationService.saveTransaction(transactionData)).then(
    response => {
      if(response.status === HttpStatusCode.Created) {
        this.savedTransaction = response.body;
        //console.log('Transaction initiated successfully:', response.body);
       // this.tostr.success('Transaction saved successfully');
      }
    }
  )
}
async updateOngoingTransactionForDomain(domain, trxnId){
  domain.transactionId = trxnId;
  await lastValueFrom(this.domainService.updateDomainDetails(domain)).then(
    response => {
      if(response.status === HttpStatusCode.Ok) {
        //console.log('Domain updated successfully:', response.body);
       // this.tostr.success('Transaction ID updated successfully');
      }
    }
  )
}

  openReciptasPdf:boolean
  async viewThePaymentReceipt(paymentReciept,fileName){
    //console.log(fileName)
    this.paymentRecieptPdf = null;
  this.openReciptasPdf = false;
  if(fileName?.endsWith('.pdf')){

    await this.displayPaymentPdf(paymentReciept);
    this.openReciptasPdf=true
  }else{
     
    this.openReciptasPdf=false
  }

  }



onUndertakingAccepted() {

  this.undertakingAccepted = true;

  localStorage.setItem('undertakingAccepted', 'true');

  this.toastr.success('Undertaking accepted successfully');

}


async viewReceiptForRow(domain: any) {

  try {
    // 🔁 Check active renewal
    const renewal = await lastValueFrom(
      this.domainService.getActiveRenewal(domain.domainId)
    );

    if (renewal?.renewalId && renewal?.renewPaymentReceipt) {
      console.log('[VIEW] Showing RENEWAL receipt');

      this.viewThePaymentReceipt(
        renewal.renewPaymentReceipt,
        renewal.renewPaymentReceiptName
      );
      return;
    }

  } catch (e) {
    console.log('[VIEW] No active renewal or no renewal receipt');
  }

  // 🧾 Fallback → DOMAIN receipt
  await this.getDomainApplicationDetails(domain.domainId);

  if (!this.domain_each?.paymentReceipt) {
    this.toastr.warning('Payment receipt not available');
    return;
  }

  console.log('[VIEW] Showing DOMAIN receipt');

  this.viewThePaymentReceipt(
    this.domain_each.paymentReceipt,
    this.domain_each.paymentReceiptName
  );
}



  paymentRecieptPdf:any;


  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); 
  } 
  }





 
  onPaymentStatusChange() {
    this.setNsStatusOptions();
  }


  nsStatusOptions: string[] = [];
  status: string[] = [];

  isNsStatusDisabled: boolean = true;

  setNsStatusOptions() {

    if (this.domain_each.paymentStatus) {
      this.isNsStatusDisabled = false;
    } else {
      this.isNsStatusDisabled = true;
    }
  }

  cancelDomain() {
    this.router.navigateByUrl('applications');
  }

  openPaymentDialog(): void {
    this.dialogRef = this.dialog.open(this.paymentDialog, {
      width: '500px',
    });
  }

  openUploadDialog(domain: any) {
  this.domainId = domain;

  this.dialog.open(this.paymentDialog, {
    width: '600px',
    disableClose: true
  });
}

  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,
    organisationDetailsId: 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.toastrService.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.toastrService.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);
    });
  }



  onDialogClose(): void {
    this.dialogRef.close();
  }

  fileName: string = '';
  fileType: string = '';
  fileError: string | null = null;



  cancelButton() {
    window.location.reload();
  }
  // closedButton() {
  //   $('#exampleModel').modal('hide');
  //    this.closeThePaymentUploadModal();
  // }
closedButton() {
  $('#exampleModalCenter').modal('hide');

  $('body').removeClass('modal-open');
  $('.modal-backdrop').remove();
}
  updatecancelButton() {
    $('#updateModal').modal('hide');
  }
  onFileChange1(event: any) {
    const file = event.target.files[0];  // Get the selected file
    //console.log("file payment recipt",file)
    if (file) {
      this.fileError = '';
      this.file = file;
      this.fileName = file.name;
      this.selectedFile = file;
      this.fileType = file.type;

      //console.log('File selected:', this.file);

      // Define the maximum allowed file size (in MB)
      const maxFileSize = this.maxFileSizeInMB * 1024 * 1024; // Convert MB to bytes

      // Check if the file type is valid
      if (
        this.fileType === 'application/pdf' ||
        this.fileType === 'image/png' ||
        this.fileType === 'image/jpeg' ||
        this.fileType === 'image/jpg'
      ) {
        // Check if the file size is valid
        if (this.file.size > maxFileSize) {
          this.toastrService.error(`Please select a file less than ${this.maxFileSizeInMB}MB.`);
          this.file = null;  // Reset the file input field
          this.fileName = ''; // Clear the file name display
          return;  // Stop further execution if the file is too large
        }
        localStorage.setItem('uploadedFileName', this.fileName);

        // You can add other logic here to handle the file (e.g., file upload, preview)
      } else {
        // If the file type is invalid, show an error message
        this.toastrService.error('Invalid file type. Only PDF, PNG, JPG, and JPEG are allowed.');
        this.file = null;  // Reset the file input field
        this.fileName = ''; // Clear the file name display
      }
    } else {
      // If no file is selected, log the message or handle it as needed
      //console.error('No file selected.');
    }
  }


  onFileChange(event: any, type: string) {
    const file = event.target.files[0];

    if (file) {

      this.fileError = '';
      const fileType = file.type;
      const fileSize = file.size; // File size in bytes

      const MAX_FILE_SIZE = this.maxFileSizeInMB * 1024 * 1024; // 2MB limit

      // Validate file type and size
      if (
        fileType === 'application/pdf' ||
        fileType === 'image/png' ||
        fileType === 'image/jpeg' ||
        fileType === 'image/jpg'
      ) {
        if (fileSize <= MAX_FILE_SIZE) {
          this.file = file;
          this.fileName = file.name;
          this.fileType = fileType;

          this.fileError = ''; // Clear any previous error
          //  this.clickedDocument(file);
        } else {
          this.fileError = 'File size exceeds the 2MB limit. Please upload a smaller file.';
          this.file = null;
          this.fileName = '';
        }
      } else {
        this.fileError = 'Invalid file type. Only PDF, DOC, JPEG, and PNG are allowed.';
        this.file = null;
        this.fileName = '';
      }
    }
  }
  closeModal() {
    this.fileName = '';
    this.fileError = '';
    this.file = null;
    // Add logic to hide the modal here, e.g., using Bootstrap modal methods
  }

  filePath: string = '';

  previewDocument() {
    this.tempimageUrl = '';
    this.temppdfUrl = '';

    const file = this.selectedFile; // Get the file that was selected previously

    const fileType = file.type;
    //console.log('File Type:', fileType);

    const reader = new FileReader();

    reader.onload = (e) => {
      if (fileType === 'application/pdf') {
        this.temppdfUrl = this.sanitizer.bypassSecurityTrustResourceUrl(e.target?.result as string);
        //console.log('PDF URL:', this.temppdfUrl);
        document.getElementById('documentUploading')?.click();

      } else if (fileType === 'image/png' || fileType === 'image/jpeg' || fileType === 'image/jpg') {
        this.tempimageUrl = this.sanitizer.bypassSecurityTrustResourceUrl(e.target?.result as string);
        console.log('Image URL:', this.tempimageUrl);
        document.getElementById('documentUploading')?.click();
      }
    };

    reader.readAsDataURL(file);  // Read file as Data URL
  }

  file: File | null = null;
  maxFileSizeInMB: number = environment.maxFileSizeMB;




  popUPButtonClose() {
    // $('#viewPaymentReceipt').modal('hide');
    // $('#exampleModalCenter').modal('show');
  }

  temppdfUrl: any;
  previewDocName: any;
  tempimageUrl: any;
  userId = localStorage.getItem('email');

// async uploadPaymentReceipt() {
  

//   console.log("Payment file upload")
//     if (!this.file) {
//       this.fileError = 'Please select a file to upload';
//       return;
//     }
    
//     const formData = new FormData();
//     formData.append('file', this.file);
//     formData.append('domainId', this.domainId.toString());

//     this.domainService.uploadPaymentReceipt(formData).subscribe(
//       (response) => {
//           if (response) {
//         this.domain_each.paymentReceipt = response.paymentReceipt || this.domain_each.paymentReceipt;
//         this.domain_each.paymentReceiptName = response.paymentReceiptName || this.file.name;
//         this.domain_each.paymentStatus = 'Payment Under Review';
//       }
        
//   //       document.getElementById('closePaymentReceipt')?.click();
//   //  $('#updateModal').modal('show');
//    this.toastrService.success('Payment receipt uploaded successfully!');
//    document.getElementById('updateDocumentClose')?.click();

//    this.getDomainApplicationDetails(this.domainId);
 
// //this.getDomainDetails(this.domainsList.domainId);
    
    
//       },
//       (error) => {
//        // this.fileError = 'Error uploading file: ' + error.message;
//       }
//     );
   
  
//   }

// async uploadPaymentReceipt() {


//   if (!this.file) {
//     this.fileError = 'Please select a file';
//     return;
//   }

//   const isRenewal = await this.detectActiveRenewal(this.domainId);

//   if (isRenewal && this.selectedRenewalId) {

//     this.domainService
//       .uploadRenewalPaymentReceipt(
//         this.domainId,
//         this.selectedRenewalId,
//         this.file
//       )
//       .subscribe(() => {
//         this.toastr.success('Renewal payment receipt uploaded');
//         this.closeThePaymentUploadModal();
//       });

//     return;
//   }

//   // fallback → domain receipt
//   const formData = new FormData();
//   formData.append('file', this.file);
//   formData.append('domainId', this.domainId.toString());

//   this.domainService.uploadPaymentReceipt(formData).subscribe(() => {
//     this.toastr.success('Payment receipt uploaded successfully');
//     this.getDomainApplicationDetails(this.domainId);
//   });
// }

// async uploadPaymentReceipt1() {

//   console.log('[UPLOAD] Payment file upload triggered');
//   console.log('[UPLOAD] domainId =', this.domainId);

//   if (!this.file) {
//     console.warn('[UPLOAD] No file selected');
//     this.fileError = 'Please select a file to upload';
//     return;
//   }

//   console.log('[UPLOAD] File details:', {
//     name: this.file.name,
//     size: this.file.size,
//     type: this.file.type
//   });

//   // 🔁 Check renewal status from backend
//   const isRenewal = await this.detectActiveRenewal(this.domainId);
//   console.log('[UPLOAD] isActiveRenewal =', isRenewal);
//   console.log('[UPLOAD] selectedRenewalId =', this.selectedRenewalId);

//   // ===============================
//   // 🔁 RENEWAL RECEIPT FLOW
//   // ===============================
//   if (isRenewal && this.selectedRenewalId) {

//     console.log('[UPLOAD] Uploading RENEWAL payment receipt');

//     this.domainService
//       .uploadRenewalPaymentReceipt(
//         this.domainId,
//         this.selectedRenewalId,
//         this.file
//       )
//       .subscribe(
//         () => {
//           console.log('[UPLOAD] Renewal receipt uploaded successfully');
//           this.toastrService.success('Renewal payment receipt uploaded successfully!');
//           document.getElementById('updateDocumentClose')?.click();
//           this.getDomainApplicationDetails(this.domainId);
//         },
//         (error) => {
//           console.error('[UPLOAD] Renewal receipt upload failed', error);
//         }
//       );

//     return; // 🔒 important
//   }

//   // ===============================
//   // 🧾 DOMAIN RECEIPT FLOW (EXISTING)
//   // ===============================
//   console.log('[UPLOAD] Uploading DOMAIN payment receipt');

//   const formData = new FormData();
//   formData.append('file', this.file);
//   formData.append('domainId', this.domainId.toString());

//   this.domainService.uploadPaymentReceipt(formData).subscribe(
//     (response) => {

//       console.log('[UPLOAD] Domain receipt upload response:', response);

//       if (response) {
//         this.domain_each.paymentReceipt =
//           response.paymentReceipt || this.domain_each.paymentReceipt;

//         this.domain_each.paymentReceiptName =
//           response.paymentReceiptName || this.file.name;

//         this.domain_each.paymentStatus = 'Payment Under Review';
//       }

//       this.toastrService.success('Payment receipt uploaded successfully!');
//       document.getElementById('updateDocumentClose')?.click();
//       this.getDomainApplicationDetails(this.domainId);
//     },
//     (error) => {
//       console.error('[UPLOAD] Domain receipt upload failed', error);
//     }
//   );
// }


// async uploadPaymentReceipt() {

//   console.log('[UPLOAD] Upload initiated for domainId =', this.domainId);

//   if (!this.file) {
//     console.warn('[UPLOAD] No file selected');
//     this.fileError = 'Please select a file to upload';
//     return;
//   }

//   console.log('[UPLOAD] File selected:', {
//     name: this.file.name,
//     size: this.file.size,
//     type: this.file.type
//   });

//   let activeRenewalId: number | null = null;

//   try {
//     console.log('[UPLOAD] Checking active renewal for domainId =', this.domainId);

//     const renewal = await lastValueFrom(
//       this.domainService.getActiveRenewal(this.domainId)
//     );

//     activeRenewalId = renewal?.renewalId ?? null;

//     console.log('[UPLOAD] Active renewal found. renewalId =', activeRenewalId);

//   } catch (e) {
//     console.log('[UPLOAD] No active renewal found. Using DOMAIN receipt flow');
//   }

//   // ===============================
//   // 🔁 RENEWAL RECEIPT
//   // ===============================
//   if (activeRenewalId) {

//     console.log('[UPLOAD] Uploading RENEWAL receipt');

//     this.domainService
//       .uploadRenewalPaymentReceipt(
//         this.domainId,
//         activeRenewalId,
//         this.file
//       )
//       .subscribe(
//         () => {
//           console.log('[UPLOAD] Renewal receipt uploaded successfully');
//           this.toastr.success('Renewal payment receipt uploaded');
//             this.getAllDomainsList(this.userId);
//            document.getElementById('updateDocumentClose')?.click();
//           this.getDomainApplicationDetails(this.domainId);
//         },
//         (error) => {
//           console.error('[UPLOAD] Renewal receipt upload failed', error);
//         }
//       );

//     return;
//   }

//   // ===============================
//   // 🧾 DOMAIN RECEIPT
//   // ===============================
//   console.log('[UPLOAD] Uploading DOMAIN receipt');

//   const formData = new FormData();
//   formData.append('file', this.file);
//   formData.append('domainId', this.domainId.toString());

//   this.domainService.uploadPaymentReceipt(formData).subscribe(
//     () => {
//       console.log('[UPLOAD] Domain receipt uploaded successfully');
//       this.toastr.success('Payment receipt uploaded');
//         this.getAllDomainsList(this.userId);
//         document.getElementById('updateDocumentClose')?.click();
//    this.getDomainApplicationDetails(this.domainId);
//     },
//     (error) => {
//       console.error('[UPLOAD] Domain receipt upload failed', error);
//     }
//   );
// }

async uploadPaymentReceipt() {

  console.log('[UPLOAD] Upload initiated for domainId =', this.domainId);

  if (!this.file) {
    console.warn('[UPLOAD] No file selected');
    this.fileError = 'Please select a file to upload';
    return;
  }

  console.log('[UPLOAD] File selected:', {
    name: this.file.name,
    size: this.file.size,
    type: this.file.type
  });

  let renewalData: any = null;

  // ===============================
  // 🔍 STEP 1: CHECK RENEWAL FROM BACKEND
  // ===============================
  try {
    console.log('[UPLOAD] Fetching renewal data...');

    renewalData = await lastValueFrom(
      this.domainService.getActiveRenewal(this.domainId)
    );

    console.log('[UPLOAD] Renewal API response:', renewalData);

  } catch (e) {
    console.log('[UPLOAD] No renewal found or API failed');
  }

  // ===============================
  // 🔁 STEP 2: RENEWAL RECEIPT FLOW
  // ===============================
  if (renewalData && renewalData.renewalId) {

    console.log('[UPLOAD] Uploading RENEWAL receipt');

    this.domainService
      .uploadRenewalPaymentReceipt(
        this.domainId,
        renewalData.renewalId,
        this.file
      )
      .subscribe(
        () => {
          console.log('[UPLOAD] Renewal receipt uploaded successfully');

          this.toastr.success('Renewal payment receipt uploaded');

          // refresh UI
          this.getAllDomainsList(this.userId);
          this.getDomainApplicationDetails(this.domainId);
 this.closeUploadModalProperly();
          // close modal
          // document.getElementById('updateDocumentClose')?.click();
        },
        (error) => {
          console.error('[UPLOAD] Renewal receipt upload failed', error);
        }
      );

    return; // 🔒 STOP here
  }

  // ===============================
  // 🧾 STEP 3: DOMAIN RECEIPT FLOW
  // ===============================
  console.log('[UPLOAD] Uploading DOMAIN receipt');

  const formData = new FormData();
  formData.append('file', this.file);
  formData.append('domainId', this.domainId.toString());

  this.domainService.uploadPaymentReceipt(formData).subscribe(
    () => {
      console.log('[UPLOAD] Domain receipt uploaded successfully');

      this.toastr.success('Payment receipt uploaded');

      // refresh UI
      this.getAllDomainsList(this.userId);
      this.getDomainApplicationDetails(this.domainId);

      // close modal
     // document.getElementById('updateDocumentClose')?.click();
     this.closeUploadModalProperly();
    },
    (error) => {
      console.error('[UPLOAD] Domain receipt upload failed', error);
    }
  );
}
acceptUndertaking() {

  this.undertakingAccepted = true;

  localStorage.setItem('undertakingAccepted', 'true');

  this.toastr.success('Undertaking Accepted');

}


// closeUploadModalProperly() {
//   const modal = document.getElementById('exampleModalCenter');

//   if (modal) {
//     const instance = (window as any).bootstrap.Modal.getInstance(modal);
//     if (instance) {
//       instance.hide();
//     }
//   }

//   // remove backdrop
//   document.body.classList.remove('modal-open');

//   const backdrops = document.getElementsByClassName('modal-backdrop');
//   while (backdrops.length > 0) {
//     backdrops[0].remove();
//   }
// }

// closeUploadModalProperly() {
//   setTimeout(() => {
//     $('#exampleModalCenter').modal('hide');

//     $('body').removeClass('modal-open');
//     $('.modal-backdrop').remove();

//     this.closeThePaymentUploadModal();
//   }, 200);
// }

closeUploadModalProperly() {
  setTimeout(() => {

    // ✅ Proper close using jQuery (same as your open)
    $('#exampleModalCenter').modal('hide');

    // ✅ FIX backdrop issue
    $('body').removeClass('modal-open');
    $('body').css('overflow', '');

    $('.modal-backdrop').remove();

    // ✅ KEEP your existing logic
    this.getDomainApplicationDetails(this.domain_each.domainId);

  }, 200);
}

  updatedDocumentFlag:boolean=false;

  updatePaymentReceipt() {
    if (!this.file) {
      console.log("entered file is not present")
      this.fileError = 'Please select a file to update';
      return;
    }

    this.domainService.updatePaymentReceipt(this.domainId, this.file).subscribe(
      (response) => {
                this.domain_each.paymentReceipt = response.paymentReceipt || this.domain_each.paymentReceipt;
        this.domain_each.paymentReceiptName = response.paymentReceiptName || this.file.name;
        this.domain_each.paymentStatus = "Payment Under Review";

        console.log('Response:', response);  // Log the response to see the exact structure
        if (response && response.message) {
           this.toastrService.success(' payment receipt updated successfully');
            // $('#updateModal').modal('hide');
          this.domain_each.paymentStatus = "Payment Under Review";
          this.updatedDocumentFlag = true;
         // this.updateDomain();
        } else {
          alert('Unexpected response format');
        }
      },
      (error) => {
        //console.error('Error response:', error);  // Log the error for debugging
        this.fileError = error.error?.message || 'Error updating file';  // Show the error message
      }
    );
  }

  
domainPayment: Domain = null;
//nameServersCountOfDomain: number = 0;
async verifyPayment(domain){
  if(domain.paymentStatus == 'Payment Not Done'){
    this.toastr.warning("Payment status is not under Ready For Payment");
    return;
  }

  if (
    domain.paymentStatus !== 'Payment Completed' &&
    domain.paymentStatus !== 'Payment Under Review' &&
    domain.paymentStatus !== 'Payment Approved'
  ) 
  {

    var nameServerCount = 0;
    nameServerCount =(await this.getNameServersOfDomain(domain.domainId)).length;
    if (nameServerCount > 0) {
      const updatedDomainWithActualCost = await this.validateAndPayOnUpdate(domain);
      if (updatedDomainWithActualCost != null) {
        this.domainPayment = updatedDomainWithActualCost;
        document.getElementById('paymentDetailsModalView').click();
      }
    }else{
      this.toastr.warning('Registrant has not added the name servers yet to view the payment details');
    }
  }else{  
    this.domainPayment = domain;
     document.getElementById('paymentDetailsModalView').click();
  }

}

  navigateToDomainNameServers(domainId: number) {
    if (this.role === 'IDRBTADMIN') {
      this.router.navigate(['/domain-details'], { queryParams: { domainId: domainId } });
    } else {
      this.router.navigate(['/domain-details'], { queryParams: { domainId: domainId } });
    }
  }
  //domainToBePaid:Domain;
  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 onSubmit2(domain) {  
      const updatedDomainWithActualCost  = await this.validateAndPayOnUpdate(domain);
      if(updatedDomainWithActualCost != null){
        domain = updatedDomainWithActualCost;
      }
      //validate before payement
      //console.log('exe')
      if(domain.applicationStatus === 'Incomplete'){
        this.toastr.warning('You application is incomplete. Click on the application id and Re-submit your appliation to pay.');
        return;
      } 
      if(domain.markAsDelete){
        this.toastr.warning("This domain is marked as delete by the Registrar. Please contact the registrar for further assistance.");
        return;
      }
      //console.log('exe')
      // const isValid = await this.validatePaymentReceiptNumber();
      //console.log(isValid)
      //  //window.confirm('Are you sure you want to submit with the payment?'); 
      // // Step 1: Update Payment Status before submitting
      // if(isValid){
      // domain.paymentReceiptNumber = this.paymentReceiptNumber;
      //console.log(this.domain)
      
      
      // // Step 2: Set the return URL before form submission
      // this.returnUrl = window.location.origin + '/applications'; // Example: http://localhost:4200/payment-response
      // this.tostr.success('Payment completed successfully','Success');
      // // Step 3: Submit the form - Payment form will be uncommneted later
      // // const ecomForm = document.forms['ecom'];     
      // // if (ecomForm) {       
      // //   ecomForm.submit(); 
      // // }
      // } 
      // $('#paymentModal').modal('hide'); // Bootstrap jQuery method
  
      const deptCode = "dr";
      const amountPayable = domain.cost;
    //  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 = domain.domainId;
      // const otherDetails = domain.domainId+'^'+localStorage.getItem('jwtToken');
      // const paymentData = `${deptCode},${amountPayable},${returnUrl}`;
      // const hash = btoa(paymentData); // Encode data in Base64
  
     const apiUrl = "https://serpmnt.idrbt.ac.in/pay1/ps/payment";
      //  const apiUrl = 'https://dev-serpmnt.idrbt.ac.in/pay1/ps/testPayment';
      // const apiUrl = "http://localhost:18000/ps/testPayment";
      const nameServers = await this.getNameServersOfDomain(domain.domainId);
      if(nameServers.length<=0){
        this.toastr.warning("Please Add name servers for the domain before payment.")
        return
      }
      //console.log('exe')
       console.log("qwertyui",this.isOnboardingDomainPaid)
      console.log(this.onBoardingDomainId,domain.domainId)
     if(this.isOnboardingDomainPaid==false && (this.onBoardingDomainId!=domain.domainId)){
      this.toastr.warning("Please pay your onboarding domain first")
      return
     }
     //console.log('exe')
  
      //console.log(nameServers)
      const transactionData = {
        transactionId: null,
        orderId:'',
        paymentTransactionId: '',
        amount: domain.cost,
        transactionStatus: 'Transaction Initiated',
        domainId: domain.domainId,
        organisationId: this.organisationId,
        paymentFor:"Domain"
      };
      //console.log(transactionData)
    
     //save transaction inititaion to transactions_table
      await this.saveTransaction(transactionData);
       //console.log(transactionData)
  
      await this.updateOngoingTransactionForDomain(domain, this.savedTransaction.transactionId);
  
      //console.log(this.domainsList)
  
      if(environment.isPaymentEnabled){
         this.http.post<{ redirectUrl: string }>(apiUrl, { deptCode: deptCode, amount: amountPayable, returnUrl: url, otherDetails:  otherDetails}).subscribe(response => {
         if (response.redirectUrl) {
           //console.log("Redirecting to Angular page...");
           window.location.href = response.redirectUrl;  // Redirect after receiving JSON response
         }
       });
      }else{
        await this.updatePaymentSatus(domain, 'Payment Completed');
      }
      
  }



  //   async updatePaymentSatus(domain:Domain, paymentStatus) {
  // //  domain.paymentStatus='processing'
  // domain.paymentStatus=paymentStatus;
  //  await lastValueFrom(this.domainService.updateDomainDetails(domain)).then(
  //   (response)=>{
  //     //console.log(response)
  //     this.domainsDataSource._updateChangeSubscription();
  //     // this.router.navigate(['/pmnt-sbms'], { queryParams: { domainId: domain.domainId } });
  //   })
  // }

async updatePaymentSatus(domain: Domain, paymentStatus) {

  // 🔥 VERY IMPORTANT: CHECK RENEWAL FIRST
  let renewal = null;

  try {
    renewal = await lastValueFrom(
      this.domainService.getActiveRenewal(domain.domainId)
    );
  } catch (e) {}

  // 🚫 STOP if renewal exists
  if (renewal && renewal.renewalId) {
    console.log("🚫 Renewal flow detected → NOT updating domain payment status");
    return;
  }

  // ✅ ONLY for domain payment
  domain.paymentStatus = paymentStatus;

  await lastValueFrom(this.domainService.updateDomainDetails(domain));

  this.domainsDataSource._updateChangeSubscription();
}

  getStatusColor(status: string): string {
    switch (status) {
      case null:
        return '#FF0000'; // Red for null 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
    }
  }

  

  
  getTooltipMessage(status: string): string {
    switch (status) {
      case null:
        return this.assetService.incompleteTooltip;
      case this.assetService.Incomplete:
        return this.assetService.incompleteTooltip;
      case this.assetService.Approved:
        return this.assetService.applicationApprovedToolTip;
      case this.assetService.Submitted:
        return this.assetService.underReviewToolTip;
      case this.assetService.Resubmitted:
        return this.assetService.domainApplicationResubmissionToolTip;
      default:
        return 'No additional information available.';
    }
  }

  // isUploadEnabled(): boolean {
  //   const status = this.domain_each?.paymentStatus;
  //   if (!status) {
  //     return false; // default disable if status is missing
  //   }
  //   return status === 'Payment Completed'
  //     || status === 'Payment Rejected'
  //     || status === 'Payment Under Review';
  // }

// isUploadEnabledForRow(domain: any): boolean {

//   const status =
//     domain.renewalPaymentStatus || domain.paymentStatus;

//   return (
//     status === 'Payment Completed' ||
//     status === 'Payment Under Review'
//   );
// }

isUploadEnabledForRow(domain: any): boolean {

  const status = domain.paymentStatus;

  return (
    status === 'Payment Completed' ||
    status === 'Payment Under Review' ||
    status === 'Payment Rejected'
  );
}

// canEnableViewReceipt(domain: any): boolean {
//   const status =
//     domain.renewalPaymentStatus || domain.paymentStatus;

//   return (
//     status === 'Payment Under Review' ||
//     status === 'Payment Approved' 
  
//   );
// }

canEnableViewReceipt(domain: any): boolean {

  // ✅ If receipt exists (domain OR renewal)
  const hasDomainReceipt = !!domain.paymentReceiptName;
  const hasRenewalReceipt = !!domain.renewPaymentReceiptName;

  // ✅ Payment conditions
  const isValidPaymentStatus =
    domain.paymentStatus === 'Payment Approved' ||
    domain.paymentStatus === 'Payment Under Review';

  // ✅ Renewal condition
  const isRenewed = domain.renewalStatus === 'Renewed';

  return hasDomainReceipt || hasRenewalReceipt || isValidPaymentStatus || isRenewed;
}




// canEnableViewReceipt(domain: any): boolean {

//   const status = (
//     domain.renewalPaymentStatus
//       ? domain.renewalPaymentStatus
//       : domain.paymentStatus || ''
//   ).toLowerCase().trim();

//   const hasReceipt =
//     (domain.renewalPaymentReceiptName && domain.renewalPaymentReceiptName.trim() !== '') ||
//     (domain.paymentReceiptName && domain.paymentReceiptName.trim() !== '');

//   return (
//     (
//       status === 'payment under review' ||
//       status === 'payment approved' ||
//       status === 'payment completed'
//     )
//     && hasReceipt
//   );
// }
// canEnableViewReceipt(domain: any): boolean {
//   const status =
//     domain.renewalPaymentStatus || domain.paymentStatus;

//   return status === 'Payment Completed';
// }



setUploadDomain(domain: any) {
  this.domain_each = domain;
  this.domainId = domain.domainId;
}

// openUploadModal(domain: any) {
//   this.setUploadDomain(domain);

//   const modal = new (window as any).bootstrap.Modal(
//     document.getElementById('exampleModalCenter')
//   );

//   modal.show();
// }


// openUploadModal(domain: any) {
//   this.setUploadDomain(domain);

//   $('#exampleModalCenter').modal('show');  // ✅ Bootstrap 4 तरीका
// }

openUploadModal(domain: any) {

  this.undertakingAccepted = false;

  localStorage.removeItem('undertakingAccepted');

  this.domainId = domain.domainId;

  $('#exampleModalCenter').modal('show');

}
  isEditAllowed(): boolean {
    const appStatus = this.domain_each?.applicationStatus;
    const payStatus = this.domain_each?.paymentStatus;

    return appStatus !== 'Approved' &&
      !['Payment Completed', 'Payment Under Review', 'Payment Approved'].includes(payStatus);
  }

  // closeThePaymentUploadModal(){
  //   this.getDomainApplicationDetails(this.domain_each.domainId);
  // }
closeThePaymentUploadModal() {

  // ✅ Step 1: Refresh data (your existing logic)
  this.getDomainApplicationDetails(this.domain_each.domainId);

  // ✅ Step 2: Close modal (ADD THIS)
  const modalEl = document.getElementById('exampleModalCenter');

  if (modalEl) {
    const modal = new Modal(modalEl);
    modal.hide();
  }

  // ✅ Step 3: Cleanup (VERY IMPORTANT)
  const backdrops = document.getElementsByClassName('modal-backdrop');
  while (backdrops.length > 0) {
    backdrops[0].parentNode?.removeChild(backdrops[0]);
  }

  document.body.classList.remove('modal-open');
  document.body.style.overflow = '';
}
openReceiptModal() {
  const modal = document.getElementById('viewThePaymentReceipt');
  if (modal) {
    const bootstrapModal = new (window as any).bootstrap.Modal(modal);
    bootstrapModal.show();
  }
}


// DSC methods
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');
  }

  getDscResponse() {
      this.isLoading = true;
      this.http.get(`${this.dscApi}/dsc/getTokenRequest`).subscribe(
        (response: any) => {
         // console.log('Response from getTokenRequest API:', response);
          if (response && response.encryptedData && response.encryptionKeyID) {
            const payload = {
              encryptedRequest: response.encryptedData,
              encryptionKeyID: response.encryptionKeyID
            };
            this.http.post(`${this.embridgeUrl}/DSC/ListToken`, payload).pipe(timeout(10000)).subscribe(
              (embridgeListTokenAPI: any) => {
                if (embridgeListTokenAPI) {
                  const embridgeListTokenAPIData = embridgeListTokenAPI.responseData;
                  this.http.get(`${this.dscApi}/dsc/getTokenList?data=${encodeURIComponent(embridgeListTokenAPIData)}`).subscribe(
                      (response: any) => {
                          if(response.tokenNames != null && response.tokenNames.length != 0){
                            this.tokens = response.tokenNames;
                            this.isLoading = false;
                            this.passwordErrorMessage = '';
                            this.openPasswordModal();
                            this.toastr.success("Fetched tokens successfully");
                          }
                          else{
                            this.tokens = [];
                            this.isLoading = false;
                            this.passwordErrorMessage = '';
                            this.toastr.error("Failed to fetch tokens");
                            this.toastr.warning("If DSC token is not inserted, please insert your DSC Token");
                          }
                      },
                      (error) => {
                          this.isLoading = false;
                          this.tokens = [];
                          this.toastr.warning("If DSC token is not inserted, please insert your DSC Token");
                      }
                  );
  
                }
                else{
                  this.isLoading = false;
                  this.tokens = [];
                }
              },
              (embridgeListTokenAPIError) => {
                this.passwordErrorMessage = 'Failed to get valid tokens.';
                this.isLoading = false;
                this.tokens = [];
                this.toastr.warning(
                  "Please check if Embridge is installed and in running state. If not please install Embridge and run it!!!",
                  "Warning",
                  {
                    timeOut: 20000,
                    progressBar: true,
                    closeButton: true
                  }
                );
              }
            );
          } else {
            this.passwordErrorMessage = 'Failed to get valid tokens.';
            this.isLoading = false;
            this.tokens = [];
            this.toastr.warning("If DSC token is not inserted, please insert your DSC Token");
          }
        },
        (error) => {
          this.isLoading = false;
          this.tokens = [];
          this.toastr.warning("If DSC token is not inserted, please insert your DSC Token");
          this.toastr.warning(
            "Please check if Embridge is installed and in running state. If not please install Embridge and run it!!!",
            "Warning",
            {
              timeOut: 20000,
              progressBar: true,
              closeButton: true
            }
          );
        }
      );
    }

  
    
  
    preventSpecialChars(event: KeyboardEvent): void {
      const regex = /^[a-zA-Z\s]+$/; // Allows only alphabets and spaces
      const key = event.key;
      const inputElement = event.target as HTMLInputElement;
   
      // Prevent invalid characters
      if (!regex.test(key)) {
        event.preventDefault(); // Prevent the default behavior if the character is not allowed
      }
   
      // Prevent leading spaces
      if (key === ' ' && inputElement.value === '') {
        event.preventDefault(); // Block spaces as the first character
      }
   
      // Prevent consecutive spaces
      if (key === ' ' && inputElement.value[inputElement.value.length - 1] === ' ') {
        event.preventDefault(); // Block an additional space if the last character is already a space
      }
    }
  
    preventSpecialCharsAndAllowNumbers(event: KeyboardEvent): void {
      const regex = /^[a-zA-Z1-9\s]+$/; // Only allows alphanumeric characters
      const key = event.key;
      const inputElement = event.target as HTMLInputElement;
      if (!regex.test(key)) {
        event.preventDefault(); // Prevent the default behavior if the character is not allowed
      }
      if (key === ' ' && inputElement.value === '') {
        event.preventDefault(); // Block spaces as the first character
      }
   
      // Prevent consecutive spaces
      if (key === ' ' && inputElement.value[inputElement.value.length - 1] === ' ') {
        event.preventDefault(); // Block an additional space if the last character is already a space
      }
    }
    clearErrors() {
      // Reset validation error and age error
      this.validationError = '';
      // this.ageError = false;
    }
    onPaste(event: ClipboardEvent) {
      event.preventDefault();
      
      const clipboardData = event.clipboardData || (window as any).clipboardData;
      let pastedText = clipboardData.getData('text');
    
      // Remove numbers and special characters
      pastedText = pastedText.replace(/[^a-zA-Z\s]/g, '');
    
      // Set the sanitized text back into the input field
      document.execCommand('insertText', false, pastedText);
    }

     onTokenSelect(){
    this.isLoading = true;
    this.http.get(`${this.dscApi}/dsc/getCertificateRequest?keyStoreDisplayName=${encodeURIComponent(this.selectedToken)}`).subscribe(
      (response: any) => {
        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.toastr.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.toastr.success("Fetched certificates successfully");
                        
                        }
                      }
                    }
                    else {
                      this.certificates = [];
                      this.isLoading = false;
                      this.passwordErrorMessage = '';
                      this.toastr.error("Failed to fetch certificates from token");
                    }
                  //      console.log(this.certificates);
                    },
                    (error) => {
                        this.isLoading = false;
                        this.certificates = [];
                        this.passwordErrorMessage = '';
                        this.toastr.error("Failed to fetch certificates from token");
                    }
                );
              }
            },
            (embridgeListCertificateAPIError) => {
              this.isLoading = false;
              this.certificates = [];
              this.toastr.warning(
                "Please check if Embridge is installed and in running state. If not please install Embridge and run it!!!",
                "Warning",
                {
                  timeOut: 20000,
                  progressBar: true,
                  closeButton: true
                }
              );
            }
          );  
        } else {
          this.isLoading = false;
          this.certificates = [];
          this.toastr.error("Failed to fetch certificates from token");
        }
      },
      (error) => {
        this.isLoading = false;
        this.certificates = [];
        this.toastr.error("Failed to fetch certificates from token");
      }
    );
  }


  


  togglePasswordVisibility() {
  this.showPassword = !this.showPassword;
}
navigateToAuthenticationError() {
  this.router.navigateByUrl("/authentication-error"); 
}


async onSubmit() {

  this.isLoading = true;

  this.domainService.getUndertakingHash(
    this.domainId,
    this.user?.designation,
    this.user?.userName
  ).subscribe({

    next: (hash: any) => {

      this.signUndertaking(hash);

    },

    error: () => {

      this.isLoading = false;

      this.toastr.error(
        'Failed to generate undertaking hash'
      );
    }

  });

}
signUndertaking(hash:string) {

const signingRequestData = {

  keyId: this.selectedCertificate.keyId,

  keyStoreDisplayName: this.selectedToken,

  keyStorePassPhrase: this.tokenPassword,

  dataType: 'Sha256HashPKCS7',

  dataToSign: hash
};

this.http.post(
`${this.dscApi}/dsc/getSigningRequest`,
signingRequestData

).subscribe({

next: (response:any) => {

 const payload = {

   encryptedRequest: response.encryptedData,

   encryptionKeyID: response.encryptionKeyID
 };

 this.http.post(
 `${this.embridgeUrl}/DSC/PKCSSign`,
 payload

 ).subscribe({

 next: (signResponse:any) => {

   this.saveSignedUndertaking(
      signResponse.responseData
   );

 },

 error: () => {

   this.isLoading = false;

   this.toastr.error(
      'DSC signing failed');
 }

});

},

error: () => {

 this.isLoading = false;

 this.toastr.error(
   'Signing request failed');
}

});

}

saveSignedUndertaking(
  signedData: string
) {

  const payload = {

    domainId: this.domainId,

    signedData: signedData,

    certificate: JSON.stringify(this.selectedCertificate),

    designation: this.user?.designation,

    name: this.user?.userName
  };

  this.domainService
    .saveSignedUndertaking(payload)
    .subscribe({

      next: () => {

   this.isLoading = false;

   // IMPORTANT
   this.isDscSignedSuccessfully = true;

   this.isDecCheckboxApproved = true;

   this.undertakingAccepted = true;

   localStorage.setItem(
      'undertakingAccepted',
      'true'
   );

   this.toastr.success(
      'Undertaking signed successfully'
   );

   this.closePasswordModal();
},
      error: () => {

        this.isLoading = false;

        this.toastr.error(
          'Failed to save signed undertaking'
        );
      }

    });

}










// DSC Methods End


selectedDomainForReceipt: any;

openReceiptSelection(domain: any) {
  this.selectedDomainForReceipt = domain;
  $('#receiptSelectionModal').modal('show');
}

async viewDomainReceipt(domain: any) {

  this.closeSelectionModal();

  await this.getDomainApplicationDetails(domain.domainId);

  if (!this.domain_each?.paymentReceipt) {
    this.toastr.warning('Domain receipt not available');
    return;
  }

  this.modalTitle = 'Domain';

  this.viewThePaymentReceipt(
    this.domain_each.paymentReceipt,
    this.domain_each.paymentReceiptName
  );

  $('#viewThePaymentReceipt').modal('show');
}


async viewRenewalReceipt(domain: any) {

  this.closeSelectionModal();

  let renewal = null;

  try {
    renewal = await lastValueFrom(
      this.domainService.getActiveRenewal(domain.domainId)
    );
  } catch (e) {
    this.toastr.warning('No renewal found');
    return;
  }

  if (!renewal?.renewalPaymentReceipt) {
    this.toastr.warning('Renewal receipt not available');
    return;
  }

  this.modalTitle = 'Renewal';

  this.viewThePaymentReceipt(
    renewal.renewalPaymentReceipt,
    renewal.renewalPaymentReceiptName
  );

$('#viewThePaymentReceipt').modal('show');
}


closeReceiptModal() {
  const modal = document.getElementById('viewThePaymentReceipt');
  if (modal) {
    const instance = (window as any).bootstrap.Modal.getInstance(modal);
    if (instance) {
      instance.hide();
    }
  }


  

  // 🔥 REMOVE BACKDROP (VERY IMPORTANT)
  const backdrops = document.getElementsByClassName('modal-backdrop');
  while (backdrops.length > 0) {
    backdrops[0].remove();
  }
}

closeViewReceiptModal() {
  $('#viewThePaymentReceipt').modal('hide');
}

closeSelectionModal() {
  $('#receiptSelectionModal').modal('hide');
}


deleteDomain(domain: any) {

  // ❌ Block only if application approved
  if (domain.applicationStatus === 'Approved') {
    this.toastr.warning('Approved domain cannot be deleted');
    return;
  }

  // 🔥 Build confirmation message
  let message = 'Are you sure you want to delete this domain?';

  // ✅ Add payment warning (but still allow delete)
  if (
    domain.paymentStatus === 'Payment Completed' ||
    domain.paymentStatus === 'Payment Under Review'
  ) {
    message += '\n\n⚠️ Payment Made for this will NOT be refunded to eliminate administrative and recancellation Cost';
  }

  // ✅ Confirm popup
 if (!confirm(message)) {
    this.toastr.info("Operation cancelled.");
    return;
  }

  this.domainApplicationService.deleteDomainOnly(domain.domainId)
    .subscribe({
      next: (res) => {
        if (res) {
          this.toastr.success('Domain deleted successfully');
          this.fetchOrgIdAndDomainsOfit();
        } else {
          this.toastr.warning('Deletion not allowed');
        }
      },
      error: () => {
        this.toastr.error('Error deleting domain');
      }
    });
}



canRestore(domain: any): boolean {
  return (
    domain.status === 'redemptionPeriod' &&
    !domain.restoreStatus
  );
}

requestRestore(domain: any) {
  this.domainService.requestRestore(domain.domainId).subscribe(() => {
    this.toastr.success('Restore request submitted');
  });
}




}
