import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { ContactDocumentUploadService } from '../contact-document-upload/service/contact-document-upload.service';
import { lastValueFrom } from 'rxjs';
import { HttpStatusCode } from '@angular/common/http';
import { ActivatedRoute, Router } from '@angular/router';
import { param } from 'jquery';
import { ToastrService } from 'ngx-toastr';
import { Location } from '@angular/common';
import { DomSanitizer } from '@angular/platform-browser';
import { ContactDetailsFormService } from '../contact-details-form/service/contact-details-form.service';
import { Roles } from '../model/roles.model';
import { RolesService } from '../roles/services/roles.service';
import { UserService } from '../user/service/user.service';
import { OrganisationDetailsComponent } from '../organisation-details/organisation-details.component';
import { OrganisationDetailsService } from '../organisation-details/service/organisation-details.service';
import { environment } from '../environments/environment';
import { DomainService } from '../rgnt-domain/service/domain.service';
import { AssetService } from '../asset.service';
import { DocumentUploadService } from '../document-upload/service/document-upload.service';

@Component({
    selector: 'app-verify-documents',
    templateUrl: './verify-documents.component.html',
    styleUrls: ['./verify-documents.component.css'],
    standalone: false
})
export class VerifyDocumentsComponent implements OnInit {

  documentsList: any[];
  documentsListDataSource: MatTableDataSource<any>;
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;
  role: string = localStorage.getItem('userRole');
  userEmailId = localStorage.getItem('email');
  searchText:String='';
  verifyEmailId:string
  organisationId: number = 0;
  modalTitle: string = '';

  displayedColumns: string[] = [];

  contactType: string = '';
  
  constructor(private contactDocumentsService: ContactDocumentUploadService,
     private documentService:DocumentUploadService,
    private router: Router, private activatedRouter: ActivatedRoute,
    private assetService: AssetService,
    private orgService: OrganisationDetailsService,
    private organizationService: OrganisationDetailsService,
    private toastr: ToastrService,
    private location: Location,
    private sanitizer:DomSanitizer,
    private contactDetailsService:ContactDetailsFormService,
    private roleService:RolesService,private userService:UserService,
    private domainService: DomainService
  ){
    this.documentsListDataSource = new MatTableDataSource<any>();
    // this.activatedRouter.queryParams.subscribe(param => {
        this.contactType = sessionStorage.getItem('contactType');
      this.organisationId = Number(sessionStorage.getItem('orgIdForDoc'))??0;
      this.verifyEmailId = sessionStorage.getItem('docEmail')??''
    // })
    
  }
  IDRBTADMIN=environment.IDRBTADMIN;
  isLoadingData:boolean=false;
  async ngOnInit(): Promise<void> {
      //console.log(this.contactType   )
      //console.log((sessionStorage.getItem('orgIdForDoc')))
      //console.log(this.verifyEmailId ) 
     await this.getDomainsListByOrganisationId(this.organisationId);
     await this.getOrgDocuments(this.organisationId);
     await this.getUsersList(this.organisationId);
     // ✅ Set flag to true if any domain has status "Domain Application Resubmitted"
        this.isDomainApplicationResubmitted = this.domainsList.some(
          domain => domain.applicationStatus === 'Incomplete' || domain.applicationStatus === 'Resubmitted'
        );
        //console.log(this.isDomainApplicationResubmitted);
    if(this.role === 'IDRBTADMIN'){
      this.displayedColumns = [
        // 'checkbox',
        'contactDocumentId',
        'fileName',
        'documentType',
        // 'approveOrReject',
        'documentStatus',
        'comment',
      ];
    }else{
     
      this.displayedColumns = [
        // 'checkbox',
        'contactDocumentId',
        'fileName',
        'documentType',
       // 'approveOrReject',
        'documentStatus',
        'comment',
        'reUpload'
      ];
    }
    this.getAllRoles();
    await this.getContactOfficerDocuments(this.contactType, this.organisationId,this.verifyEmailId);
    await this.getContactOfficersDetails(this.organisationId)
    await this.getOrganisationDetails(this.organisationId);
    // await this.get
    // await this.get
  }

  
  user = {
    id: 0,
    userName: '',
    userId: '',
    userRoles:[],
    active: false,
    encryptedPassword: '',
    mobileNumber: '',
    confirmPassword: '',
    createdByEmailId:'',
    organisationId:0,
    organisationDetails: {},
    isOnboardingCompleted: false,
    designation :''
  }

  navigateToSessionTimeout(){
    this.router.navigateByUrl('/session-timeout');
  }

