import { Component, ElementRef, OnInit, TemplateRef, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { DomainService } from '../rgnt-domain/service/domain.service';
import { DomainApplicationDetailsService } from '../domain-application-details/service/domain-application-details.service';
import { ToastrService } from 'ngx-toastr';
import { Domain } from '../model/domain.model';
import { HttpClient, HttpStatusCode } from '@angular/common/http';
import { MatDialog, MatDialogRef } from '@angular/material/dialog';
import { lastValueFrom } from 'rxjs/internal/lastValueFrom';
import { DomSanitizer } from '@angular/platform-browser';
import { environment } from '../environments/environment';
import { DocumentUploadService } from '../document-upload/service/document-upload.service';
import { ContactDocumentUploadService } from '../contact-document-upload/service/contact-document-upload.service';
import { ContactDetailsFormService } from '../contact-details-form/service/contact-details-form.service';
import { OrganisationDetailsService } from '../organisation-details/service/organisation-details.service';
import { NgModel } from '@angular/forms';
import { AssetService } from '../asset.service';
import { UserDomainService } from '../user-domain-details/service/user-domain.service';
import { Modal } from 'bootstrap';
import { RegistrationService } from '../registration/service/Registration.service';
import { UserService } from '../user/service/user.service';
import { AnyCatcher } from 'rxjs/internal/AnyCatcher';

@Component({
    selector: 'app-rgnt-domain-application-details',
    templateUrl: './rgnt-domain-application-details.component.html',
    styleUrls: ['./rgnt-domain-application-details.component.css'],
    standalone: false
})
export class RgntDomainApplicationDetailsComponent implements OnInit {

  isEditing: boolean = false;
  @ViewChild('paymentDialog') paymentDialog!: TemplateRef<any>;
  selectedFile: File | null = null;
  dialogRef!: MatDialogRef<any>;
  selectedFileName: string = 'No File Selected';
  isLoadingData:boolean=false;
  role: string = localStorage.getItem('userRole');

  constructor(private route: ActivatedRoute,
    private domainService: DomainService, private http: HttpClient,
     private oreganizationService:DomainApplicationDetailsService,
     private orgService: OrganisationDetailsService,
     private toastrService: ToastrService,
    private router: Router,private sanitizer: DomSanitizer,
    private documentService:DocumentUploadService,
    private contactDocumentsService:ContactDocumentUploadService,
    private contactDetailsService:ContactDetailsFormService,
    private organizationDetailsService:OrganisationDetailsService,
  private dialog: MatDialog,private assetService:AssetService,
private userdomainService:UserDomainService,
private registrationService:RegistrationService,
private organisationDetailsService:OrganisationDetailsService,
private userService:UserService) {
    const savedFileName = localStorage.getItem('uploadedFileName');
    if (savedFileName) {
      this.fileName = savedFileName??'';
    }
  }

  domainId: number; 
  async ngOnInit(): Promise<void> {
    this.route.queryParams.subscribe(param => {
      var domainId = param['domainId'];
      this.domainId = param['domainId'];
    })
    //console.log(this.domainId)
   // this.isLoadingData=true
    await this.getAllCountryCodes();
    await this.getDomainApplicationDetails(this.domainId);
  

    await this.getAllUsersOfOrg(this.domainsList.organisationId);
    
    this.getMaxDomainLength();
    this.getRegularExpressionForEmail();
    //console.log('executed')
    //console.log('executed2')
    
    this.route.queryParams.subscribe(params => {
      this.fileName = params['fileName']??'';
      this.fileType = params['fileType'];
    });
  }
  domainsList: 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.domainsList = res.body;
      //console.log("domain data received:", this.domainsList);
      this.fileName = this.domainsList.paymentReceiptName??'';
      this.setNsStatusOptions();
      //console.log("domain data received:", res);

      setTimeout(() => {
        this.getOrganizationDetails(this.domainsList.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);
  }
}



  async getDomainDetails(domainId:number) {
    //this.isLoadingData=true;
     //console.log("Datal",domainId)
     await lastValueFrom(this.domainService.getDomainByDomainId(domainId)).then(
        (res) => {
         if (res.status === HttpStatusCode.Ok) {
           this.domainsList = res.body;
           //console.log(this.domainsList)
           this.fileName=this.domainsList.paymentReceiptName??'';
           this.updatePaymentReceipt();
          //console.log("domain data received:",res);
         this.getOrganizationDetails(this.domainsList.organisationId);
         } else {
           //console.log("Unexpected status code:", res.status);
          this.isLoadingData=false
         }
       },
       (error) => {
         this.isLoadingData=false
         //console.error("Error fetching domain data:", error);
       }
     );
   }

  organizationsList:any={};
  async getOrganizationDetails(organisationId:number) {
   
    //console.log("Datal",organisationId)
    this.oreganizationService.getOrganizationByDomainId(organisationId).subscribe({
      next: (res) => {
        if (res.status === HttpStatusCode.Ok) {
          this.organizationsList = res.body;
          //console.log(this.organizationsList);
          this.onPincodeChange();
          this.getOrgDocuments(organisationId);
          this.getUsersList(organisationId)
         //console.log("organization data received:",res);
        } else {
          //console.log("Unexpected status code:", res.status);
          this.isLoadingData=false
        }
      },
      error: (error) => {
        //console.error("Error fetching organization data:", error);
        this.isLoadingData=false
      }
    });
  }
  gstDoc:any
  panDoc:any
  licenseDoc:any
  boardResolutionDoc:any;
  boardApprovalDoc:any;
  entireOrgDocsObj:any;
  panDocPdf:any
  gstDocPdf:any
  licenceDocPdf:any
  boardResolutionDocPdf:any
  boardApprovalDocPdf: any
  orgGstStatus;
  orgPanStatus;
  orgLicenceStatus;
  orgBoardStatus;
  orgDocNames:string[]=[]
  orgGSTDocComment;
orgPanDocComment;
orgLicenceDocComment;
orgBoardDocComment;
  async getOrgDocuments(orgId){
    await lastValueFrom(this.documentService.getOrgDoucumentsById(orgId)).then(
      response => {
        //console.log("hello")
        this.entireOrgDocsObj=response.body;
        //console.log(this.entireOrgDocsObj)
        this.entireOrgDocsObj.forEach(doc => {
          if (doc.organisationGstinNumber && doc.organisationGstinNumber.trim() !== '') { 
            this.orgGstStatus = doc.documentStatus; 
            this.orgGSTDocComment = doc.comment;
          }
          if (doc.panNumber && doc.panNumber.trim() !== '') { 
            this.orgPanStatus = doc.documentStatus; 
             this.orgPanDocComment = doc.comment;
          }
          if (doc.licenseNumber && doc.licenseNumber.trim() !== '') { 
            this.orgLicenceStatus = doc.documentStatus;
            this.orgLicenceDocComment = doc.comment; 
          }
          if(doc.boardResolutionDocument){
            this.orgBoardStatus=doc.documentStatus;
            this.orgBoardDocComment = doc.comment;
          }
          this.orgDocNames.push(doc.fileName);
          // ... similar checks for other document types
          //console.log(this.orgGstStatus, this.orgPanStatus, this.orgLicenceStatus, this.orgBoardStatus);
        });
        //console.log(this.orgDocNames)
        this.getContactOfficerDocuments(orgId);
      
      },(error)=>{
        //console.log(error)
        this.isLoadingData=false
        if(error.status===HttpStatusCode.Unauthorized){
          this.isLoadingData=false
          this.router.navigateByUrl("session-timeout");
        }
      }
    )
  }
  showTooltip(){
    document.getElementById("myTooltip").style.display = "block";
  }
  hideTooltip(){
    document.getElementById("myTooltip").style.display = "none";
  }

  domain : Domain = new Domain()

  async updateOrgDetails(){
    // if(this.domainsList.applicationStatus !== 'Incomplete' && 
    //   this.domainsList.applicationStatus !== 'Resubmitted'
    // ){
    //   return;
    // }
    //console.log(this.organizationsList)
    if(this.organizationsList.institutionName == null || this.organizationsList.institutionName ==''){
      return
    }
    if(!this.emailCheck()){
      return
    }
    if (this.organizationsList.pincode == null || (String(this.organizationsList.pincode)?.trim() === '')) {
      this.toastrService.error("Pincode cannot be empty");
      return;
    }else if(this.organizationsList.pincode.length<=5){
      this.toastrService.error("Please enter valid pincode");
      return;
    }
    if(this.organizationsList.address == null || (this.organizationsList.address?.trim()==='')||this.organizationsList.address.length<=5){
      return;
    }
    if(this.pincodeError !=''){
      return;
    }
   await this.validateCountryAndMobile();
   await this.validateStdAndTelephone();
   if(this.countryCodeMobileCombinationError!=''){
      return
   }
   if(this.stdCodeAndTelephoneCombinationError!=''){
    return
   }
   await lastValueFrom(this.orgService.updateOrganisationDetails(this.organizationsList)).then(
    response => {
      if(response.status === HttpStatusCode.Created){
        this.toastrService.success('Entity details updated successfully.');
        //this.getDomainDetails(this.domainsList.domainId);   
    }
    });
  }

  openReciptasPdf:boolean
async viewThePaymentReceipt(paymentReciept,fileName){
  //console.log(fileName)
if(fileName?.endsWith('.pdf')){
  
  await this.displayPaymentPdf(paymentReciept);
  this.openReciptasPdf=true
}else{
  this.openReciptasPdf=false
}
  
  
  document.getElementById("viewThePaymentRecipt").click();
}

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); 
} 
}

  updateDomain() {
    ////console.log('Starting domain update process...');
    //console.log(this.organizationsList,this.domainsList)
    if (this.organizationsList?.pincode == null || (String(this.organizationsList.pincode)?.trim() === '')) {
      // this.toastrService.error("Pincode cannot be empty");
      return;
    }else if(this.organizationsList?.pincode.length<=5){
      // this.toastrService.error("Please enter valid pincode");
      return;
    }
    if(this.organizationsList?.address == null || (this.organizationsList?.address?.trim()==='')||this.organizationsList.address.length<=5){
      return;
    }
    if(this.pincodeError!=''){
      return
    }
      this.domainsList.modifiedByEmailId= localStorage.getItem('email');
      this.domainsList.modifiedDateTime= new Date();
    this.oreganizationService.updateDomain(this.domainId, this.domainsList).subscribe({
        next: (response) => {
            //console.log('Response received:', response);

            if (response.status === HttpStatusCode.Ok) {
                //console.log('Domain update successful.');

                  //this.domain = response.body;
                if(this.updatedDocumentFlag==false){
                  this.toastrService.success("Domain data updated successfully.");
                  // document.getElementById('updateDocumentClose')?.click();
                }
                this.updatedDocumentFlag=false;
                
              
            } else if (response.status === HttpStatusCode.NotFound) {
                //console.log('Domain not found.');
                this.toastrService.error("Domain not found.");
            } else {
                //console.log('Unexpected response status:', response.status);
                this.toastrService.error("Unexpected error during update.");
            }
        },
        error: (error) => {
            //console.error('Error occurred during domain update:', error);

            if (error.status === HttpStatusCode.InternalServerError) {
                //console.log('Internal server error.');
                this.toastrService.error("Internal server error. Domain data not updated.");
            } else {
                //console.log('Other error status:', error.status);
                this.toastrService.error("An error occurred while updating the domain.");
            }

            //console.error('Full error:', error);
        }
    });
}

