
import { HttpStatusCode } from '@angular/common/http';
import { Component, ElementRef, TemplateRef, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { Router } from '@angular/router';
import { firstValueFrom, lastValueFrom } from 'rxjs';
import { DomainService } from '../rgnt-domain/service/domain.service';
import { MatPaginator, PageEvent } from '@angular/material/paginator';
import { MatSort, SortDirection } from '@angular/material/sort';
import { MatDialog, MatDialogRef } from '@angular/material/dialog';
import { Domain } from '../model/domain.model';
import { TransactionRequest } from '../model/TransactionRequest.model';
import { DomainInvoiceService } from '../domain-invoices/service/domain-invoices.service';
// import { DomainApplicationService } from './service/domain-application.service';
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { FormBuilder, FormGroup } from '@angular/forms';
import { UserService } from '../user/service/user.service';
import { ToastrService } from 'ngx-toastr';
import { NameServerService } from '../name-server-form/service/name-server.service';
import { environment } from '../environments/environment';
import { AssetService } from '../asset.service';
import { DomainApplicationService } from '../domain-application/service/domain-application.service';
import { OrganisationDetailsService } from '../organisation-details/service/organisation-details.service';
//import { AES256Bit } from './service/encryption.service';
declare var $: any;
@Component({
    selector: 'app-entity-approval',
    templateUrl: './entity-approval.component.html',
    styleUrls: ['./entity-approval.component.css'],
    standalone: false
})
export class EntityApprovalComponent {
  currentOnboardingOrganization: any;
  paymentForm: FormGroup;
  // @ViewChild('paymentForm') paymentFormElement: any;

  EncryptTrans: string = '';
  MultiAccountInstructionDtls: string = '';
  merchIdVal: string = '1000356';
  maxDataCount: number = 0;
  role: string = localStorage.getItem('userRole');
  userEmailId = localStorage.getItem('email');
  currentStatus: string = ''
  displayedColumns: string[] = [
    //initialized in ngOninit based on the role
  ]; // Matches matColumnDef values

  onBoardingStepIndex: number = 10;
  paymentReceiptNumber: string;
  domainsList: any[];
  entitiesList: any[];
  domainsDataSource: MatTableDataSource<any>;
  entitiesDataSource: MatTableDataSource<any>;
  transactionReqObj: TransactionRequest = new TransactionRequest();
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;
  searchText: string = '';
  constructor(private fb: FormBuilder, private userService: UserService,
    private domainService: DomainService, private router:
      Router, private dialog: MatDialog, private domainApplicationService: DomainApplicationService,
    private http: HttpClient, private nameserverService: NameServerService,
    private tostr: ToastrService,
    private orgService: OrganisationDetailsService,
    private assetService: AssetService) {
    this.domainsDataSource = new MatTableDataSource<any>();
    this.entitiesDataSource = new MatTableDataSource<any>();

  }
  organisationId;

  async ngOnInit() {
    if (this.role != "IDRBTADMIN") {

    } else {
      //console.log('exe 1')
      this.displayedColumns = [
        'organisationDetailsId',
        'institutionName',
        'submissionDate',
        'organisationApplicationStatus',
        'latestPaymentStatus',
        'createdByEmailId',
        'askToResubmit',
        'deleteApplication',
        // 'checkbox',
        // 'domainId',
        // 'organizationName',
        // 'domainName',
        //  'bankName',
        // 'submissionDate',
        // 'applicationStatus',
        //  'paymentStatus',
        //  'nsRecordStatus',
        // 'industry',
        //  'tenure',
        //'checkPayment',
        //  'viewNameServers',
        //  'resubmitComment',
        // 'userMailId',
        //15-10-2025 removed markAsDelete feature
        // 'markAsDelete'
      ]
      // this.getAllDomainsListByOrgId(0);
      //await this.getDomainsCountByorgId();
      //console.log(this.domainsListOfOrg)
    }
    //console.log(this.role)
    //console.log(this.userEmailId)
      this.getFilteredEntities();
    // this.processPayment();
  }

  async fetchOrgIdAndDomainsOfit() {
    await lastValueFrom(this.userService.getUserByEmailId(this.userEmailId)).then(
      (response) => {

        //console.log(response)
        this.organisationId = response.body.organisationId;
        if (this.organisationId != 0) {
          //console.log(this.organisationId)
          this.getAllDomainsListByOrgId(this.organisationId);
        }


      },
      (error) => {
        if (error.status === HttpStatusCode.Unauthorized) {
          this.navigateToSessionTimeout();
        }
      }
    );
  }

  getUserOrgId(): any {
    this.userService.getUserByEmailId(this.userEmailId).subscribe({
      next: (response) => {
        return response.body.organisationId;

      }, error: (error) => {
        if (error.status === HttpStatusCode.Unauthorized) {
          this.navigateToSessionTimeout();
        }
      }
    })
  }
  async getAllDomainsList(userId: string) {
    await lastValueFrom(this.domainService.getAllDomains(userId)).then(
      (response) => {
        if (response.status === HttpStatusCode.Ok) {
          //console.log(response)
          this.domainsList = response.body;
          this.domainsDataSource.data = this.domainsList;

          setTimeout(() => {
            this.domainsDataSource.sort = this.sort;
          }, 0);
          setTimeout(() => {
            this.domainsDataSource.paginator = this.paginator;
          }, 0);

        }
      },
      (error) => {
        if (error.status === HttpStatusCode.Unauthorized) {
          this.navigateToSessionTimeout();
        }
      }
    );
  }
  isLoadingData: boolean = false;

  async getLoggedInUserDetails() {
    if (localStorage.getItem('email') == null) {
      this.navigateToSessionTimeout();
      return
    }
    this.isLoadingData = true;
    await lastValueFrom(this.userService.getUserByEmailId(localStorage.getItem('email'))).then(
      response => {
        //console.log(response)
        if (response.status === HttpStatusCode.Ok) {
          //console.log(response.body)
          this.organisationId = response.body.organisationId;
          if (this.role === 'IDRBTADMIN') {
            this.onBoardingStepIndex = 10;
          } else {
            this.onBoardingStepIndex = response.body.onboardingStepIndex;
          }
          //console.log(this.onBoardingStepIndex)
          if (this.role !== 'IDRBTADMIN') {
            //console.log('exe')
            //console.log(this.organisationId)
            if (this.organisationId > 0) {
              this.getAllDomainsListByOrgId(this.organisationId);
            } else {
              this.domainsList = []
              this.isLoadingData = false;
            }

            this.displayedColumns = [
              // 'checkbox',
              // 'domainId',
              // 'organizationName',
              // 'domainName',
              // 'bankName',
              // 'submissionDate',
              // 'applicationStatus',
              // 'paymentStatus',
              // 'nsRecordStatus',
              // 'industry',
              // 'tenure',
              //'checkPayment',
              //  'viewNameServers',
              // 'resubmitComment',
              // 'markAsDelete',
              // 'payment'

            ]
          }
        }
      }, error => {
        if (error.status === HttpStatusCode.Unauthorized) {
          this.navigateToSessionTimeout();
        }
      }
    )
  }

  async getOrganisationDetailsByOrganisationId(orgId: number) {
    if (!orgId || orgId <= 0) {
      console.log("Invalid Organization ID");
      return;
    }
    console.log("Fetching organization by ID in Entity page:", orgId);
    this.isLoadingData = true;
    await lastValueFrom(this.orgService.getOrganisationDetailsByOrganisationId(orgId)).then(
      (response) => {
        if (response.status === HttpStatusCode.Ok) {
          this.currentOnboardingOrganization = response.body;
          console.log("Fetched organization in Entity Page:", this.currentOnboardingOrganization);

          //If you need to display columns for organization details
          // this.displayedColumns = [
          // ];

          this.isLoadingData = false;
        }
      },
      (error) => {
        if (error.status === HttpStatusCode.Unauthorized) {
          this.navigateToSessionTimeout();
        }
        this.isLoadingData = false;
      }
    );
  }

async getFilteredEntities(): Promise<void> {

  this.isLoadingData = true;

  const filters = JSON.parse(
    localStorage.getItem('filters') || '{}'
  );

  this.orgService.getAllOrganisations().subscribe(

    async (response) => {

      if (response.body && response.body.length > 0) {

        try {

          // FETCH ALL LATEST PAYMENT STATUSES IN SINGLE API CALL

          const paymentResponse = await lastValueFrom(
            this.domainService.getLatestPaymentStatuses()
          );

          const paymentStatuses = paymentResponse.body || {};

          // MAP PAYMENT STATUS TO ENTITIES

          this.entitiesList = response.body.map((entity) => {

            entity.latestPaymentStatus =
              paymentStatuses[entity.organisationDetailsId] || 'NA';

            return entity;
          });

          // SORT BY SUBMISSION DATE DESC

          this.entitiesList = this.entitiesList.sort((a, b) => {

            if (!a.submissionDate) return 1;

            if (!b.submissionDate) return -1;

            return (
              new Date(b.submissionDate).getTime() -
              new Date(a.submissionDate).getTime()
            );

          });

          // DATASOURCE

          this.entitiesDataSource.data = this.entitiesList;

          this.entitiesDataSource.paginator = this.paginator;

          this.entitiesDataSource.sort = this.sort;

          this.noDataFound = false;

        } catch (e) {

          console.error(
            'Error fetching latest payment statuses',
            e
          );

          this.noDataFound = true;
        }

      } else {

        this.entitiesList = [];

        this.entitiesDataSource.data = this.entitiesList;

        this.noDataFound = true;
      }

      this.isLoadingData = false;

    },

    (error) => {

      this.isLoadingData = false;

      this.noDataFound = true;

      if (error.status === HttpStatusCode.Unauthorized) {

        this.navigateToSessionTimeout();

      }

    }

  );

}

//  getFilteredEntities(): void {
//    this.isLoadingData = true;
//   const filters = JSON.parse(localStorage.getItem('filters') || '{}');

//   this.orgService.getAllOrganisations().subscribe(
//     (response) => {
//       if (response.body && response.body.length > 0) {

//         // ✅ ADD ONLY THIS SORT LOGIC (LATEST submissionDate FIRST)
//         this.entitiesList = response.body.sort((a, b) => {
//           if (!a.submissionDate) return 1;
//           if (!b.submissionDate) return -1;

//           return (
//             new Date(b.submissionDate).getTime() -
//             new Date(a.submissionDate).getTime()
//           );
//         });

//         this.entitiesDataSource.data = this.entitiesList;
//         this.entitiesDataSource.paginator = this.paginator;
//         this.entitiesDataSource.sort = this.sort;
//         this.noDataFound = false;

//       } else {
//         this.entitiesList = [];
//         this.entitiesDataSource.data = this.entitiesList;
//         this.noDataFound = true;
//       }
//        this.isLoadingData = false;
//     },
//     (error) => {
//         this.isLoadingData = false;
//       this.noDataFound = true;
//       if (error.status === HttpStatusCode.Unauthorized) {
//         this.navigateToSessionTimeout();
//       }
//     }
//   );
// }

  // getFilteredDomains(): void {
  //   const filters = JSON.parse(localStorage.getItem('filters') || '{}'); // Retrieve filters from localStorage
  //   //console.log("filterd data is:",filters);
  //   this.domainService.getFilteredData(this.filters).subscribe(
  //     (response) => {
  //       // Check if the response has data
  //       //console.log(response)
  //       if (response.body && response.body.length > 0) {
  //         this.domainsList = response.body;
  //         //console.log(this.domainsList)
  //         this.domainsDataSource.data = this.domainsList;
  //         this.domainsDataSource.paginator = this.paginator;
  //         this.domainsDataSource.sort = this.sort;
  //         this.noDataFound = false; // Hide "No results" message if data is found
  //       } else {
  //         // If no data is found, display the "No results found" message
  //         this.domainsList = []; // Ensure the data list is empty
  //         this.domainsDataSource.data = this.domainsList; // Set the data source to empty
  //         this.noDataFound = true; // Set the flag to true to show "No results" message
  //       }
  //     },
  //     (error) => {
  //       //console.error('Error fetching filtered domains:', error);
  //       this.noDataFound = true; // In case of error, show "No results" message
  //       if (error.status === HttpStatusCode.Unauthorized) {
  //         this.navigateToSessionTimeout();
  //       }
  //     }
  //   );
  // }

  navigateToDomainNameServers(domainId: number) {
    if (this.role === 'IDRBTADMIN') {
      this.router.navigate(['/domain-details'], { queryParams: { domainId: domainId } });
    } else {
      this.router.navigate(['/domain-details'], { queryParams: { domainId: domainId } });
    }
  }

  navigateToEntityDetails(entity) {
    // if (domain.organisationId == null || domain.organisationId == 0) {
    //   this.tostr.warning("Entity is not yet registered");
    //   return;
    // }
    if (this.role === 'IDRBTADMIN') {
      this.router.navigate(['/entity-application-details'], { queryParams: { organisationDetailsId: entity.organisationDetailsId } });
    } else {
      this.router.navigate(['/rngt-app-details'], { queryParams: { organisationDetailsId: entity.organisationDetailsId } });
    }
  }
  navigateToSessionTimeout() {
    this.router.navigateByUrl('/session-timeout');
  }
  // applyFilter() {
  //   this.domainsDataSource.filter = this.searchText.trim().toLowerCase(); // Filters based on search text

  //   if (this.domainsDataSource.paginator) {
  //     this.domainsDataSource.paginator.firstPage(); // Reset paginator to the first page after filtering
  //   }
  // }
  applyFilter() {
    const filterValue = (event.target as HTMLInputElement).value.trim().toLowerCase(); // Get the filter text

    this.entitiesDataSource.filterPredicate = (data: any, filter: string) => {

      const displayedColumnsValues = this.displayedColumns.map(column => {
        if (column === 'submissionDate') {
          // For date columns, format the date to 'MMM d, y, h:mm a' format
          const dateValue = data[column];
          return this.formatDate(new Date(dateValue));
        } else if (column === 'institutionName') {
          const institutionName = data.institutionName?.toString().toLowerCase() || "";
          const organisationDetailsId = data.organisationDetailsId?.toString().toLowerCase() || "";
          console.log(institutionName+organisationDetailsId)
          return organisationDetailsId + institutionName; // Combine for filtering
        } else {
          // For non-date columns, return the column value
          console.log ("table adata", data[column])
          return data[column];
        }
      });

      // Perform a case-insensitive search across the columns
      return displayedColumnsValues.some(value =>
        value?.toString().toLowerCase().includes(filter)
      );
    };

    // Apply the filter value to the data source
    this.entitiesDataSource.filter = filterValue;

    // Reset paginator to the first page after filtering
    if (this.entitiesDataSource.paginator) {
      this.entitiesDataSource.paginator.firstPage();
    }
  }


  formatDate(date: Date): string {
    const options: Intl.DateTimeFormatOptions = {
      month: 'short',  // 'Jan', 'Feb', etc.
      day: 'numeric',  // '30', '1', etc.
      year: 'numeric', // '2025', '2026', etc.
      hour: 'numeric', // '3', '12', etc.
      minute: 'numeric', // '46', '30', etc.
      hour12: true, // AM/PM format
    };

    return date.toLocaleString('en-US', options); // Format as 'Jan 30, 2025, 3:46 PM'
  }
  filters = {
    applicationId: '',
    userId: this.userEmailId,
    organisationName: '',
    domainName: '',
    nsRecordStatus: '',
    status: '',
    submissionDateFrom: '', // Add this field for the "From" date
    submissionDateTo: ''
  };

  // resetFilters(): void {
  //   this.filters = {
  //     userId: '',
  //     organisationName: '',
  //     nsRecordStatus: '',
  //     status: '',
  //     submissionDateFrom: '', // Add this field for the "From" date
  // submissionDateTo: '' 
  //   };
  //   this.getFilteredDomains();
  // }

  filterButton() {
    // Assuming you have a filter object with values (e.g., from input fields)
    //console.log(this.filters.submissionDateFrom)
    const filters = {
      userId: this.userEmailId,
      applicationId: this.filters.applicationId,
      organisationName: this.filters.organisationName,
      domainName: this.filters.domainName, // The value entered by the user
      nsRecordStatus: this.filters.nsRecordStatus,    // The value entered by the user
      status: this.filters.status,
      submissionDateFrom: this.filters.submissionDateFrom,
      submissionDateTo: this.filters.submissionDateTo
    };

    // Store the filters in localStorage as a JSON string
    localStorage.setItem('filters', JSON.stringify(filters));

    // Clear the noDataFound flag and fetch filtered data
    this.noDataFound = false;
    this.getFilteredEntities(); // Fetch the filtered data
    // window.location.reload();
  }
  noDataFound: boolean = false;

  clearButton() {

    //localStorage.removeItem('filters');

    // Clear any local filter variables
    this.filters.organisationName = '';
    this.filters.domainName = '',
      this.filters.nsRecordStatus = '';
    this.filters.status = '';
    this.filters.submissionDateFrom = '', // Add this field for the "From" date
      this.filters.submissionDateTo = '';
    this.filters.applicationId = ''
    localStorage.setItem('filters', JSON.stringify(this.filters));

    // Fetch all domains without any filters
    if (this.role !== 'IDRBTADMIN') {
      //console.log('exe')

      this.getAllDomainsList(this.userEmailId);


    } else {

      this.getAllDomainsList("");

    }
  }
  processPayment() {
    this.domainApplicationService.processPayment().subscribe(
      (response: string[]) => {
        //  this.paymentForm = this.fb.group({
        //   encryptTrans: response[0],
        //   merchIdVal: '1000356'
        // });
        this.EncryptTrans = response[0];
        this.MultiAccountInstructionDtls = response[1];
        this.merchIdVal = '1000356';
      }, (error) => {
        //console.error('HTTP Error:', error); 
      });
  }
  async updatePaymentSatus(domain: Domain, paymentStatus) {
    //  domain.paymentStatus='processing'
    domain.paymentStatus = paymentStatus;
    await lastValueFrom(this.domainService.updateDomainDetails(domain)).then(
      (response) => {
        //console.log(response)
        this.domainsDataSource._updateChangeSubscription();
        // this.router.navigate(['/pmnt-sbms'], { queryParams: { domainId: domain.domainId } });
      })
  }

  onSubmit1(): void {
    if (this.paymentForm.valid) {
      const formData = {
        encryptTrans: this.EncryptTrans,
        multiAccountInstructionDtls: this.MultiAccountInstructionDtls,
        merchIdVal: '1000356'
      };
      // Here you can send the form data to the server or perform other actions.
      this.http.post('https://test.sbiepay.sbi/secure/AggregatorHostedListener', formData)
        .subscribe(response => {
          //  //console.log('Payment submitted successfully', response);
        }, error => {
          //  //console.error('Error submitting payment', error);
        });
    }
  }

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

  // returnUrl
  async onSubmit2(domain) {
    const updatedDomainWithActualCost = await this.validateAndPayOnUpdate(domain);
    if (updatedDomainWithActualCost != null) {
      domain = updatedDomainWithActualCost;
    }
    //validate before payement
    //console.log('exe')
    if (domain.applicationStatus === 'Incomplete') {
      this.tostr.warning('You application is incomplete. Click on the application id and Re-submit your appliation to pay.');
      return;
    }
    if (domain.markAsDelete) {
      this.tostr.warning("This domain is marked as delete by the Registrar. Please contact the registrar for further assistance.");
      return;
    }
    //console.log('exe')
    // const isValid = await this.validatePaymentReceiptNumber();
    //console.log(isValid)
    //  //window.confirm('Are you sure you want to submit with the payment?'); 
    // // Step 1: Update Payment Status before submitting
    // if(isValid){
    // domain.paymentReceiptNumber = this.paymentReceiptNumber;
    //console.log(this.domain)


    // // Step 2: Set the return URL before form submission
    // this.returnUrl = window.location.origin + '/applications'; // Example: http://localhost:4200/payment-response
    // this.tostr.success('Payment completed successfully','Success');
    // // Step 3: Submit the form - Payment form will be uncommneted later
    // // const ecomForm = document.forms['ecom'];     
    // // if (ecomForm) {       
    // //   ecomForm.submit(); 
    // // }
    // } 
    // $('#paymentModal').modal('hide'); // Bootstrap jQuery method

    const deptCode = "dr";
    const amountPayable = domain.cost;
    //  const url = "https://registrar.idrbt.ac.in/#/payment-response";
    //const url = "https://registraruat.idrbt.ac.in/api/dr/domain/paymentResponse";

    //SBI api path for regsitrar.idrbt.ac.in build
    //const url = `${environment.paymentURL}/dr/domain/paymentResponse`;

    //sbi api path for oracle migration build
    //const url = 'http://172.27.143.131:9008/dr/domain/paymentResponse';
    const url = environment.paymentUrl;
    //const url = 'https://registrarorc.idrbt.ac.in/payment/dr/domain/paymentResponse';
    //console.log(url);
    const otherDetails = domain.domainId;
    // const otherDetails = domain.domainId+'^'+localStorage.getItem('jwtToken');
    // const paymentData = `${deptCode},${amountPayable},${returnUrl}`;
    // const hash = btoa(paymentData); // Encode data in Base64

    const apiUrl = "https://serpmnt.idrbt.ac.in/pay1/ps/payment";
    // const apiUrl = "http://localhost:18000/ps/testPayment";
    const nameServers = await this.getNameServersOfDomain(domain.domainId);
    if (nameServers.length <= 0) {
      this.tostr.warning("Please Add name servers for the domain before payment.")
      return
    }
    //console.log('exe')
    if (this.isOnboardingDomainPaid == false && (this.onBoardingDomainId != domain.domainId)) {
      this.tostr.warning("Please pay your onboarding domain first")
      return
    }
    const transactionData = {
      transactionId: null,
      orderId: '',
      paymentTransactionId: '',
      amount: domain.cost,
      transactionStatus: 'Transaction Initiated',
      domainId: domain.domainId,
      organisationId: this.organisationId,
      paymentFor: "Domain"
    };
    //save transaction inititaion to transactions_table
    await this.saveTransaction(transactionData);
    await this.updateOngoingTransactionForDomain(domain, this.savedTransaction.transactionId);
    if (environment.isPaymentEnabled) {
      this.http.post<{ redirectUrl: string }>(apiUrl, { deptCode: deptCode, amount: amountPayable, returnUrl: url, otherDetails: otherDetails }).subscribe(response => {
        if (response.redirectUrl) {
          //console.log("Redirecting to Angular page...");
          window.location.href = response.redirectUrl;  // Redirect after receiving JSON response
        }
      });
    } else {
      await this.updatePaymentSatus(domain, 'Payment Completed');
    }

  }

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

  savedTransaction: any = null;
  async saveTransaction(transactionData: any) {
    await lastValueFrom(this.domainApplicationService.saveTransaction(transactionData)).then(
      response => {
        if (response.status === HttpStatusCode.Created) {
          this.savedTransaction = response.body;
        }
      }
    )
  }

  async getNameServersOfDomain(domainId: number): Promise<any[]> {
    const response = await firstValueFrom(this.nameserverService.getNameServersByDomainId(domainId));
    return response.body;
  }
  async submitPayment() {
    //console.log("entered")
    const paymentData = {
      merchantId: "1000605",
      operatingMode: "DOM",
      // merchantKey : "pWhMnIEMc4q6hKdi2Fx50Ii8CKAoSIqv9ScSpwuMHM4=",
      merchantCountry: "IN",
      merchantCurrency: "INR",
      orderAmount: 100,
      otherDetails: "Other",
      successURL: "http://localhost:4200",
      failURL: "http://localhost:4200",
      aggregatorId: "SBIEPAY",
      merchantOrderNo: "12345",
      merchantCustomerID: "12345",
      payMode: "NB",
      // actionUrl: "https://test.sbiepay.sbi/secure/AggregatorHostedListener",
      accessMedium: "ONLINE",
      transactionSource: "ONLINE"
    };
    // const encryptionKey = CryptoJS.lib.WordArray.random(32).toString(CryptoJS.enc.Base64);
    // const dataString = JSON.stringify(paymentData);
    const dataString = `${paymentData.merchantId}|${paymentData.operatingMode}|${paymentData.merchantCountry}|${paymentData.merchantCurrency}|${paymentData.orderAmount}|${paymentData.otherDetails}|${paymentData.successURL}|${paymentData.failURL}|${paymentData.aggregatorId}|${paymentData.merchantOrderNo}|${paymentData.merchantCustomerID}|${paymentData.payMode}|${paymentData.accessMedium}|${paymentData.transactionSource}`;
    //console.log(dataString);
    const key_Array = "pWhMnIEMc4q6hKdi2Fx50Ii8CKAoSIqv9ScSpwuMHM4=";
    const decodedKey = atob(key_Array);  // Decodes Base64 string to a string of bytes
    const keyArray = new Uint8Array(decodedKey.length);
    // const singleRequest = 'Some request data to encrypt';

    // Encrypt the data
    // const encryptedResponse = await this.encrypt(dataString, keyArray);
    //console.log(dataString);
    //console.log(encryptedResponse);

    // const encryptedData = CryptoJS.AES.encrypt(dataString, encryptionKey).toString();
    //console.log(encryptedData);
    // this.EncryptTrans = encryptedResponse;
    // Convert the payment data object to a JSON stringconst dataString = JSON.stringify(paymentData);
    //   this.domainApplicationService.submitPayment({encryptedData}).subscribe(
    //     (response) => {
    //       //console.log('Payment submitted successfully:', response);
    //       // Handle response here, such as redirecting the user or showing a message
    //       window.location.href = response.body;
    //     },
    //     (error) => {
    //       //console.error('Payment submission failed:', error);
    //       // Handle error here, such as displaying an error message
    //     }
    //   );
  }


  formData = {
    encryptTrance: '',
    encryptValue: ''
  };



  onSubmit() {
    // Replace 'YOUR_API_URL' with your actual API endpoint
    const apiUrl = 'https://test.sbiepay.sbi/secure/AggregatorHostedListener';
    const headers = new HttpHeaders({
      'Content-Type': 'application/json',
      // 'Origin': 'http://localhost:4200',
      // 'Referer': 'http://localhost:4200',
    });

    this.http.post(apiUrl, this.formData, { headers })
      .subscribe({
        next: (response) => {
        },
        error: (error) => {
        }
      });
  }
  isOnboardingDomainPaid: boolean = false;
  onBoardingDomainId: number;
  async getAllDomainsListByOrgId(orgId: number) {
    this.isLoadingData = true;
    this.loadPaginationState();
    await lastValueFrom(this.domainService.getAllDomainsByOrgId(orgId)).then(
      (response) => {
        if (response.status === HttpStatusCode.Ok) {
          this.domainsList = response.body;
          if (this.domainsList.length !== 0) {
            const onboardingDomain = this.domainsList.find(domain => domain.isOnboardingDomain === true);
            this.onBoardingDomainId = onboardingDomain.domainId;
            if (onboardingDomain) {
              if (onboardingDomain.paymentStatus == 'Payment Completed' || onboardingDomain.paymentStatus == 'Payment Under Review' || onboardingDomain.paymentStatus == 'Payment Approved') {
                this.isOnboardingDomainPaid = true;
              }
            } else {
              this.isOnboardingDomainPaid = false;
            }
          }
          this.domainsDataSource.data = this.domainsList;
          this.maxDataCount = this.domainsDataSource.data.length
          setTimeout(() => {
            // Set paginator state BEFORE assigning
            this.paginator.pageIndex = this.pageIndex;
            this.paginator.pageSize = this.pageSize;

            // Assign paginator and sort
            this.domainsDataSource.paginator = this.paginator;


            // Force MatPaginator to render correct page
            this.paginator._changePageSize(this.pageSize);

            // Subscribe to future page changes
            this.paginator.page.subscribe((event: PageEvent) => {
              this.handlePageEvent(event);
            });


            //  this.domainsDataSource.sort = this.sort;

          });
          setTimeout(() => {
            this.domainsDataSource.sort = this.sort;
            this.sort.sortChange.subscribe(() => {
              this.savePaginationState();
            });
          });

          this.isLoadingData = false;
        }
      },
      (error) => {
        console.log(error)
        if (error.status === HttpStatusCode.Unauthorized) {
          this.isLoadingData = false;
          this.navigateToSessionTimeout();
        }
      }
    );
  }

  domain: any;
  async getCurrentDomainToPay(domain: any) {
    this.domain = domain;
    try {
      const result = await lastValueFrom(this.nameserverService.getNameServersByDomainId(domain.domainId));
      // Process the result here
      if (result?.body?.length > 0) {
        this.openModal();
      } else {
        this.tostr.warning("Please add name servers")
      }
      return result; // Or do whatever you want with the result

    } catch (error) {
      // Handle errors here
      this.tostr.warning("Please add name servers for the domain and pay")
      throw error; // Or return a default value, or handle the error in another way.
    }
  }

  @ViewChild('paymentModal', { static: false }) paymentModal!: ElementRef;
  //  @ViewChild('incompleteModel', { static: false }) incompleteModel!: ElementRef;

  openModal() {
    $('#paymentModal').modal('show'); // Bootstrap jQuery method
  }

  cancel() {
    this.paymentReceiptNumber = '';
    $('#paymentModal').modal('hide'); // Bootstrap jQuery method
  }

  errorMessage: string = '';
  async validatePaymentReceiptNumber() {
    const alphanumericRegex = /^[a-zA-Z0-9]+$/;

    if (this.paymentReceiptNumber === '') {
      this.errorMessage = 'Payment receipt number cannot be empty.';
      return false;
    } else if (!alphanumericRegex.test(this.paymentReceiptNumber)) {
      this.errorMessage = 'Payment receipt number must contain only letters and numbers.';
      return false;
    } else {
      this.errorMessage = '';
      return true;
    }
  }

  domainListCount: number = 0;
  domainsListOfOrg: any[] = [];
  async getDomainsCountByorgId() {
    //console.log('exe')
    await lastValueFrom(this.domainService.getAllDomainsByOrgId(this.domain.organisationId)).then(
      response => {
        if (response.status === HttpStatusCode.Ok) {
          this.domainsListOfOrg = response.body;
          this.domainListCount = response.body.length;
          //    //console.log("domainListCount",this.domainListCount)

        }
      }
    );
  }

  getStatusColor(status: string): string {
    switch (status) {
      case null:
        return '#FF0000'; // Red for null status
      case this.assetService.Approved:
        return '#00CC00'; // Green
      case this.assetService.Submitted:
        return '#FF6A18'; // Orange
      case this.assetService.Incomplete:
        return '#FF0000';
      case this.assetService.Rejected:
        return '#FF0000';
      case this.assetService.Resubmitted:
        return '#17a2b8';
      default:
        return 'black'; // Default text color
    }
  }
  navigateToOnboarding() {
    $('#incompleteModel').modal('hide');
    this.router.navigateByUrl("rgnt-domains")
  }
  tooltipMessage: string

  getTooltipMessage(status: string): string {
    switch (status) {
      case null:
        return this.assetService.incompleteTooltip;
      case this.assetService.Incomplete:
        return this.assetService.incompleteTooltip;
      case this.assetService.Approved:
        return this.assetService.applicationApprovedToolTip;
      case this.assetService.Submitted:
        return this.assetService.underReviewToolTip;
      case this.assetService.Resubmitted:
        return this.assetService.domainApplicationResubmissionToolTip;
      default:
        return 'No additional information available.';
    }
  }

  pageIndex = 0;
  pageSize = 10;
  private loadPaginationState(): void {
    const savedPageIndex = localStorage.getItem('domainsApplicationPageIndex');
    const savedPageSize = localStorage.getItem('domainsApplicationPageSize');
    const savedSortActive = localStorage.getItem('domainsApplicationSortActive');
    const savedSortDirection = localStorage.getItem('domainsApplicationSortDirection') as SortDirection;

    this.pageIndex = savedPageIndex ? +savedPageIndex : 0;
    this.pageSize = savedPageSize ? +savedPageSize : 10;

    setTimeout(() => {
      if (this.sort) {
        if (savedSortActive && savedSortDirection) {
          this.sort.active = savedSortActive;
          this.sort.direction = savedSortDirection;
        } else {
          // Default sort
          this.sort.active = 'domainId';
          this.sort.direction = 'desc';
        }

        this.sort.sortChange.emit({
          active: this.sort.active,
          direction: this.sort.direction,
        });
      }
    });
  }

  private savePaginationState(): void {
    localStorage.setItem('domainsApplicationPageIndex', this.pageIndex.toString());
    localStorage.setItem('domainsApplicationPageSize', this.pageSize.toString());

    if (this.sort) {
      localStorage.setItem('domainsApplicationSortActive', this.sort.active);
      localStorage.setItem('domainsApplicationSortDirection', this.sort.direction);
    }
  }

  handlePageEvent(event: PageEvent): void {
    this.pageIndex = event.pageIndex;
    this.pageSize = event.pageSize;
    this.savePaginationState();
  }
  resubmitComment: string = ''
  clickedDomain: any
  async openModalForResumbitComment(organisationDetailsId) {
    document.getElementById("resubmitModalOpen").click();
    this.clickedDomain = organisationDetailsId;
  }
 
async updateDomainApplicationStatus(organisationDetailsId: any) {

  console.log(
    'updateDomainApplicationStatus → organisationDetailsId:',
    JSON.parse(JSON.stringify(organisationDetailsId))
  );

  if (organisationDetailsId.paymentStatus === 'Payment Completed') {
    organisationDetailsId.applicationStatus = this.assetService.Resubmitted;
  } else {
    organisationDetailsId.applicationStatus = this.assetService.Incomplete;
  }

  organisationDetailsId.resubmitComments = this.resubmitComment;

  await lastValueFrom(
    this.domainService.updateEntityApprovalDetails(organisationDetailsId)
  ).then((response) => {

    console.log('API response:', response);

    if (response.status === HttpStatusCode.Ok) {
      this.tostr.success('Application asked to resubmit successfully');
      this.clickedDomain = null;
      this.resubmitComment = '';
    }
  });
}


  domainPayment: Domain = null;
  //nameServersCountOfDomain: number = 0;
  async verifyPayment(domain) {
    if (domain.paymentStatus == 'Payment Not Done') {
      this.tostr.warning("Payment status is not under Ready For Payment");
      return;
    }

    if (
      domain.paymentStatus !== 'Payment Completed' &&
      domain.paymentStatus !== 'Payment Under Review' &&
      domain.paymentStatus !== 'Payment Approved'
    ) {
      var nameServerCount = 0;
      nameServerCount = (await this.getNameServersOfDomain(domain.domainId)).length;
      if (nameServerCount > 0) {
        const updatedDomainWithActualCost = await this.validateAndPayOnUpdate(domain);
        if (updatedDomainWithActualCost != null) {
          this.domainPayment = updatedDomainWithActualCost;
          document.getElementById('paymentDetailsModalView').click();
        }
      } else {
        this.tostr.warning('Registrant has not added the name servers yet to view the payment details');
      }
    } else {
      this.domainPayment = domain;
      document.getElementById('paymentDetailsModalView').click();
    }

  }

  domainDetails: any;
  async getDomainByDomainId(organisationDetailsId: number) {
    try {
      const response = await lastValueFrom(
        this.domainService.getDomainByDomainId(organisationDetailsId)
      );
      this.domainDetails = response.body;
    } catch (error: any) {
      console.error('Error fetching domain details:', error);
    }
  }


  isLoading: boolean = false;
  async deleteApplication(domainId: number) {
    this.isLoading = true;
   await this.getDomainByDomainId(domainId);

    if (!this.domainDetails) {
    this.isLoading = false;
    this.tostr.error("Failed to fetch domain details.");
    return;
  }
   console.log("delete Application", this.domainDetails);
    this.isLoading = false;
    const isApplicationApproved =
      this.domainDetails.applicationStatus === this.assetService.Approved;

    const isPaymentApprovedOrCompleted = [
      'Payment Completed',
      'Payment Under Review',
      'Payment Approved'
    ].includes(this.domainDetails.paymentStatus);

    // Stop if domain is already approved
    if (isApplicationApproved) {
      this.tostr.warning("Domain registered in NIXI cannot be deleted.");
      return;
    }

    // Single confirmation for all not-approved applications
    let confirmed = false;
    if (this.domainDetails.isOnboardingDomain) {
      confirmed = window.confirm(
        `⚠️ CRITICAL ACTION ⚠️\n\nDeleting the onboarding (i.e. FIRST) domain application will permanently remove:\n\n• Entity Details & Documents\n• Officials Details & Documents\n• Domain Name\n• Name Servers\n• Name Identifiers\n• DNSSEC Records (if any)\n\n🚨 THIS ACTION CANNOT BE UNDONE 🚨\n\nAre you absolutely sure you want to proceed?`
      );


    } else {
      confirmed = window.confirm(
        `⚠️ CRITICAL ACTION ⚠️\n\nDeleting this domain application will permanently remove:\n\n• Domain Name\n• Name Servers\n• Name Identifiers\n• DNSSEC Records (if any)\n\nThis action cannot be undone.\n\nAre you absolutely sure you want to proceed?`
      );
    }

    if (!confirmed) {
      this.tostr.info("Operation cancelled.");
      return;
    }

    // Double confirmation only if payment status is in the special list
    let doubleConfirmed = true; // default for cases without payment concern
    // if (isPaymentApprovedOrCompleted) {
    if (this.domainDetails.isOnboardingDomain) {
      doubleConfirmed = window.confirm(
        `\n\nAny payment made for this Application will be REFUNDED in Off-line mode separately.\n\nAre you absolutely sure you want to proceed with the deletion?`
      );
    } else {
      doubleConfirmed = window.confirm(
        `\n\nThe Application deletion will not result in any credit for payment made for this.\n\nAre you absolutely sure you want to proceed with the deletion?`
      );
    }



    if (!doubleConfirmed) {
      this.tostr.info("Operation cancelled.");
      return;
    }
    //}

    // Proceed with deletion
    try {
      this.isLoading = true;
      const response = await lastValueFrom(
        this.domainApplicationService.deleteDomainApplication(domainId)
      );
      this.isLoading = false;
      if (response.status === HttpStatusCode.Ok) {
        if (response.body === true) {
          this.tostr.success("Domain application deleted successfully.");
        } else {
          this.tostr.info("Domain application could not be deleted or was already approved.");
        }

        await this.getAllDomainsListByOrgId(0);
      } else {
        this.tostr.error("Unexpected response while deleting domain application.");
      }
    } catch (error: any) {
      console.error("Error deleting domain application:", error);

      if (error.status === HttpStatusCode.Unauthorized) {
        this.navigateToSessionTimeout();

      } else if (error.error && error.error.errorCode === "ERR_ONBOARDING_DOMAIN_MORETHAN_ONE_CODE-1002") {
        // Handle OnboardingDomainDuplicateException (more than one domain)
        this.tostr.error(
          'The registrant has more than one onboarding domain.'
        );

      } else {
        this.tostr.error(
          'Failed to delete domain application. Please try again later.',
          'Error'
        );
      }
    }
    finally {
      this.isLoading = false;
    }
  }

  //organization delete if no domain exists and status says approved or submiteed ?


async deleteEntity(entity: any) {

  const domains = await lastValueFrom(
    this.domainService.getAllDomainsByOrgId(entity.organisationDetailsId)
  );

  // 🟢 CASE 1: Domains exist → use your current function
  if (domains.body && domains.body.length > 0) {

   for (const domain of domains.body) {
  await this.deleteApplication(domain.domainId);
} // your existing function
    return;
  }

  // 🔵 CASE 2: NO domains → delete organisation directly
  const confirmDelete = confirm(
    `⚠️ This will permanently delete the entire organisation and users.\n\nThis action cannot be undone.\n\nProceed?`
  );

  if (!confirmDelete) return;

  try {
    const response = await lastValueFrom(
      this.domainApplicationService.deleteOrganisationIfNoDomains(entity.organisationDetailsId)
    );

    if (response.body) {
      this.tostr.success("Organisation deleted successfully.");
    } else {
      this.tostr.warning("Deletion not allowed.");
    }

    this.getFilteredEntities();

  } catch {
    this.tostr.error("Error deleting organisation.");
  }
}
}