  AllRoles:Roles[]
  getAllRoles(){
    this.roleService.getAllRoles().subscribe({
      next:(response)=>{
      this.AllRoles=response.body;
      ////console.log(this.AllRoles)
      },error:(error)=>{
        ////console.log(error)
      }
    })
  }
  contactDetailsList: any[] = [];
    async getContactOfficersDetails(selectedOrganisationId: number){
      await lastValueFrom(this.contactDetailsService.getContactOfficersDetails(selectedOrganisationId)).then(
        response => {
          if(response.status === HttpStatusCode.Ok){
            ////console.log(response.body);
            this.contactDetailsList = response.body;
           this.getDetailsOfSuperAdmin(selectedOrganisationId);
          }
        },error => {
          if(error.status === HttpStatusCode.Unauthorized){
            this.navigateToSessionTimeout();
          }
        }
      )
    }
     emailRoleMap = {}
     superAdminEmail='';
    getDetailsOfSuperAdmin(selectedOrganisationId){
      this.userService.getAllUsers(selectedOrganisationId).subscribe({
        next:(response)=>{
          ////console.log(response)
          

          this.contactDetailsList.forEach(item => {
            if (item.emailId) {
              if (this.emailRoleMap[item.emailId]) {
                this.emailRoleMap[item.emailId].push(item.contactRole);
              } else {
                this.emailRoleMap[item.emailId] = [item.contactRole];
              }
            }
          })
          response.body.forEach((user) => {
            const userId = user.userId;
            const roles = user.userRoles;
          
            if (roles && roles.some((role) => role.roleName === "Super Admin")) {
              if (this.emailRoleMap[userId]) {
                if (!this.emailRoleMap[userId].includes("Super Admin")) {
                  this.emailRoleMap[userId].push("Super Admin");
                  this.superAdminEmail=user.userId;
                  ////console.log(this.superAdminEmail)
                }
              } else {
                this.emailRoleMap[userId] = ["Super Admin"];
              }
            }
          });
         ////console.log(this.emailRoleMap)
        }
      })
    }
    docNames;
  contactRoleMap= new Map();
  async getContactOfficerDocuments(contactType: string, organisationId: number,email){
    //console.log(contactType,organisationId,email)
    this.isLoadingData=true;
    await lastValueFrom(this.contactDocumentsService.getContactOfficerDocumentsForAddUser(contactType,organisationId,email)).then(
      response => {
        if(response.status === HttpStatusCode.Ok){
          this.documentsList = response.body;
          //console.log(this.documentsList)
          this.docNames = this.documentsList.map(document => document.fileName);
        //   this.documentsList.forEach(document => {  // Iterate over documentsList
        //     ////console.log(document)
        //     this.contactRoleMap.set(document.documentType, document.documentStatus);
        // });
        ////console.log(this.contactRoleMap)
          this.documentsListDataSource.data = this.documentsList;
          setTimeout(() => {
            this.documentsListDataSource.sort = this.sort;
            this.documentsListDataSource.paginator = this.paginator;
          },0)
          this.isLoadingData=false;
          ////console.log(this.documentsList);
        }
      }, error => {
        this.isLoadingData=false;
        if(error.status === HttpStatusCode.Unauthorized){
          this.navigateToSessionTimeout();
        }
      }
    )
    return this.documentsList;
  }