onPaymentStatusChange() {

  this.setNsStatusOptions();
}
 

nsStatusOptions: string[] = [];
status:string[]=[];

isNsStatusDisabled: boolean = true;  

setNsStatusOptions() {

  if (this.domainsList.paymentStatus) {
    this.isNsStatusDisabled = false; 
  } else {
    this.isNsStatusDisabled = true;   
  }
}

cancelDomain(){
this.router.navigateByUrl('applications');
}

openPaymentDialog(): void {
  this.dialogRef = this.dialog.open(this.paymentDialog, {
    width: '500px',
  });
}

onFileSelected(event: Event): void {
  const input = event.target as HTMLInputElement;
  if (input.files && input.files.length > 0) {
    this.selectedFile = input.files[0];
    this.selectedFileName = input.files[0].name;
    //console.log(`File selected: ${this.selectedFile.name}`);
    this.fileType = this.selectedFile.type;
    this.fileName = this.selectedFileName;
  }
}


selectedDocFile = {
  fileName: '',
  fileSize: 0,
  organisationId: 0,
  file: null,
  contactType: 'Domain'
};
docFileName: string = '';
onDocFileSelected(event: any) {
  const file: File = event.target.files[0];
  //console.log("Selected file:", file);

  if (file) {

    const allowedTypes = ['image/jpeg', 'image/jpg', 'application/pdf'];

    if (!allowedTypes.includes(file.type)) {
      this.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();
}
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 = '';


// clickedDocument(file: File) {
//   this.tempimageUrl = '';  // Reset image preview
//   this.temppdfUrl = '';  // Reset PDF preview

//   const fileType = file.type;

//   // Set file name for preview
//   this.previewDocName = file.name;

//   const reader = new FileReader();
//   reader.onload = (e) => {
//     if (fileType === 'application/pdf') {
//       // Handle PDF
//       this.temppdfUrl = this.sanitizer.bypassSecurityTrustResourceUrl(e.target?.result as string);
//       //console.log('PDF URL:', this.temppdfUrl); 
//     } else if (fileType === 'image/png' || fileType === 'image/jpeg' || fileType === 'image/jpg') {
//       // Handle image
//       this.tempimageUrl = this.sanitizer.bypassSecurityTrustResourceUrl(e.target?.result as string);
//     };

//     reader.readAsDataURL(file);
//   }
  
// }
// previewDocument(){
//   $('#updateModal').modal('hide');
//   $('#viewPaymentReceipt').modal('show');
  
// }
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;
 

 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) => {
        
  //       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;
      }
    );
   
  
  }
  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) => {
        //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.domainsList.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
      }
    );
}
docName:string=''
docDisplayName:string='';
async reuploadOrgDocs(documentType){


  if(documentType === 'Domain Board Approval'){
    this.docName=documentType
    document.getElementById("reuploadModel").click();
  }else{
      this.docName=documentType
      document.getElementById("reuploadModel").click();
      this.organizationsList.documentPreviewCompleted = false;
      await this.updateOrganizationDocStatus();
  }
 
}