  async enableOrDisableLoginStatus(loginStatus: string, contactOfficerDetails: any){
    ////console.log(contactOfficerDetails.id)
    //first update the login status of contact officer and then create the user login for the contact officer
    if(contactOfficerDetails.contactRole === 'Administrative Officer'){
      await this.getAdminOfficerDetails(contactOfficerDetails.id);
      //before updating status
      // await this.getContactOfficerDocuments("Administrative",this.adminOfficerDetails.organisationId);
      let count = 0;
      ////console.log('exe')
      ////console.log(this.documentsList)
      this.documentsList.forEach(doc => {
        if(doc.documentStatus === 'Approved'){
          count = count + 1;
          ////console.log(count)
        }else{
          count = count - 1;
          ////console.log(count)
        }
      });
      if(count === 2 && loginStatus === 'Approved'){
        this.adminOfficerDetails.loginStatus = 'Approved';
        this.adminOfficerDetails.isActive = true;
        
      }else if(count < 2 && loginStatus === 'Approved'){
        // this.toastr.error('Document verification pending.')
        return;
      }else if(count === 2 && loginStatus === 'Rejected'){
        this.adminOfficerDetails.loginStatus = 'Rejected';
        await this.updateAdminOfficerLoginStatus(this.adminOfficerDetails);
      }else if(count < 2 && loginStatus === 'Rejected'){
        this.adminOfficerDetails.loginStatus=loginStatus
        await this.updateAdminOfficerLoginStatus(this.adminOfficerDetails);
        return;
      }
    }else if(contactOfficerDetails.contactRole === 'Technical Officer'){
      await this.getTechnicalOfficerDetails(contactOfficerDetails.id);
      ////console.log(this.technicalOfficerDetails.organisationId)
      await this.getContactOfficerDocuments("Technical",this.technicalOfficerDetails.organisationId,this.technicalOfficerDetails.techEmail);
      let count = 0;
      ////console.log('exe')
      ////console.log(this.documentsList)
      this.documentsList.forEach(doc => {
        if(doc.documentStatus === 'Approved'){
          count = count + 1;
          ////console.log(count)
        }else{
          count = count - 1;
          ////console.log(count)
        }
      });
      if(count === 2){
        ////console.log(this.technicalOfficerDetails)
        this.technicalOfficerDetails.loginStatus = loginStatus;
        this.technicalOfficerDetails.isActive = true;
        await this.updateTechnicalOfficerLoginStatus(this.technicalOfficerDetails);
      }else{
        ////console.log(this.technicalOfficerDetails)
        // this.technicalOfficerDetails.isActive = false;
        this.technicalOfficerDetails.loginStatus=loginStatus
        await this.updateTechnicalOfficerLoginStatus(this.technicalOfficerDetails);
        // this.toastr.error('Document verification pending');
        return;
      }
    }else{
      await this.getBillingOfficerDetails(contactOfficerDetails.id);
      ////console.log(this.billingOfficerDetails.billEmail)
      await this.getContactOfficerDocuments("Billing",this.billingOfficerDetails.organisationId,this.billingOfficerDetails.billEmail);
      let count = 0;
      ////console.log('exe')
      this.documentsList.forEach(doc => {
        if(doc.documentStatus === 'Approved'){
          count = count + 1;
          ////console.log(count)
        }else{
          count = count - 1;
          ////console.log(count)
        }
      });
      if(count === 2){
        this.billingOfficerDetails.loginStatus = loginStatus;
        this.billingOfficerDetails.isActive = true;
      await this.updateBillingOfficerLoginStatus(this.billingOfficerDetails);
      }else{
        // this.billingOfficerDetails.isActive = false;
        this.billingOfficerDetails.loginStatus=loginStatus
        await this.updateBillingOfficerLoginStatus(this.billingOfficerDetails);
        // this.toastr.error('Document verification pending');
        return;
      }
    }
    //create the new user based on login status
    if(loginStatus === 'Approved'){
      this.user.active = true;
      ////console.log(this.adminOfficerDetails)
      ////console.log(this.technicalOfficerDetails)
      ////console.log(this.billingOfficerDetails)
    }else{
      this.user.active = false;
      // this.toastr.error('Login Rejected');
      return;
    }
    this.user.userName = contactOfficerDetails.personName;
    this.user.userId = contactOfficerDetails.emailId;
    ////console.log(contactOfficerDetails.contactRole);
    if(contactOfficerDetails.contactRole=='Administrative Officer'){
      ////console.log(this.emailRoleMap)
      this.user.userRoles = this.AllRoles.filter(role => {
        if (this.user.userId && this.emailRoleMap[this.user.userId]) {
            return this.emailRoleMap[this.user.userId].includes(role.roleName);
        }
        return false;
    });
    ////console.log(this.user.userRoles)
    }else if(contactOfficerDetails.contactRole=='Billing Officer'){
      this.user.userRoles = this.AllRoles.filter(role => {
        if (this.user.userId && this.emailRoleMap[this.user.userId]) {
            return this.emailRoleMap[this.user.userId].includes(role.roleName);
        }
        return false;
    });
    }else if(contactOfficerDetails.contactRole=='Technical Officer'){
      this.user.userRoles = this.AllRoles.filter(role => {
        if (this.user.userId && this.emailRoleMap[this.user.userId]) {
            return this.emailRoleMap[this.user.userId].includes(role.roleName);
        }
        return false;
    });
    }
    // this.user.role = contactOfficerDetails.contactRole;
    this.user.mobileNumber = contactOfficerDetails.mobileNumber;
    this.user.createdByEmailId = localStorage.getItem('email');
    this.user.organisationId = contactOfficerDetails.organisationId;
    this.user.isOnboardingCompleted = true;
    this.user.designation = contactOfficerDetails.designation;
    this.user.active  = true;
    ////console.log(this.user);
    // return
   
    if(this.user.userId==this.superAdminEmail){
      await lastValueFrom(this.userService.updateUserRole(this.user.userRoles,this.superAdminEmail)).then(
        response => {
          ////console.log(response)
          if(response.status === HttpStatusCode.Created){
            ////console.log(response);
            // this.toastr.success('Login approved');
            //if(this.role === 'IDRBTADMIN'){
               this.getContactOfficersDetails(0);
            // }else if(this.role != 'IDRBTADMIN' && parseInt(this.organisationId) > 0){
            //    this.getContactOfficersDetails(parseInt(this.organisationId));
            // }
          }
        },error => {
          if(error.status === HttpStatusCode.Unauthorized){
            this.navigateToSessionTimeout();
          }else if(error.status === HttpStatusCode.InternalServerError){
            this.toastr.error('Error while approving user... please try again !');
          }
        }
      )
    }
    else{

      await lastValueFrom(this.userService.saveUser(this.user)).then(
        response => {
          ////console.log(response)
          if(response.status === HttpStatusCode.Created){
            ////console.log(response);
            if(this.adminOfficerDetails!=null){
              this.updateAdminOfficerLoginStatus(this.adminOfficerDetails)
              this.adminOfficerDetails=null;
            }else if(this.technicalOfficerDetails!=null){
              this.updateTechnicalOfficerLoginStatus(this.technicalOfficerDetails);
              this.technicalOfficerDetails=null;
            }else if(this.billingOfficerDetails){
              this.updateBillingOfficerLoginStatus(this.billingOfficerDetails);
              this.billingOfficerDetails=null;
            }
            // this.toastr.success('Login approved');
            //if(this.role === 'IDRBTADMIN'){
               this.getContactOfficersDetails(0);
            // }else if(this.role != 'IDRBTADMIN' && parseInt(this.organisationId) > 0){
            //    this.getContactOfficersDetails(parseInt(this.organisationId));
            // }
          }
        },error => {
          if(error.status === HttpStatusCode.Unauthorized){
            this.navigateToSessionTimeout();
          }else if(error.status === HttpStatusCode.InternalServerError){
            this.toastr.error('Error while approving user... please try again !');
          }
        }
      )
    }
    
  }
  