boardDocName:string=''
BoardDocDisplayName:string='';
async reuploadBoardDoc(documentType){
  this.boardDocName=documentType
  document.getElementById("reuploadModel").click();
}

boardApprovalDocName: string = '';
BoardApprovalDocDisplayName: string = '';
async reUploadBoardApprovalDoc(documentType){
  this.boardApprovalDocName=documentType
  document.getElementById("reuploadModel").click();
}



domainsListOfOrg: any;
async getAllDomainsByOrganisationId(organisationId: number) {
  await lastValueFrom(this.domainService.getAllDomainsByOrgId(organisationId)).then((response) => {
    if (response.status === HttpStatusCode.Ok) {
      this.domainsListOfOrg = response.body;
      //console.log(this.domainsListOfOrg);
    }
  })
}

async updateAllUnApproveDomainsStatusesToSubmittedForAnOrganisation(organisationId: number) {
  await this.getAllDomainsByOrganisationId(organisationId);
  this.domainsListOfOrg.forEach((domain) => {
    if(domain.applicationStatus !== this.assetService.Approved) {
        domain.applicationStatus = this.assetService.Submitted;
      this.updateDomainApplicationStatusWhenDocumentReupload(domain);
    }
  });
  this.toastrService.success("All domains updated to Submitted status");
}

async updateDomainApplicationStatusWhenDocumentReupload(domain){
  await lastValueFrom(this.domainService.updateDomainDetails(domain)).then((response) => {
    //if (response.status === HttpStatusCode.Ok) {
      //console.log(response.body);
    //} 
  })
}