  async updateAdminOfficerLoginStatus(adminDetails: any){
    await lastValueFrom(this.contactDetailsService.updateAdminDetails(adminDetails)).then(
      response => {
        if(response.status === HttpStatusCode.Ok){
         // this.getContactOfficersDetails(response.body.organisationId);
         ////console.log(response);
        }
      }
    )
  }

  async updateTechnicalOfficerLoginStatus(techDetails: any){
    await lastValueFrom(this.contactDetailsService.updateTechDetails(techDetails)).then(
      response => {
        if(response.status === HttpStatusCode.Ok){
         // this.getContactOfficersDetails(response.body.organisationId);
         ////console.log(response)
        }
      }
    )
  }

  async updateBillingOfficerLoginStatus(billDetails: any){
    await lastValueFrom(this.contactDetailsService.updateBillDetails(billDetails)).then(
      response => {
        if(response.status === HttpStatusCode.Ok){
         // this.getContactOfficersDetails(response.body.organisationId);
         ////console.log(response)
        }
      }
    )
  }

  binaryData: any;
  documentNumber: any = '';
  currentDocumentId: number = 0;
  showImage:boolean;
  async viewCurrentData(binaryData: any, documentNumber: any,fileName:any, documentType:any ,doc){
    //this.binaryData = null
    this.modalTitle = documentType;  
    this.currentDocument=doc
    ////console.log(fileName)
    if (binaryData!=null && fileName.endsWith('.pdf')) {
           await this.displayPdf(binaryData); 
            this.showImage=false
            // ////console.log(document.getElementById("viewTheRgntDocs"))
            document.getElementById("viewTheRgntDocs")?.click();
          } else if (binaryData!=null) { 
            this.showImage=true;
            this.binaryData = binaryData;
            document.getElementById("viewTheRgntDocs")?.click();
          }
          
   
      this.documentNumber = documentNumber;
    // ////console.log(binaryData)
    // ////console.log(this.documentNumber)

  }
  viewTheDocsPdf:any
  async displayPdf(binaryData) {
    ////console.log(typeof binaryData === 'string')
    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);
    
      
       const pdfUrl = URL.createObjectURL(blob);
      this.viewTheDocsPdf = this.sanitizer.bypassSecurityTrustResourceUrl(pdfUrl); 
    
  } 
  }

  async updateApplicationStatusToIncomplete(){
    await this.getOrgDocuments(this.organisationId);
    //  console.log("org status",this.orgGstStatus,this.orgPanStatus,
    // this.orgBoardStatus,this.orgLicenceStatus,this.adminStatus,
    // this.technicalOfficerStatus,this.billingOfficerStatus)
 
   await this.updateAllUnApproveDomainsStatusesToIncompleteOfAnOrganisation(this.organisationId);  
   //this.toastr.success("The orgnisation's domain statuses has been changed to Incomplete for non-approved applications");
    
  }

  // /**
  //  * 
  //  * @param approvalStatus 
  //  * @param currentDocumentId 
  //  */
  currentDocument: any;
  documentComment: string = '';
  async approveOrRejectDocument(approvalStatus: string){
  

  if (this.approveTheDocsIsDisabled) {
    this.toastr.warning("Registrant has not completed the onboarding");
    return;
  }
    try {
    const response = await lastValueFrom(
      this.contactDocumentsService.updateDocumentStatus(
        approvalStatus,
        this.currentDocument.contactDocumentId,
        this.currentDocument.organisationId,
        this.currentDocument.contactType,
        this.currentDocument.documentType,
        this.documentComment,
        this.currentDocument.emailId
      )
    );

    if (response.status === HttpStatusCode.Ok) {
      if (approvalStatus === 'Approved') {
        //console.log("entered inside the approve/reject success method");
        document.getElementById("closeApproveRejectModal")?.click();
        this.toastr.success('Document Approved.');
        this.clearComments();
      } else {
        this.toastr.success('Document Rejected.');
        this.closeRejectModal();
        this.clearComments();
        await this.updateApplicationStatusToIncomplete();
      }
    }
  } catch (error: any) {
    if (error.status === HttpStatusCode.Unauthorized) {
      this.navigateToSessionTimeout();
    } else {
      console.error('Error during approval/rejection:', error);
    }
  }
    this.clearComments();
    await this.getContactOfficerDocuments(this.contactType, this.organisationId,this.verifyEmailId); 
    ////console.log(this.contactDetailsList)
    if(approvalStatus === 'Approved'){
      // this.toastr.success('Document Approved.');
      this.clearComments();
      if(this.contactType=='Administrative'){
        
        const matchingContactDetails = this.contactDetailsList.filter(contactDetail => {
          return contactDetail.emailId === this.verifyEmailId;
        });
        ////console.log(matchingContactDetails)
      
        if (matchingContactDetails.length > 0) {
          // Iterate through all matching contact details
          matchingContactDetails.forEach(matchingContactDetail => {
            if(matchingContactDetail.contactRole=="Administrative Officer"){
              this.enableOrDisableLoginStatus(approvalStatus, matchingContactDetail);
            }
            
          });
        }
      }else if (this.contactType=='Billing'){
        const matchingContactDetails = this.contactDetailsList.filter(contactDetail => {
          return contactDetail.emailId === this.verifyEmailId && contactDetail.contactRole === 'Billing Officer'; // Add contactRole filter
        });
      ////console.log(matchingContactDetails)
        if (matchingContactDetails.length > 0) {
          // Iterate through all matching contact details
          matchingContactDetails.forEach(matchingContactDetail => {
            if(matchingContactDetail.contactRole=="Billing Officer"){
              this.enableOrDisableLoginStatus(approvalStatus, matchingContactDetail);
            }
          });
        }
      }else if( this.contactType=='Technical'){
       
        const matchingContactDetails = this.contactDetailsList.filter(contactDetail => {
          return contactDetail.emailId === this.verifyEmailId && contactDetail.contactRole === 'Technical Officer'; // Add contactRole filter
        });
      
      
        if (matchingContactDetails.length > 0) {
          // Iterate through all matching contact details
          matchingContactDetails.forEach(matchingContactDetail => {
            if(matchingContactDetail.contactRole=="Technical Officer"){
              this.enableOrDisableLoginStatus(approvalStatus, matchingContactDetail);
            }
          });
        }
      }
      // document.getElementById("closeApproveCommentModal").click();
    }else{
      // this.toastr.success('Document Rejected.');
      // document.getElementById("closeRejectCommentModal").click();
      this.clearComments();
      if(this.contactType=='Administrative'){
        this.enableOrDisableLoginStatus(approvalStatus,this.contactDetailsList[0])
      }else if (this.contactType=='Billing'){
        this.enableOrDisableLoginStatus(approvalStatus,this.contactDetailsList[1])
      }else if( this.contactType=='Technical'){
        this.enableOrDisableLoginStatus(approvalStatus,this.contactDetailsList[2])
      }
    }
  }

  storeCurrentDocumentDetails(document: any){
    this.currentDocument = document;
  }

  goBack(){
    this.location.back();
  }
  clickedDocDetails:any;
  openFileReupload(documents){
    //console.log(documents)
    this.docName=documents.documentType
    //console.log(this.docName)
     this.clickedDocDetails=documents
    if(this.docName == 'Aadhaar'){
      this.inputValue=documents.aadharNumber
    }else {
      this.inputValue=''
    }
     document.getElementById("reuploadModel")?.click();
    return
  
    // document.getElementById("reUploadDocument")?.click();
    // this.orgDetails.documentPreviewCompleted = false;
    // this.updateOrganizationDocStatus();    //this.toastr.success('Document uploaded successfully.')
  }

  @ViewChild('filesInput') fileInput!: ElementRef;
  
   
  async handleTheDocument(event: any) {
  const docType = this.clickedDocDetails['documentType'];
    //console.log(this.inputFieldError)
    // { message: '', type: '' }
  if (this.inputFieldError.message=='' && this.inputFieldError.type=='') {
    if (this.uploadedDocuments == null || this.uploadedDocuments == undefined) {
      this.docErrors = "Please Upload Document";
      return;
    }

    if ((docType == 'Aadhaar') && this.inputValue == '') {
      this.inputFieldError.message = "Please enter the " + docType + " number";
      return;
    }
    // console.log(this.docNames[0],this.uploadedDocuments)
    if (this.docNames.includes(this.uploadedDocuments.name)) {
        this.inputFieldError.message = "Selected file already exists";
        return;
      }

    let file = this.uploadedDocuments;
    //console.log(docType);

    try {
      const response = await lastValueFrom(
        this.contactDocumentsService.updateContactDocument(
          this.clickedDocDetails['contactDocumentId'],
          file,
          docType,
          this.inputValue
        )
      );
        this.uploadedDocuments=null
      // Success flow
      await this.getContactOfficerDocuments(this.contactType, this.organisationId, this.verifyEmailId);
      this.toastr.success("Document uploaded successfully");
      await this.updateOrganizationDocStatus();
      // Close modal after successful upload
     $('#reuploadModal').modal('hide');

this.clearTheinpuErrors();
      document.getElementById('closeUploadModal')?.click();
      await this.getOrgDocuments(this.organisationId);
      this.uploadSuccessMessage=''
   file=null;

      //await this.updateStatus();
    //   console.log("org status",this.orgGstStatus,this.orgPanStatus,
    // this.orgBoardStatus,this.orgLicenceStatus,this.adminStatus,
    // this.technicalOfficerStatus,this.billingOfficerStatus)
     
  if((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 === '')) {
   
     await this.updateAllUnApproveDomainsStatusesToSubmittedForAnOrganisation(this.organisationId); 
   
}

    } catch (error) {
      console.log("error came", error);
    }
  }
}


  async updateStatus(){
    

      

  }

  orgDetails: any;
  async getOrganisationDetails(organisationId: number){
    await lastValueFrom(this.orgService.getOrganisationDetailsByOrganisationId(organisationId)).then(
      response => {
        if(response.status === HttpStatusCode.Ok){
          this.orgDetails = response.body;
        }
      }
    )
  }

  async updateOrganizationDocStatus(){
    this.orgDetails.documentPreviewCompleted = false;
    await lastValueFrom(this.orgService.updateOrganisationDetails(this.orgDetails)).then(
      response => {
        //this.toastr.success('Document re-uploaded')
        if (response.status === HttpStatusCode.Ok) {
          //this.toastr.success('Organisation documents updated successfully.');
        } else {
          //this.toastr.error('Error updating organisation documents.');
        }
      }
    )
     await this.getOrgDocuments(this.organisationId);
  }

  // viewDocuments(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=false
  //       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{
  //     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(); 
  //     }
  //   }
  // }

  clearComments(){
    this.documentComment='';
  }
  adminOfficerDetails: any = null;
  technicalOfficerDetails: any = null;
  billingOfficerDetails: any = null;
  async getAdminOfficerDetails(id: number){
    await lastValueFrom(this.contactDetailsService.getAdminOfficerDetailsById(id)).then(
      response => {
        if(response.status === HttpStatusCode.Ok){
          this.adminOfficerDetails = response.body;
        }
      },error => {
        if(error.status === HttpStatusCode.Unauthorized){
          this.navigateToSessionTimeout();
        }
      }
    )
  }

  async getTechnicalOfficerDetails(id: number){
    await lastValueFrom(this.contactDetailsService.getTechnicalOfficerDetailsById(id)).then(
      response => {
        if(response.status === HttpStatusCode.Ok){
          this.technicalOfficerDetails = response.body;
        }
      },error => {
        if(error.status === HttpStatusCode.Unauthorized){
          this.navigateToSessionTimeout();
        }
      }
    )
  }

  async getBillingOfficerDetails(id: number){
    await lastValueFrom(this.contactDetailsService.getBillingOfficerDetailsById(id)).then(
      response => {
        if(response.status === HttpStatusCode.Ok){
          this.billingOfficerDetails = response.body;
        }
      },error => {
        if(error.status === HttpStatusCode.Unauthorized){
          this.navigateToSessionTimeout();
        }
      }
    )
  }