@ViewChild('filesInput') fileInput!: ElementRef;

  triggerFileInput() {
    this.fileInput.nativeElement.click();
  }
  organisationDocErrors:string=''
  organisationInputValue:any='';
  UploadedDocuments:any;
  uploadSuccessMessage: string = '';
  handleFileInput(event: any) {
    const selectedFile = event.target.files[0];
    const maxFileSize = this.maxFileSizeInMB * 1024 * 1024;  // Convert MB to bytes
    if (this.orgDocNames.includes(selectedFile.name)) {
      this.organisationDocErrors = "Selected file already exists";
      return
    }
    if (selectedFile.size > maxFileSize) {
      this.organisationDocErrors =`Select a file less than ${this.maxFileSizeInMB}MB.`;
      return;
    }
    const validFileTypes = ['application/pdf', 'image/jpeg', 'image/jpg'];
    if (!validFileTypes.includes(selectedFile.type)) {
      this.organisationDocErrors = 'Invalid file type. Only PDF, JPG, and JPEG are allowed'
      // input.value = ''; // Reset the file input field
      return;
    }
    const uploadedDoc = {
      type: selectedFile,
      fileName: selectedFile.name,
      fileSize: selectedFile.size, // Optional for extra checks
      value: this.organisationInputValue || null,
      organisationId: this.domainsList.organisationId,
      file: event.target.files[0],
      contactType: 'Organisation'
    };
    this.UploadedDocuments=uploadedDoc;
    this.organisationDocErrors=''
    this.uploadSuccessMessage = `${this.docName} - ${selectedFile.name}.`;
     this.organisationInputsFieldErrors=''
   
  }

  async uploadFile(file,docName){
    await lastValueFrom(this.documentService.updateOrgDocs(file,docName)).then(
      (response)=>{
        this.toastrService.success("Reuploaded document")
        this.UploadedDocuments = null;
        document.getElementById("closeUploadModal").click();
        //window.location.reload()
      },(error)=>{
         this.toastrService.error('Could not process your request at the moment, please try again later or contact registrar');
      }
    )
  }

  async uploadDomainBoardApprovalDocument(domainId: number, selectedFile: any): Promise<boolean> {
  try {
    const response = await lastValueFrom(this.userdomainService.uploadDomainBoardApprovalDocument(domainId, selectedFile));
    if (response) {
      this.toastrService.success("Document uploaded.");
      this.UploadedDocuments = null;
      document.getElementById("closeUploadModal")?.click();
      return true;
    }
    return false;
  } catch (error) {
    this.toastrService.error(
      'Could not process your request at the moment, please try again later or contact registrar'
    );
    return false;
  }
}

  // reUploadDocument(file){
  //   if(file!=null){
  //     this.uploadFile(file,this.docName);
  //   }else{
  //     //console.log("file not there")
  //   }
  //   this.UploadedDocuments=null;
  //   this.organisationInputValue='';

  // }
  organisationInputsFieldErrors:string='';
  async reUploadDocument(file: File | null) {
    // For "BOARD" document type, we only need to check if a file is uploaded
    if (this.docName === 'BOARD' || this.docName === 'Domain Board Approval') {
      if (!file) {
        this.organisationInputsFieldErrors = 'Please upload a document.';
        return;  // Stop further execution if file is missing
      }
    } else {
      // For non-BOARD documents, check both input field and file
      if (!this.organisationInputValue) {
        this.organisationInputFieldErrors = `Please enter ${this.docName} number.`;
        return;  // Stop further execution if input is missing
      }
      if (!file) {
        this.organisationInputsFieldErrors = 'Please upload a document.';
        return;  // Stop further execution if file is missing
      }
    }
  //console.log(this.organisationInputFieldErrors,this.organisationInputsFieldErrors=='')
    // If input and file are valid, proceed with the upload
    if((this.organisationInputFieldErrors==''||this.organisationInputFieldErrors==undefined)&&this.organisationInputsFieldErrors==''){

   if(this.docName != 'Domain Board Approval'){
    await this.uploadFile(file, this.docName);
    await this.getOrgDocuments(this.domainsList.organisationId);
   }else{
    await this.uploadDomainBoardApprovalDocument(this.domainsList.domainId, file);
    this.getDomainDetails(this.domainsList.domainId);
   }

  //check status of all docs of an org
  // console.log("org status",this.orgGstStatus,this.orgPanStatus,
  //   this.orgBoardStatus,this.orgLicenceStatus,this.adminStatus,
  //   this.technicalOfficerStatus,this.billingOfficerStatus)
  if((this.orgGstStatus === 'Approved' || this.orgGstStatus === 'Not Reviewed' 
    || this.orgGstStatus === null || this.orgGstStatus === '')
  && (this.orgPanStatus === 'Approved' || this.orgPanStatus === 'Not Reviewed' 
    || this.orgPanStatus === null || this.orgPanStatus === '')
  && (this.orgBoardStatus === 'Approved' || this.orgBoardStatus === 'Not Reviewed' 
    || this.orgBoardStatus === null || this.orgBoardStatus === '')
  && (this.orgLicenceStatus === 'Approved' || this.orgLicenceStatus === 'Not Reviewed' 
    || this.orgLicenceStatus === null || this.orgLicenceStatus === '') 
  && (this.adminStatus === 'Approved' || this.adminStatus === 'Not Reviewed' 
    || this.adminStatus === null || this.adminStatus === '')
  && (this.technicalOfficerStatus === 'Approved' || this.technicalOfficerStatus === 'Not Reviewed' 
    || this.technicalOfficerStatus === null || this.technicalOfficerStatus === '')
  && (this.billingOfficerStatus === 'Approved' || this.billingOfficerStatus === 'Not Reviewed' 
    || this.billingOfficerStatus === null || this.billingOfficerStatus === '')) {
   
     this.updateAllUnApproveDomainsStatusesToSubmittedForAnOrganisation(this.domainsList.organisationId); 
   
}
    }
  
    // Reset the uploaded documents and input value after upload attempt
      // Reset uploaded document list (if you have a variable like this)


    
    
  }

  async updateOrganizationDocStatus(){
    //console.log(this.organizationsList)
    this.organizationsList.documentPreviewCompleted = false;
    await lastValueFrom(this.orgService.updateOrganisationDetails(this.organizationsList)).then(
      response => {
        if (response.status === HttpStatusCode.Ok) {
          //this.toastrService.success('Organisation documents updated successfully.');
          this.getOrgDocuments(this.domainsList.organisationId);
        } else {
          //this.toastrService.error('Error updating organisation documents.');
        }
      }
    )

  }
  
  
  
  organisationInputFieldErrors
  handleOrganisationInputChange(event: any): void {
    let inputValue = event.target.value; // Get the actual input value
    inputValue = inputValue.toUpperCase();
    event.target.value = inputValue; 
    
    // Clear the error if the input is empty
    if (!inputValue) {
      this.organisationInputFieldErrors = ''; // Clear any previous errors when input is cleared
      this.buttonDisabled = true;  // Optionally, disable button when input is empty
      return;
    }
  
    if (/^[a-zA-Z0-9\s]*$/.test(inputValue)) { // Test against allowed characters first
      this.organisationInputValue = inputValue;
      this.organisationInputFieldErrors = ''; // Clear any previous errors
  
      switch (this.docName) {  // Use a switch for cleaner logic
        case 'PAN':
          // Validate only the length (10 characters)
          if (inputValue.length !== 10) {
            this.organisationInputFieldErrors = 'PAN must be exactly 10 characters.';
            this.buttonDisabled = true;
          } else if (!/^[A-Z0-9]{10}$/.test(inputValue)){
            this.organisationInputFieldErrors = 'PAN must only contain uppercase letters and numbers.'; // Clear any error if the length is valid
            this.buttonDisabled = true;
          }else{
            this.buttonDisabled = false;
          }
          break;
        
  
          case 'GST':
            // Validate the length (exactly 15 characters) and allowed characters (uppercase and numbers only)
            if (inputValue.length !== 15) {
              this.organisationInputFieldErrors = 'GSTIN must be exactly 15 characters.';
              this.buttonDisabled = true;
            } else if (!/^[A-Z0-9]{15}$/.test(inputValue)) {
              this.organisationInputFieldErrors = 'GSTIN must only contain uppercase letters and numbers.';
              this.buttonDisabled = true;
            } else {
              this.buttonDisabled = false;
            }
            break;
            case 'LICENCE':
              // Validate only the length (21 characters)
            const trimmedInputValue = inputValue.trim();

  if (trimmedInputValue.length === 0) {
    this.organisationInputFieldErrors = 'LICENCE Number cannot be empty or only spaces.';
    this.buttonDisabled = true;
  } else if (trimmedInputValue.length > 20) {
    this.organisationInputFieldErrors = 'LICENCE Number must be less than or equal to 20 characters.';
    this.buttonDisabled = true;
  }
  // Uncomment and adjust the following block if you need to restrict characters
  /*
  else if (!/^[A-Z0-9!@#$%^&*()_+\-=\[\]{};':"\\|,.<>/?]+$/.test(trimmedInputValue)) {
    this.organisationInputFieldErrors = 'LICENCE Number contains invalid characters.';
    this.buttonDisabled = true;
  }
  */
  else {
    // If all checks pass, clear any errors and enable the button
    this.organisationInputFieldErrors = '';
    this.buttonDisabled = false;
  }
  break;
  
        default: // Handle the default case (no specific validation) if needed
          break;
      }
    } else {
      //this.organisationInputFieldErrors = 'Invalid characters entered.'; // More general error message
      this.buttonDisabled = true;
    }
  }
  
  getMaxLength(docName: string): number {
    switch (docName) {
      case 'GST':
        return 15; // GST number should have 15 characters
      case 'PAN':
        return 10; // PAN number should have 10 characters
      case 'LICENCE':
        return 20; // Licence number should have 21 characters
      default:
        return 0; // Default case, no maximum length
    }
  }
  
  buttonDisabled=false;
  adminStatus;
  technicalOfficerStatus;
  billingOfficerStatus;
  clearTheinpuErrors(){
    this.organisationInputValue=''
    this.organisationInputFieldErrors=''
   this.organisationInputsFieldErrors=''
    this.buttonDisabled=false;
    this.uploadSuccessMessage=''
    this.organisationDocErrors=''

  }
  contactDetails
  getContactOfficerDocuments(organisationId: number): void {
    this.contactDetailsService.getContactOfficersDetails(organisationId)
    .subscribe({
      next: (response) => {
        if (response.status === HttpStatusCode.Ok) {
          //console.log(response)
        // const allStatus= response.body[0].split(",")
        //  this.adminStatus=allStatus[0];
        //  this.technicalOfficerStatus=allStatus[1];
        //  this.billingOfficerStatus=allStatus[2];
        this.createContactRoleEmailMap(response.body);
          //console.log(this.contactRoleEmailMap)
          this.contactDocumentsService.getDocStatusOfOfficers(organisationId,this.contactRoleEmailMap)
          .subscribe({
            next:(response)=>{
              const allStatus= response[0].split(",")
         this.adminStatus=allStatus[0];
         this.technicalOfficerStatus=allStatus[1];
         this.billingOfficerStatus=allStatus[2];
              
               
            }
          })
         this.isLoadingData=false;
        
        }
      },
      error: (error) => {
        this.isLoadingData=false
        if (error.status === HttpStatusCode.Unauthorized) {
          // Your logic for Unauthorized error here
        }
      }
    });
}
contactRoleEmailMap = new Map<string, string>();
createContactRoleEmailMap(contactDetailsList) {
   this.contactRoleEmailMap.clear(); // Clear the map before populating it
  // in this  contactDetailsList take only the first administrative officer, technical officer and billing officer
  // Only keep the first occurrence of each officer role: Administrative Officer, Technical Officer, Billing Officer
  const rolesToKeep = ["Administrative Officer", "Technical Officer", "Billing Officer"];
  const seenRoles = new Set<string>();
  contactDetailsList = contactDetailsList.filter((contactDetail) => {
    if (
      contactDetail &&
      rolesToKeep.includes(contactDetail.contactRole) &&
      !seenRoles.has(contactDetail.contactRole)
    ) {
      seenRoles.add(contactDetail.contactRole);
      return true;
    }
    return false;
  });

  if (contactDetailsList && Array.isArray(contactDetailsList)) {
    contactDetailsList.forEach((contactDetail) => {
      if (contactDetail && (contactDetail.isActive === true || contactDetail.isActive === null)) {
        if (contactDetail.contactRole && contactDetail.emailId) {
          this.contactRoleEmailMap.set(contactDetail.contactRole, contactDetail.emailId);
        }
      }
    });
  }

 
}

BoardApprovalDocImage:boolean;
BoardDocImage:boolean;
OrgGstDocImage:boolean;
OrgLicenceImage:boolean;
OrgPanImage:boolean;
modalTitle:string='';
  viewDocuments(docType){
    this.modalTitle=docType
    if(docType=='GSTIN'){
      this.gstDoc = this.extractDocument(this.entireOrgDocsObj, 'organisationGstinDocument');
      if (this.gstDoc?.size > 0 && this.gstDoc?.get('fileName').endsWith('.pdf')) {
        this.displayPdf(this.gstDoc.get('document'), "organisationGstinDocument"); 
        this.OrgGstDocImage=false
        document.getElementById("gstModal")?.click();
      } else if (this.gstDoc.size > 0) { 
        this.OrgGstDocImage=true
        this.gstDoc = this.extractDocumentImage(this.entireOrgDocsObj, 'organisationGstinDocument'); 
        document.getElementById("gstModal")?.click();
      }
     
    }else if(docType=='PAN'){
      this.panDoc = this.extractDocument(this.entireOrgDocsObj, 'panDocument');
       
      if (this.panDoc?.size > 0 && this.panDoc?.get('fileName').endsWith('.pdf')) {
        this.displayPdf(this.panDoc.get('document'), "panDocument"); // Corrected documentField
        this.OrgPanImage=false;
        document.getElementById("panModal")?.click();
      } else if (this.panDoc.size > 0) { 
        this.panDoc = this.extractDocumentImage(this.entireOrgDocsObj, 'panDocument');
        this.OrgPanImage=true;
        document.getElementById("panModal")?.click(); 
      }
    }else if(docType=='LICENCE'){
      this.licenseDoc = this.extractDocument(this.entireOrgDocsObj, 'licenseDocument');
      if (this.licenseDoc?.size > 0 && this.licenseDoc?.get('fileName').endsWith('.pdf')) {
        this.displayPdf(this.licenseDoc.get("document"), "licenseDocument"); // Corrected documentField
        this.OrgLicenceImage=false;
        document.getElementById("licenceModal")?.click(); 
      } else if (this.licenseDoc.size > 0) { 
        this.licenseDoc = this.extractDocumentImage(this.entireOrgDocsObj, 'licenseDocument'); 
        this.OrgLicenceImage=true;
        document.getElementById("licenceModal")?.click(); 
      }
    } else if (docType == 'Domain Board Approval') {
      //console.log("entered the board approval doc")
      this.boardApprovalDoc = this.extractBoardDocument(this.domainsList?.twoLetterDomainDocumentProof,
        this.domainsList?.twoLetterDomainDocumentFileName);
        if(this.boardApprovalDoc?.size > 0 && this.boardApprovalDoc?.get('fileName').endsWith('.pdf')) {
          this.displayPdf(this.boardApprovalDoc.get("document"), "boardApprovalDocument"); // Corrected documentField
          this.BoardApprovalDocImage=false;
          document.getElementById("boardApprovalModal")?.click(); 
        } else if (this.boardApprovalDoc.size > 0) { 
          this.BoardApprovalDocImage=true;
          this.boardApprovalDoc = this.boardApprovalDoc.get('document'); 
          document.getElementById("boardApprovalModal")?.click(); 
        }
    }
    else{
      this.boardResolutionDoc = this.extractDocument(this.entireOrgDocsObj, 'boardResolutionDocument');
      if (this.boardResolutionDoc?.size > 0 && this.boardResolutionDoc.get('fileName').endsWith('.pdf')) {
        this.displayPdf(this.boardResolutionDoc.get("document"), "boardResolutionDocument"); // Corrected documentField
        this.BoardDocImage=false;
        document.getElementById("boardModal")?.click(); 
      } else if (this.boardResolutionDoc.size > 0) { 
        //console.log("entered the else")
        this.BoardDocImage=true;
        this.boardResolutionDoc = this.extractDocumentImage(this.entireOrgDocsObj, 'boardResolutionDocument'); 
        document.getElementById("boardModal")?.click(); 
      }
    }
  }

  private extractDocument(orgDocs: any, documentField: string): Map<string, any> {
    //console.log(documentField)
    const foundDoc = orgDocs.find(doc => !!doc[documentField]);
  
    if (foundDoc) {
      return new Map([
        ['fileName', foundDoc.fileName], 
        ['document', foundDoc[documentField]]
      ]);
    } else {
      return new Map(); 
    }
  }

  private extractBoardDocument(boardDocument: any, fileName: string): Map<string, any> {
    //console.log(documentField)
    if (boardDocument && fileName) {
      return new Map([
        ['fileName', fileName], 
        ['document', boardDocument]
      ]);
    } else {
      return new Map(); 
    }
  }

  private extractDocumentImage(orgDocs: any, documentField: string): any {
    const foundDoc = orgDocs.find(doc => !!doc[documentField]);
  
    if (foundDoc) {
      return foundDoc[documentField]; 
    } else {
      return null; 
    }
  }
  displayPdf(binaryData,docName) {
    if (typeof binaryData === 'string') { 
      // If data is a Base64 string
      const binaryString = atob(binaryData); 
      const len = binaryString.length;
      const bytes = new Uint8Array(len);
      for (let i = 0; i < len; i++) {
        bytes[i] = binaryString.charCodeAt(i);
      }
      const blob = new Blob([bytes], { type: 'application/pdf' });
      
      // const arrayBuffer = new Uint8Array(binaryData);
    
      if(docName=="organisationGstinDocument"){
       // const blob = new Blob([arrayBuffer], { type: 'application/pdf' });
       const pdfUrl = URL.createObjectURL(blob);
        this.gstDocPdf = this.sanitizer.bypassSecurityTrustResourceUrl(pdfUrl); 
      }
      if(docName=="panDocument"){
        const pdfUrl = URL.createObjectURL(blob);
        this.panDocPdf = this.sanitizer.bypassSecurityTrustResourceUrl(pdfUrl); 
      }
      if(docName=="licenseDocument"){
        const pdfUrl = URL.createObjectURL(blob);
        this.licenceDocPdf = this.sanitizer.bypassSecurityTrustResourceUrl(pdfUrl); 
      }
      if(docName=="boardResolutionDocument"){
        const pdfUrl = URL.createObjectURL(blob);
        this.boardResolutionDocPdf = this.sanitizer.bypassSecurityTrustResourceUrl(pdfUrl); 
      }
      if(docName=="boardApprovalDocument"){
        const pdfUrl = URL.createObjectURL(blob);
        this.boardApprovalDocPdf = this.sanitizer.bypassSecurityTrustResourceUrl(pdfUrl); 
      }
  } 
  }

  cityOptions: Array<{ name: string; district: string; state: string }> = [];