closeTheApproveRejectModal(action){
      if(!this.approveTheDocsIsDisabled){
          document.getElementById("closeApproveRejectModal").click();
          if(action=='Approve'){
            setTimeout(() => {
              document.getElementById("contactApproveComment").click();
            }, 10);
          }else if(action=='Reject'){
             setTimeout(() => {
              document.getElementById("contactRejectComment").click();
            }, 10);
          }
          
      }else{
        this.toastr.warning("Registrant has not completed the onboarding");
      }
    
    }
  closeRejectModal(){
  document.getElementById("closeRejectCommentModal").click();
  document.getElementById("closeApproveRejectModal").click();

 }
 openTheApproveRejectModal(){
  document.getElementById("viewTheRgntDocs").click();
 }

 domainsList: any[] = [];
 isDomainApplicationResubmitted: boolean = false;
async getDomainsListByOrganisationId(organisationId: number) {
  await lastValueFrom(this.domainService.getAllDomainsByOrgId(organisationId)).then(
    response => {
      if (response.status === HttpStatusCode.Ok) {
        this.domainsList = response.body;

        //console.log(this.isDomainApplicationResubmitted);
        //console.log(this.domainsList);
      }
    },
    error => {
      if (error.status === HttpStatusCode.Unauthorized) {
        this.navigateToSessionTimeout();
      }
    }
  );
}
inputFieldError:any={ message: '', type: '' }
selectedDocType:string=''
inputValue:string=''
docName:string=''
uploadedDocuments
  handleInputChange(event: any): void {
    //console.log(event.target.value)
    //console.log(this.selectedDocType)
    this.inputFieldError = { message: '', type: '' };
    const inputValue1 = event.target.value.trim();
    // Get the raw input value from the event
    let inputValue = event.target.value;
    if(!inputValue1){
      this.inputFieldError = { message: '', type: '' };
      return;
    }
    // Step 1: Handle PAN validation
    // if (this.docName === 'PAN') {
    //   // Remove special characters and keep only alphanumeric characters
    //   let sanitizedInput = inputValue.replace(/[^a-zA-Z0-9]/g, '');
      
    //   // Convert to uppercase
    //   this.inputValue = sanitizedInput.toUpperCase();
    //   // Validate PAN format: 5 letters + 4 digits + 1 letter
    //   //const isValidPAN = /^[A-Z]{5}[0-9]{4}[A-Z]{1}$/.test(sanitizedInput);
    //   const isValidPAN = this.inputValue.length == 10;
  
    //   this.inputFieldError = isValidPAN
    //     ? { message: '', type: '' }
    //     : { message: 'Invalid PAN format.', type: 'inputValue' };
    // }
  
    // Step 2: Handle Aadhaar validation with space after every 4 digits
     if (this.docName === 'Aadhaar') {
      // Allow only numeric input for Aadhaar (reject any non-digit characters)
      let sanitizedAadhaarInput = inputValue.replace(/[^0-9]/g, '');
  
      // If the input value is longer than 12 digits, truncate it
      sanitizedAadhaarInput = sanitizedAadhaarInput.slice(0, 12);
  
      // Add space after every 4 digits for Aadhaar formatting
      let formattedAadhaar = sanitizedAadhaarInput.replace(/(\d{4})(?=\d)/g, '$1 ');
  
      // Update the input value with formatted Aadhaar number
      this.inputValue = formattedAadhaar;
  
      // Validate Aadhaar format: must be exactly 12 digits (without spaces)
      const isValidAadhaar = /^[0-9]{12}$/.test(sanitizedAadhaarInput);
  
      this.inputFieldError = isValidAadhaar
        ? { message: '', type: '' }
        : { message: 'Invalid Aadhaar format.', type: 'inputValue' };
    }
    else{
      this.inputFieldError = { message:'', type:''}
    }
  }