loading = false;
pincodeError: string = ''; 
fetchCityState(pincode: string): void {
  this.loading = true;
  this.pincodeError = ''; // Clear the error at the beginning of each validation

  // Check if the input pincode is empty
  if (pincode === '') {
    this.clearCityAndState();
    this.pincodeError = 'Pincode is required.'; // Show 'pincode required' message
    this.loading = false;
    return;
  }

  // Check if the pincode is not exactly 6 digits
  if (!/^\d{6}$/.test(pincode)) {
    this.pincodeError = 'Pincode must be exactly 6 digits.'; // Show pattern error
    this.clearCityAndState();
    this.loading = false;
    return;
  }

  // Proceed with API call if pincode is valid
  if (pincode !== '160034') {
    this.organizationDetailsService.getPinCodeData(pincode).subscribe(
      (response: any) => {
        this.loading = false;

        if (response.body.length>0) {
          const places = response.body;

          this.cityOptions = places.map((place: any) => ({
            name: place.city + ', ' + place.district,
            district: place.district,
            state: place.state,
        }));

          if (this.cityOptions.length > 0) {
            this.organizationsList.city = this.cityOptions[0].name || '';
            this.organizationsList.state = this.cityOptions[0].state || '';
            this.organizationsList.district = this.cityOptions[0].district || '';
            this.enableCityDropdown();
          } else {
            this.clearCityAndState();
          
          }
        } else {
          this.clearCityAndState();
          this.pincodeError = 'Invalid pincode.';
        }
      },
      (error) => {
        this.loading = false;
        this.clearCityAndState();
        this.pincodeError = 'Error fetching data. Please try again later.';
      }
    );
  } else if (pincode === "160034") {
    // Hardcoded case for pincode 160034 (Chandigarh)
    this.cityOptions = [{ name: 'Chandigarh', district: 'Chandigarh', state: 'Chandigarh' }];
    this.organizationsList.city = this.cityOptions[0].name || '';
    this.organizationsList.state = this.cityOptions[0].state || '';
    this.organizationsList.district = this.cityOptions[0].district || '';
    this.pincodeError = ''; // No error message for this hardcoded case
  }
}
StdCodes;
stdCodesbasedOnState:any;
loadStdCodes(state: string): void {
  //console.log(this.StdCodes);
  this.stdCodesbasedOnState = this.StdCodes?.filter(item => item.state === state);
}

enableCityDropdown(): void {
  // Enable city form control programmatically
  this.loadStdCodes(this.organizationsList.state); // Assuming you want to load stdCodes based on state
}

clearCityAndState(): void {
  this.cityOptions = [];
  this.organizationsList.city = '';
  this.organizationsList.state = '';
  this.organizationsList.district = '';
  this.stdCodesbasedOnState = null;
}
styleCityAndState:boolean=false;

onPincodeChange(): void {
  const pincode = this.organizationsList.pincode; // Directly access pincode

  // Validate if the pincode is a valid 6-digit number
  if (pincode && /^\d{6}$/.test(pincode)) {
    this.styleCityAndState = false; // Hide error style
    this.fetchCityState(pincode);
    
  } else {
    this.styleCityAndState = true; // Show error style
    this.clearCityAndState(); // Clear city and state dropdowns
    this.pincodeError = pincode ? 'Pincode must be exactly 6 digits.' : 'Pincode is required.'; // Show respective error message
  }
}


 getStatusColor(status: string): string {
    switch (status) {
      case this.assetService.Approved:
        return '#00CC00'; // Green
      case this.assetService.Submitted:
        return '#FF6A18'; // Orange
      case this.assetService.Incomplete:
        return '#FF0000';
        case this.assetService.Rejected:
        return '#FF0000'; 
         case this.assetService.Resubmitted:
        return '#17a2b8';
      default:
        return 'black'; // Default text color
    }
  }

preventConsecutiveSpacesAndSpecialChar(event: Event, address: any): void {
  const inputElement = event.target as HTMLInputElement;
  const value = inputElement.value;

  // Prevent leading spaces (if space is the first character)
  if (value.startsWith(' ')) {
    inputElement.value = value.trim();  // Remove leading spaces if any
    return; // Prevent the space
  }

  // Prevent consecutive spaces (if space is typed after a space)
  if (value[value.length - 1] === ' ' && value[value.length - 2] === ' ') {
    inputElement.value = value.trim();  // Trim extra spaces if any
    return; // Prevent consecutive spaces
  }

  // Block special characters at the first position (if input is empty)
  if (/^[^a-zA-Z0-9]/.test(value)) {
    inputElement.value = value.replace(/^[^a-zA-Z0-9]/, '');  // Remove special character at the start
  }

  // Check for special character at the start of the input and set error accordingly
  if (/^[^a-zA-Z0-9]/.test(value)) {
    address.control.setErrors({ startWithSpecialChar: true });
  } else {
    address.control.setErrors(null); // Clear error if the value is valid
  }
}


preventInvalidInput(event: KeyboardEvent): void {
  const key = event.key; // Get the key that is being pressed
  const inputElement = event.target as HTMLInputElement; // This variable is not strictly needed in the final version but kept for context.

  // Allow Backspace key to delete characters universally
  if (key === 'Backspace') {
    return; // Allow Backspace to delete characters
  }

  //console.log(this.docName); // Keep this for debugging if needed

  // Handle input based on docName
  if (this.docName === 'LICENCE') {
    // For LICENCE, we explicitly allow all characters including spaces.
    // Since Backspace is handled above, and we want to allow everything else,
    // no further prevention is needed here.
    return;
  } else {
    // For other docNames:
    // Prevent space keypress
    if (key === ' ') {
      event.preventDefault(); // Block space keypress
      return; // Stop further processing for space
    }

    // Allow only letters and numbers (no special characters)
    // This regex tests if the *single key pressed* is an alphanumeric character.
    if (!/^[a-zA-Z0-9]$/.test(key)) {
      event.preventDefault(); // Block non-alphanumeric characters
    }
  }


  // if(this.docName === 'LICENCE'){

  // }
  // // Prevent any key that is not alphanumeric (letters or numbers) or spaces
  // if (!/^[a-zA-Z0-9]$/.test(key)) {
  //   event.preventDefault(); // Block any key that is not allowed
  // }
}
getUniqueDistricts(): string[] {
  return Array.from(new Set(this.cityOptions.map(city => city.district)));
}

@ViewChild('domainModal') domainModal!: ElementRef;
isDomainAvailable: boolean = false;
chosenDomainName: string = '';
chnageInDomainName: boolean = false;
async onKeyupDomainName(){
  if(this.domainNameError){
    
    this.toastrService.error(this.domainNameError);
    // document.getElementById("closeDomainName")?.click();
    //     const modalInstance = Modal.getInstance(this.domainModal.nativeElement);
    //     modalInstance?.show(); // ✅ Close the modal properly
    //  const modal = new Modal(this.domainModal.nativeElement);
    // modal.hide();
    return;
  }else{
      const modal = new Modal(this.domainModal.nativeElement);
    modal.show();
  }
  
  //console.log(this.chosenDomainName)
  //console.log(this.domainsList.bankName)
  if(this.chosenDomainName === this.domainsList.bankName) {
    //console.log("Domain name hasn't changed, skipping availability check.");
    this.isDomainAvailable = true;
    this.chnageInDomainName = false;
    return; // No need to check if the domain name hasn't changed
  }
    const alreadyPresent = await this.getAliasByAliasName(this.chosenDomainName);

    if(alreadyPresent){
      this.isDomainAvailable = false;
      return
    }
    this.chnageInDomainName = true;
  //console.log("Domain name has changed, checking availability.");
  // Check if the domain name is available
  // this.isDomainAvailable = 
 await lastValueFrom(this.userdomainService.checkDomainCombination(this.chosenDomainName, 
    this.domainsList.domainName,"",""))
    .then((response) => {
      //console.log(response)
      this.isDomainAvailable = response;
    });
   
}
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
  }
}
setDomainName(){
  //console.log(this.domainsList.bankName)
  this.chosenDomainName = this.domainsList.bankName;
  this.selectedTenure = this.domainsList.numberOfYears;
  //console.log(this.chosenDomainName)
}


  async updateDomainNameAndTenure() {

    this.domainsList.bankName = this.chosenDomainName;
    //console.log((this.domainsList.bankName.length))
    if (this.chnageInDomainName) {
      //if domain name lenght === 2 and if file is null dont allow to save
      if (this.domainsList.bankName.length === 2) {
        if (this.selectedDocFile.file === null || this.selectedDocFile.file === undefined) {
          this.toastrService.error('Please upload the Board Approval Document for 2-letter domain names.');
          return;
        } else {
          //if domain name length is 2 and file is uploaded, save the domain with file and name
          //calling update domain name method to update the domain name
         // this.domainsList.twoLetterDomainDocumentProof = this.selectedDocFile;
         // this.domainsList.twoLetterDomainDocumentFileName = this.docFileName;
         // this.domainsList.twoLetterDomainDocumentApprovalStatus = null;
         this.UploadedDocuments = this.selectedDocFile;
          const isUploaded = await this.uploadDomainBoardApprovalDocument(this.domainsList.domainId,this.UploadedDocuments).then();
          if(isUploaded){
            //console.log('uplaoded')
            await this.getDomainApplicationDetails(this.domainsList.domainId);
            //console.log(this.domainsList)
            this.domainsList.bankName = this.chosenDomainName;
            await this.updateDomainName(this.domainsList);
            //old tenure
            this.domainsList.oldTenure = this.domainsList.numberOfYears;
            //new tenure
            this.domainsList.numberOfYears = this.selectedTenure;
            //calling update tenure method to update the tenure
            await this.updateTenure(this.domainsList.domainId, this.domainsList.oldTenure, this.domainsList.numberOfYears);
          }
        }
         //if domain name lenght > 2  allow to save directly without file bcz , file is not required
      } else {
        await this.getDomainApplicationDetails(this.domainsList.domainId);
        this.domainsList.bankName = this.chosenDomainName;
        await this.updateDomainName(this.domainsList);
          //old tenure
          this.domainsList.oldTenure = this.domainsList.numberOfYears;
          //new tenure
          this.domainsList.numberOfYears = this.selectedTenure;
          //calling update tenure method to update the tenure
          await this.updateTenure(this.domainsList.domainId, this.domainsList.oldTenure, this.domainsList.numberOfYears);
      }
      //if no changes in domain Name still allow to just update with no changes.
    } else {
      //calling update domain name method to update the domain name
      await this.getDomainApplicationDetails(this.domainsList.domainId);
      await this.updateDomainName(this.domainsList);
      //old tenure
      this.domainsList.oldTenure = this.domainsList.numberOfYears;
      //new tenure
      this.domainsList.numberOfYears = this.selectedTenure;
      //calling update tenure method to update the tenure
      await this.updateTenure(this.domainsList.domainId, this.domainsList.oldTenure, this.domainsList.numberOfYears);
    }


  }

async updateDomainName(domain: any){
   await lastValueFrom(this.domainService.updateDomainDetails(domain)).then(
    response => {
      if (response.status === HttpStatusCode.Ok) {
        //this.toastrService.success('Domain name updated successfully.');
        this.isEditing = false; // Set isEditing to true to hide the input field
        document.getElementById("closeDomainName")?.click();
        //  const modalInstance = Modal.getInstance(this.domainModal.nativeElement);
        // modalInstance?.hide(); // ✅ Close the modal properly
        this.getDomainDetails(this.domainsList.domainId);
        this
      } else {
         this.toastrService.error('Could not process your request at the moment, please try again later or contact registrar');
      }
    });
}

async updateTenure(domainId: number, oldTenure: number, newTenure: number) {
  //console.log("tenure is called")
  await lastValueFrom(this.domainService.updateTenure(domainId, oldTenure, newTenure)).then(
    response => {
      if (response.status === HttpStatusCode.Ok) {
        this.toastrService.success('Domain updated successfully.');
        this.getDomainDetails(domainId);
      } else {
         this.toastrService.error('Could not process your request at the moment, please try again later or contact registrar');
      }
    }
  );
}

async updateDomainApplicationStatus(){
  //if(this.domainsList.paymentStatus === 'Payment Completed') {
    this.domainsList.applicationStatus = this.assetService.Submitted;
  //}
  await lastValueFrom(this.domainService.updateDomainDetails(this.domainsList)).then(
    response => {
      if (response.status === HttpStatusCode.Ok) {
        this.toastrService.success('Domain application status updated successfully.');
        this.getDomainDetails(this.domainsList.domainId);
      } else {
         this.toastrService.error('Could not process your request at the moment, please try again later or contact registrar');
      }
    });
}

async reSubmitApplication(){
  if(this.selectedTenure!=null&&this.selectedTenure!=0){
    this.domainsList.numberOfYears=this.selectedTenure;
  }
   this.updateDomainApplicationStatus();
  //  this.updateOrgDetails();
}


domainNameError: string = '';

validateDomainName(): boolean {
  // Clear previous error
  this.domainNameError = '';

  // Required check
  if (!this.chosenDomainName || this.chosenDomainName.trim() === '') {
    this.domainNameError = 'Domain name is required.';
    return false;
  }

  // Min length check
  if (this.chosenDomainName.length < 2) {
    this.domainNameError = 'Domain name must be at least 2 characters.';
    return false;
  }

  // Max length check
  if (this.chosenDomainName.length > this.domainMaxLength) {
    this.domainNameError = 'Domain name must not exceed '+this.domainMaxLength +' characters.';
    return false;
  }

  // Pattern check
  const pattern = /^[a-z]+([a-z0-9-]*[a-z0-9])?$/;
  if (!pattern.test(this.chosenDomainName)) {
    this.domainNameError = 'Domain name must start with a lowercase letter, can include digits or hyphens, and cannot end with a hyphen.';
    return false;
  }

  return true;
}

tenures: number[] = Array.from({ length: 10 }, (_, i) => i + 1);
selectedTenure: number = 1;
domainMaxLength:number = 0;
getMaxDomainLength() {
  this.userdomainService.getDomainMaxLength('domainMaxLength').subscribe({
    next: (response) => {
      // this.userDomainForm.get('zone')?.setValidators([Validators.required, Validators.maxLength(response[0].value)]);
       const resp = response;
      resp.forEach((element: any) => {
        if (element.type === 'domainMaxLength') {
          this.domainMaxLength = element.value;
        }
      });
    },
    error: (error) => {
      if (error.status === HttpStatusCode.Unauthorized) {
        this.router.navigateByUrl('/session-timeout')
      }
    }
  });
}
regExp: string = '';
getRegularExpressionForEmail() {
  // Assuming 'this.assetService' is where getEmailReqExp is defined
  this.registrationService.getEmailReqExp('email').subscribe({
    next: (response: string) => { // 👈 Make sure to expect a string here
      // 'response' is ALREADY the extracted 'value' string from the map operator.
      const respo = response[0] as any;
      this.regExp = respo.value.trim(); // Trim any whitespace
      //console.log('Email regex fetched and assigned:', this.regExp);
    },
    error: (error) => {
      //console.error('Error fetching email regex:', error);
      // Handle the error, e.g., set a default value or clear regExp
      this.regExp = ''; // Or null, depending on your default state
    }
  });
}