getMaxLength(): number | null {
    switch (this.selectedDocType) {
      case 'Organization GSTIN':
        return 15;
      case 'PAN':
        return 10;
      case 'License Given By RBI': // CIN
        return 20;
      default:
        return null; // Or a default max length if needed
    }
  }
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
    }
  }
}

reUploadDocument(doc){

}
clearTheinpuErrors(){
this.inputFieldError={ message: '', type: '' };
        this.inputValue='';
        this.docErrors='';
        this.docName='';
        this.uploadSuccessMessage='';
        this.uploadedDocuments=null
}
triggerFileInput(){
this.fileInput.nativeElement.click();
}
uploadSuccessMessage
docErrors
maxFileSizeInMB: number = environment.maxFileSizeMB;
handleFileInput(event: any) {
    const selectedFile = event.target.files[0];
    const maxFileSize = this.maxFileSizeInMB * 1024 * 1024;  // Convert MB to bytes
    
    if (selectedFile.size > maxFileSize) {
      this.docErrors =`Select a file less than ${this.maxFileSizeInMB}MB.`;
      return;
    }
    const validFileTypes = ['application/pdf', 'image/jpeg', 'image/jpg'];
    if (!validFileTypes.includes(selectedFile.type)) {
      this.docErrors = 'Invalid file type. Only PDF, JPG, and JPEG are allowed'
      // input.value = ''; // Reset the file input field
      return;
    }
   
    this.uploadedDocuments=selectedFile;
    this.docErrors='';
    this.uploadSuccessMessage = `${this.docName} - ${selectedFile.name}.`;
    this.inputFieldError= { message: '', type: '' };
   
  }

  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.toastr.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);
    //} 
  })
}