emailCheck():boolean {
  //console.log(this.organizationsList.organisationEmail)
    //const emailPattern = /^[a-zA-Z][a-zA-Z0-9.]*@[a-zA-Z0-9.]+\.[a-zA-Z]{2,4}$/
    const emailPattern = new RegExp(this.regExp.trim());
    if (!this.organizationsList.organisationEmail) {
     return false
    } else if (!emailPattern.test(this.organizationsList.organisationEmail)) {
     return false
    } else {
      return true;
    }
  }

  convertToUpperCase(): void {
  if (this.organizationsList.institutionName) {
    this.organizationsList.institutionName = this.organizationsList.institutionName.toUpperCase();
  }
}
async updateDomainBasedOnisCoOperativeBank() {
    const result =await lastValueFrom(this.domainService.updateDomainBasedOnisCoOperativeBankWithInvoice(this.domainId));
      this.domain=result.body;
      // Log the successful result or perform further actions
      //console.log('Domain update successful:', result);

      // You might want to update UI state or show a success message here
      // this.showSuccessMessage('Domain updated successfully!');
      this.toastrService.success("Updated Successfully")

    } catch (error) {
      //console.log(error)
      this.toastrService.success("please try after some time")
      // Catch any errors that occur during the async operation.
      // 'error' could be an HttpErrorResponse, a generic Error, or any other thrown value.
      //console.error('Error updating domain:', error);

      // Provide user feedback, e.g., display an error message
      // this.showErrorMessage('Failed to update domain. Please try again.');

      // You might also want to re-throw the error if it needs to be handled further up the call stack
      // throw error;

    }

   usersOfOrg: any[] = [];
isOrgOnboarded: boolean = false;

async getAllUsersOfOrg(organisationId: number) {
  try {
    const response = await lastValueFrom(this.userService.getAllUsers(organisationId));
    if (response.status === HttpStatusCode.Ok) {
      this.usersOfOrg = response.body;

      // Check if any user has completed onboarding
      this.isOrgOnboarded = this.usersOfOrg.some(user => user.isOnboardingCompleted === true);

     // console.log('Users of Org:', this.usersOfOrg);
      console.log('Is Org Onboarded:', this.isOrgOnboarded);
    }
  } catch (error) {
    console.error('Error fetching users:', error);
    this.usersOfOrg = [];
    this.isOrgOnboarded = false;
  }
}


     async getUsersList(organisationId: number) {
      //console.log('Organisation ID:', organisationId);
      if (isNaN(organisationId) || organisationId <= 1) {
        //console.error('Invalid organisationId:', organisationId);
        return;
      }
      await lastValueFrom(this.userService.getAllUsers(organisationId)).then(
        (response) => {
          if (response.status === HttpStatusCode.Ok) {
            //console.log(response.body);
           // this.usersList = response.body;
            this.usersList = response.body.filter((user: any) => {
            // Check if userRoles exists and is an array
              if (!user.userRoles || !Array.isArray(user.userRoles)) {
                return false; // Skip if userRoles is missing or not an array
              }

              // Check if any of the user's roles is 'Super Admin'
              const hasSuperAdminRole = user.userRoles.some((role: any) => {
                return role.roleName === 'Super Admin';
              });

              // Check the deletion status
              const isNotDeleted = (user.isDeleted === false || user.isDeleted === null);

              return hasSuperAdminRole && isNotDeleted;
            });
          //console.log(this.usersList)
          }
        },
        (error) => {
          if (error.status === HttpStatusCode.Unauthorized) {
            // this.isLoadingData=false;
           this.router.navigateByUrl('/session-timeout')
          }
        }
      );
    }

 isUploadEnabled(): boolean {
  const status = this.domainsList?.paymentStatus;
  if (!status) {
    return false; // default disable if status is missing
  }
  return status === 'Payment Completed' 
  || status === 'Payment Rejected' 
  || status === 'Payment Under Review';
}

isEditAllowed(): boolean {
  const appStatus = this.domainsList?.applicationStatus;
  const payStatus = this.domainsList?.paymentStatus;

  return appStatus !== 'Approved' &&
         !['Payment Completed', 'Payment Under Review', 'Payment Approved'].includes(payStatus);
}

closeThePaymentUploadModal(){
  this.getDomainApplicationDetails(this.domainsList.domainId);
}

countryCodes:any
 async getAllCountryCodes(){
        this.organisationDetailsService.getAllCountryCodes().subscribe({
          next:(response)=>{
            this.countryCodes=response.body
            //console.log(this.countryCodes)
          }
        })
    }

    async updateCountryCode(event: Event): Promise<void> {
  // Get the selected value from the dropdown
  const selectedCode = (event.target as HTMLSelectElement).value;

  // Update your model with the selected country code
  this.organizationsList.countryCode = selectedCode;

  console.log(`Country Code updated to: ${selectedCode}`);

  // --- Optional Custom Logic ---
  // Find the full country object if needed
  const selectedCountry = this.countryCodes.find(
    (c) => c.countryCode === selectedCode
  );

  if (selectedCountry) {
    console.log('Selected Country Object:', selectedCountry);
  }

  await this.validateCountryAndMobile();

  // Example: Clear mobile number if country changes
  // this.organizationsList.mobileNumber = '';
}

countryCodeMobileCombinationError=''
async validateCountryAndMobile(): Promise<void> {
   try {
    const validMobileFormat = await lastValueFrom(
      this.organisationDetailsService.validateCodeAndNumber(
        this.organizationsList.countryCode,
        this.organizationsList.mobileNumber
      )
    );

    if (!validMobileFormat) {
      this.countryCodeMobileCombinationError =
        'Please enter a valid Country code or mobile number.';
    } else {
      this.countryCodeMobileCombinationError = '';
    }
  } catch(error) {
    console.log(error)
    if(error.error.errorCode === "PHONE_SERVICE_INVALID_PHONE_NUMBER_EXP_CODE-1018"){
        this.countryCodeMobileCombinationError =
        'Please enter a valid Country code or mobile number.';
    }else{
      this.countryCodeMobileCombinationError ='Please try again.';
    }
    
  }
}
  stdCodeAndTelephoneCombinationError=''
async validateStdAndTelephone(): Promise<void> {
  const stdCode = this.organizationsList.stdCode?.trim();
  const stdTelephone = this.organizationsList.stdTelephone?.trim();

  // Reset error first
  this.stdCodeAndTelephoneCombinationError = '';

  // Check for missing fields
  if (!stdCode || !stdTelephone) {
    this.stdCodeAndTelephoneCombinationError = 'Enter both STD code and telephone number';
    return;
  }

  // Check for telephone length
  if (stdTelephone.length < 5) {
    this.stdCodeAndTelephoneCombinationError = 'Please enter a valid telephone number';
    return;
  }

  // If all good, clear error
  this.stdCodeAndTelephoneCombinationError = '';
}
}