// orgGstStatus;
//   orgPanStatus;
  orgLicenceStatus;
  orgBoardStatus;

  entireOrgDocsObj:any;
  async getOrgDocuments(orgId){
    await lastValueFrom(this.documentService.getOrgDoucumentsById(orgId)).then(
      (response) => {
        //console.log("hello")
        this.entireOrgDocsObj=response.body;
       
        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.orgDocNames)
        this.getContactOfficerDocuments1(orgId);
      
      },(error)=>{
        //console.log(error)
        this.isLoadingData=false
        if(error.status===HttpStatusCode.Unauthorized){
          this.isLoadingData=false
          this.router.navigateByUrl("session-timeout");
        }
      }
  )
  }

  adminStatus;
  technicalOfficerStatus;
  billingOfficerStatus;

  async getContactOfficerDocuments1(organisationId: number) {
    await lastValueFrom(this.contactDetailsService.getContactOfficersDetails(organisationId))
    .then(
      (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) => {
        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);
        }
      }
    });
  }

 
}

async updateAllUnApproveDomainsStatusesToIncompleteOfAnOrganisation(organisationId: number) {
  await this.getOrgDocuments(organisationId);
  //  console.log(this.orgGstStatus,this.orgPanStatus,
  //   this.orgBoardStatus,this.orgLicenceStatus,this.adminStatus, this.technicalOfficerStatus,this.billingOfficerStatus)
   if((this.orgBoardStatus === 'Rejected')
  || (this.orgLicenceStatus === 'Rejected') 
  || (this.adminStatus === 'Rejected')
  || (this.technicalOfficerStatus === 'Rejected')
  || (this.billingOfficerStatus === 'Rejected')) {
   
  await this.getAllDomainsByOrganisationId(organisationId);
  this.domainsListOfOrg.forEach((domain) => {
    if(domain.applicationStatus !== this.assetService.Approved 
      || domain.applicationStatus !== this.assetService.Incomplete) {
        domain.applicationStatus = this.assetService.Incomplete;
      this.updateDomainApplicationStatusWhenDocumentReupload(domain);
    }
  });
  this.toastr.success("All domains for this organisation updated to Incomplete status");
}
}
clear(){
  window.location.reload();
}
  usersList=[];
  approveTheDocsIsDisabled:boolean=true
 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) {

           // this.usersList = response.body;
            this.usersList = response.body.filter((user: any) => {
            // Check if userRoles exists and is an array
              if (!user.userRoles || !Array.isArray(user.userRoles)) {
                return false; // Skip if userRoles is missing or not an array
              }

              // Check if any of the user's roles is 'Super Admin'
              const hasSuperAdminRole = user.userRoles.some((role: any) => {
                return role.roleName === 'Super Admin';
              });

              // Check the deletion status
              const isNotDeleted = (user.isDeleted === false || user.isDeleted === null);

              return hasSuperAdminRole && isNotDeleted;
            });
            this.approveTheDocsIsDisabled= !(response.body.some(user => user.isOnboardingCompleted === true));

            console.log(" Users API response:", response.body);
console.log(" onboarding status check:",
  response.body.map(u => u.isOnboardingCompleted)
);
console.log(" Final flag:", this.approveTheDocsIsDisabled);
          }
        },
        (error) => {
          if (error.status === HttpStatusCode.Unauthorized) {
            // this.isLoadingData=false;
            // this.navigateToSessionTimeout();
          }
        }
      );
    }

}