<nav
  class="navbar navbar-expand-lg navbar-light Navbar-top px-0 sticky-top shadow"
>
  <div>
    <a role="button" class="btn-open first ps-3 payment-page-hide">
      <span class="fas fa-bars fa-lg text-secondary"></span>
    </a>
  </div>
  <div
    class="d-flex align-items-center nav-logo-responsive payment-page-remove-link"
  >
    <div
      class="Nvest-Solutions-Priv partnerLogo p-md-0 ps-md-4 py-1 ps-3 textWhtClr"
    >
      <img class="align-self-center contain-fit" />
    </div>
    <div class="textWhtClr m-0 ps-md-3 ps-1 pe-3">
      <img
        src="https://dip.sbigeneral.in/Content/images/PartnerLogo/partner_logo.png"
        style="max-width: 130px"
        class="contain-fit me-auto"
      />
    </div>
    <div class="textWhtClr m-2 ps-md-3 ps-2 pe-3 d-flex justify-content-end">
      <img
        onclick="redirectToDash()"
        src="https://dip.sbigeneral.in/Content/images/logo.svg"
        style="max-width: 120px"
        class="contain-fit cursor-pointer"
      />
    </div>
  </div>
  <div>
    <button
      class="navbar-toggler collapsed border-0 payment-page-hide"
      onclick="$('#page-wrapper').toggleClass('blurContent');"
      type="button"
      data-bs-target="#navbarSupportedContent"
      aria-controls="navbarSupportedContent"
      aria-expanded="false"
      aria-label="Toggle navigation"
      data-bs-toggle="collapse"
    >
      <span class="navbar-toggler-icon"></span>
    </button>
  </div>
  <div class="collapse navbar-collapse" id="navbarSupportedContent">
    <ul
      class="navbar-nav ms-auto bg-white header-navbar"
      style="align-items: center"
    >
      <div id="filter-Drawer" style="display: none">
        <div class="d-flex">
          <div class="drawer-controls d-flex">
            <a
              href="#filterDrawer"
              data-toggle="drawer"
              aria-foldedopen="false"
              aria-controls="filterDrawer"
              class="btnSecondry filter-icon"
            >
              <i class="fa fa-solid fa-filter"></i>
            </a>
          </div>
        </div>
      </div>
      <li class="nav-item ps-3 d-lg-none d-block mt-1">
        <a onclick="redirectHome()" class="waves-effect waves-light">Home</a>
      </li>
      <li class="nav-item ps-3 mt-1" style="display: none" id="optOurPlan">
        <a
          target="_blank"
          onclick="redirectOurPlans()"
          class="waves-effect waves-light"
          >Our Plans</a
        >
      </li>
      <li class="nav-item ps-3 mt-1" style="display: none" id="optRetrieve">
        <a
          target="_blank"
          onclick="redirectRetriveQuote()"
          class="waves-effect waves-light"
          >Retrieve Quote</a
        >
      </li>
      <li class="nav-item ps-3 mt-1" id="contactNumber" style="display: none">
        <div class="fw-bold">For any Assistance</div>
        <div><i class="fa fa-phone"></i>&nbsp &nbsp+0XX-0XXXXXXXX</div>
      </li>
      <li class="nav-item pl-1 mt-1 dropdown hide" id="notificationWrapper">
        <a
          class="fs-20 position-relative overflow-visible"
          data-bs-toggle="dropdown"
        >
          <i class="fa fa-bell-o" id="Notification-icon"></i>
          <span class="notification-badge">&nbsp;</span>
        </a>
        <ul
          class="dropdown-menu dropdown-menu-end ps-0 rounded-0 shadow"
          aria-labelledby="navbarDropdownMenuLink"
          id="noti-content"
          onclick="event.stopPropagation();"
        >
          <li id="notificationText"></li>
        </ul>
      </li>
      <li class="nav-item ps-1 mt-1">
        <a class="fs-20" onclick="redirectToSearch()"
          ><i class="fa fa-search payment-page-hide"></i
        ></a>
      </li>
      <li class="nav-item ps-1 me-2 mt-1 payment-page-hide">
        <a
          href="/Login/Logout"
          id="logoutOption"
          class="fs-20 text-decoration-none"
          ><i class="icon-logout"></i
        ></a>
      </li>
    </ul>
  </div>
</nav>

<div class="col-12 header-title">
  <h5 class="fw-bold mb-0 cursor-pointer" onclick="goBack()">
    <i></i>&nbsp;&nbsp; Limit Allocation Creation
  </h5>
</div>

<div
  class="container-fluid"
  style="
    height: 100vh;
    background: linear-gradient(
      rgb(255, 225, 255),
      rgb(248, 248, 248),
      rgb(156, 240, 255)
    );
  "
>
  <div class="row justify-content-center mt-5 mb-5">
    <div class="col-md-12 col-lg-10">
      <div class="row justify-content-end">
        <div class="col-md-12 col-lg-3">
          <table
            id="filtertable2"
            class="table table-bordered table-striped table-sm"
          >
            <thead>
              <tr>
                <th colspan="7">Parent Info</th>
              </tr>
            </thead>
            <tbody>
              <tr class="parent-info-row" *ngFor="let parent of report1">
                <td
                  colspan="8"
                  style="display: flex; justify-content: space-between"
                >
                  <div class="text-secondary" style="font-weight: bold">
                    Parent Code:
                  </div>
                  <div class="text-primary">{{ parent.imd_PARENT_CODE }}</div>
                </td>
                <td
                  colspan="5"
                  style="display: flex; justify-content: space-between"
                >
                  <div class="text-secondary" style="font-weight: bold">
                    Name:
                  </div>
                  <div class="text-primary">{{ parent.customerName }}</div>
                </td>
                <td
                  colspan="5"
                  style="display: flex; justify-content: space-between"
                >
                  <div class="text-secondary" style="font-weight: bold">
                    Credit Limit:
                  </div>
                  <div class="text-primary">
                    {{ parent.parent_CREDIT_LIMIT | currency : "INR" }}
                  </div>
                </td>
                <td
                  colspan="5"
                  style="display: flex; justify-content: space-between"
                >
                  <div class="text-secondary" style="font-weight: bold">
                    Available Limit:
                  </div>
                  <div class="text-primary">
                    {{ parent.availabaleAmount | currency : "INR" }}
                  </div>
                </td>
                <td
                  colspan="5"
                  style="display: flex; justify-content: space-between"
                >
                  <div class="text-secondary" style="font-weight: bold">
                    Credit Period:
                  </div>
                  <div class="text-primary">{{ parent.creditperiod }}</div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      <div class="d-flex justify-content-between align-items-center mb-3">
        <button
          class="btn btn-primary set-new-limit-btn"
          id="setNewLimitBtn"
          (click)="openPopup()"
        >
          Set New Limit
        </button>
        <div class="button-container">
          <div *ngIf="!showTransactionDetails">
            <button
              class="btn btn-primary set-new-limit-btn"
              id="setNewLimitBtn"
              (click)="showTransactionPopup()"
            >
              View Parent Transaction Details
            </button>
          </div>
          <div *ngIf="showTransactionDetails">
            <button
              class="btn btn-primary go-back-btn"
              id="goBackBtn"
              (click)="goBack()"
            >
              Check Credit Limit
            </button>
          </div>
        </div>
      </div>

      <div *ngIf="showTransactionDetails">
        <mat-form-field>
          <mat-label>Filter</mat-label>
          <input
            matInput
            (keyup)="applyFilter($event)"
            placeholder="Ex. Policy Number"
          />
        </mat-form-field>

        <table
          mat-table
          [dataSource]="dataSource"
          matSort
          class="mat-elevation-z8"
        >
          <ng-container matColumnDef="select">
            <th mat-header-cell *matHeaderCellDef>Select</th>
            <td mat-cell *matCellDef="let transaction">
              <input
                type="checkbox"
                (change)="onCheckboxClick(transaction, $event)"
                [disabled]="transaction.replenish_status === 'Y'"
              />
            </td>
          </ng-container>

          <ng-container matColumnDef="policyNumber">
            <th mat-header-cell *matHeaderCellDef mat-sort-header>
              Policy Number
            </th>
            <td mat-cell *matCellDef="let transaction">
              {{ transaction.policyNumber }}
            </td>
          </ng-container>

          <ng-container matColumnDef="customerName">
            <th mat-header-cell *matHeaderCellDef mat-sort-header>
              Customer Name
            </th>
            <td mat-cell *matCellDef="let transaction">
              {{ transaction.customerName }}
            </td>
          </ng-container>

          <ng-container matColumnDef="quoteNumber">
            <th mat-header-cell *matHeaderCellDef mat-sort-header>
              Quote Number
            </th>
            <td mat-cell *matCellDef="let transaction">
              {{ transaction.quoteNumber }}
            </td>
          </ng-container>

          <ng-container matColumnDef="issuanceDate">
            <th mat-header-cell *matHeaderCellDef mat-sort-header>
              Issuance Date
            </th>
            <td mat-cell *matCellDef="let transaction">
              {{ transaction.insurenceDate | date : "dd-MM-yyyy" }}
            </td>
          </ng-container>

          <ng-container matColumnDef="riskStartDate">
            <th mat-header-cell *matHeaderCellDef mat-sort-header>
              Risk Start Date
            </th>
            <td mat-cell *matCellDef="let transaction">
              {{ transaction.tran_date | date : "dd-MM-yyyy" }}
            </td>
          </ng-container>

          <ng-container matColumnDef="premiumAmount">
            <th mat-header-cell *matHeaderCellDef mat-sort-header>
              Premium Amount
            </th>
            <td mat-cell *matCellDef="let transaction">
              {{ transaction.premium | currency : "INR" }}
            </td>
          </ng-container>

          <ng-container matColumnDef="elapsedDays">
            <th mat-header-cell *matHeaderCellDef mat-sort-header>
              Elapsed Days
            </th>
            <td mat-cell *matCellDef="let transaction">
              {{
                transaction.replenish_status === "Y"
                  ? "0"
                  : transaction.elapsed_days
              }}
            </td>
          </ng-container>

          <ng-container matColumnDef="acdNumber">
            <th mat-header-cell *matHeaderCellDef mat-sort-header>
              ACD Number
            </th>
            <td mat-cell *matCellDef="let transaction">
              {{ transaction.acd_number }}
            </td>
          </ng-container>

          <ng-container matColumnDef="replenishStatus">
            <th mat-header-cell *matHeaderCellDef mat-sort-header>
              Replenish Status
            </th>
            <td
              mat-cell
              *matCellDef="let transaction"
              [ngStyle]="{
                color: transaction.replenish_status === 'Y' ? 'green' : 'red'
              }"
            >
              {{
                transaction.replenish_status === "Y"
                  ? "Success Payment"
                  : "Pending"
              }}
            </td>
          </ng-container>

          <ng-container matColumnDef="replenishDate">
            <th mat-header-cell *matHeaderCellDef mat-sort-header>
              Replenish Date
            </th>
            <td mat-cell *matCellDef="let transaction">
              {{ transaction.replenishDate | date : "dd-MM-yyyy" }}
            </td>
          </ng-container>

          <ng-container matColumnDef="vehicleNo">
            <th mat-header-cell *matHeaderCellDef mat-sort-header>
              Vehicle No
            </th>
            <td mat-cell *matCellDef="let transaction">
              {{ transaction.vehicleNo }}
            </td>
          </ng-container>

          <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
          <tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
        </table>

        <mat-paginator
          [pageSizeOptions]="[5, 10, 25]"
          showFirstLastButtons
        ></mat-paginator>
      </div>

      <app-credit-update-popup
        [isupdatePopupOpen]="isupdatePopupOpen"
        [ImdCode]="selectedImdCode"
        [AgreementCode]="selectedAgreementCode"
        [ACDNumber]="selectedAcdNumber"
        [CreditLimit]="selectedCreditLimit"
        (closePopupEvent)="handlePopupClose()"
      ></app-credit-update-popup>

      <div *ngIf="isDataEmptyMessage" class="required">
        {{ emptyDataMessage }}
      </div>

      <app-makepaymentpopup
        [ispaymentPopupOpen]="ispaymentPopupOpen"
        [totalAmount]="selectedPremiumSum"
        [Amount]="selectedAmount"
        [acdNumber]="lastSelectedAcdNumber"
        [Imd_code]="parentcode"
        [child_code]="childcode"
        [policyNumber]="policynumbers"
        [Agrement_code]="agrementcode"
        [userId]="UserId"
        [insurenceDate]="insurenceDate"
        [tran_date]="tran_date"
        [cdcode]="cdcode"
        (closePopupEvent)="handlePopupClose()"
      ></app-makepaymentpopup>

      <div
        style="
          display: flex;
          justify-content: center;
          margin-top: 15px;
          position: relative;
          z-index: 1;
        "
      >
        <p *ngIf="showTransactionDetails">
          <button
            class="btn btn-primary set-new-limit-btn"
            (click)="openPaymentPopup()"
          >
            Make Payment
          </button>
        </p>
      </div>
    </div>
  </div>

  <div class="footer position-fixed bottom-0 w-100" style="height: 40px">
    <div class="footer-content d-flex flex-column align-items-center pb-1">
      <p class="text-muted mb-1">
        SBIGI does not accept Cash for Premium Payments against the Policy. 2024
        SBI General Insurance Company Limited All Rights Reserved
      </p>
      <div class="d-flex flex-wrap gap-1">
        <span class="text-muted">All Rights Reserved</span>
      </div>
    </div>
  </div>
</div>
import {
  AfterViewInit,
  Component,
  OnChanges,
  OnInit,
  ViewChild,
} from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { CreditCardLimit } from 'src/app/Model/credit-card-limit';
import { NavigationState } from 'src/app/Model/navigation-state';
import { TransactionCard } from 'src/app/Model/transaction-card';
import { CreditCardLimitServiceService } from 'src/app/Services/credit-card-limit-service.service';
import { RedirectServiceService } from 'src/app/Services/redirect-service.service';
import { TranactionCardServiceService } from 'src/app/Services/tranaction-card-service.service';
import { SharedService } from 'src/app/Utill/shared-service.service';
import { encryptText } from 'src/app/Utill/encryption-utill';
import { decryptText } from 'src/app/Utill/decryption-utill';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { FormControl } from '@angular/forms';

@Component({
  selector: 'app-credit-card-limit',
  templateUrl: './credit-card-limit.component.html',
  styleUrls: ['./credit-card-limit.component.css'],
})
export class CreditCardLimitComponent implements OnInit, AfterViewInit {
  dataSource = new MatTableDataSource<any>();
  displayedColumns: string[] = [
    'select',
    'policyNumber',
    'customerName',
    'quoteNumber',
    'issuanceDate',
    'riskStartDate',
    'premiumAmount',
    'elapsedDays',
    'acdNumber',
    'replenishStatus',
    'replenishDate',
    'vehicleNo',
  ];

  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;

  filterControls = {
    policyNumber: new FormControl(''),
    customerName: new FormControl(''),
    quoteNumber: new FormControl(''),
    premiumAmount: new FormControl(''),
    acdNumber: new FormControl(''),
  };

  isPopupOpen = false; // To control popup visibility
  isLoading = false;
  ispaymentPopupOpen = false;
  isupdatePopupOpen = false;
  imdcodeParent: string = '';
  AgreementchildCode: string = '';
  AcdNumbers: string = '';
  selectedTransactions: any[] = [];
  policynumbers: string[] = [];
  selectedAmount: number[] = [];
  selectedPremiumSum: number = 0; // Store the sum of selected premiums
  lastSelectedAcdNumber: string = '';
  agrementcode: string = '';
  insurenceDate: string = '';
  tran_date: string = '';
  cdcode: string = '';
  childcode: string = '';
  parentcode: string = '';
  CreditLimits: number = 0;
  emptyDataMessage: string = '';
  isDataEmptyMessage: boolean = false;
  dataTable: any;
  imdCode: any = '';
  report: any[] = [];
  report1: any[] = [];
  parentCode1: any | null;
  UserId: string = '';
  reporttransaction: any[] = [];

  creditcardLimit: CreditCardLimit = new CreditCardLimit();
  transacationcardLimit: TransactionCard = new TransactionCard();
  navigat: NavigationState = new NavigationState();
  intialrecordcount: number = 0;
  newrecordcount: number = 0;
  transactions: any[] = [];
  showTransactionDetails = false;
  selectedImdCode: string = '';
  selectedAgreementCode: string = '';
  selectedAcdNumber: string = '';
  selectedCreditLimit: number = 0;
  page: number = 1;

  openPopup() {
    this.isPopupOpen = true;
  }

  updateOpenPopup() {
    this.isupdatePopupOpen = true;
  }

  paymentPopupOpen() {
    this.ispaymentPopupOpen = true;
  }

  handlePopupClose() {
    this.isPopupOpen = false;
    this.ispaymentPopupOpen = false;
    this.isupdatePopupOpen = false;
  }

  constructor(
    private Credit: CreditCardLimitServiceService,
    private redirect: RedirectServiceService,
    private sharedService: SharedService,
    private route: ActivatedRoute,
    private routers: Router,
    private Transaction: TranactionCardServiceService
  ) {}

  ngOnInit(): void {
    if (sessionStorage.getItem('isTokenVerified') === 'true') {
      console.log('Token already verified, skipping ngOnInit logic.');
      return;
    }
    this.checkForToken();
  }
  checkForToken() {
    const urlParams = new URLSearchParams(window.location.search);
    const token = urlParams.get('token');

    const activeToken = localStorage.getItem(this.tokenKey);

    // Step 1: Check if token is provided in URL
    if (!token) {
      alert('Token is missing or invalid.');
      this.redirectToError();
      return;
    }

    // Check if the token is already active in another tab
    if (activeToken && activeToken === token) {
      alert('This token is already in use in another tab.');
      this.redirectToError();
      return;
    }

    // Mark the token as active in localStorage
    localStorage.setItem(this.tokenKey, token);
    console.log('Token activated in this tab.');

    // Step 2: Validate token with backend before proceeding
    this.validateTokenWithBackend(token);
  }
  ngAfterViewInit() {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
    this.dataSource.data = this.reporttransaction; // Set initial data for the dataSource
    this.FetchCreditCardPage2(this.parentCode1); // Fetch credit card data
  }

  ngOnChanges(): void {
    this.FetchCreditCardPage2(this.parentCode1);
  }

  FetchCreditCardPage2(imdCode: string) {
    const customKey = new Uint8Array([
      1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
    ]);
    const customIV = new Uint8Array([
      16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1,
    ]);

    // Encrypting the IMD code
    encryptText({ imdCode: imdCode.trim() }, customKey, customIV)
      .then((encryptedResult) => {
        if (encryptedResult) {
          this.Credit.FetchCreditCardDetails(
            encryptedResult.encryptedText,
            encryptedResult.key,
            encryptedResult.base64iv
          ).subscribe({
            next: (data: any[]) => {
              this.newrecordcount = data.length;
              console.log('New record count:', this.newrecordcount);

              if (this.newrecordcount > this.intialrecordcount) {
                console.log('New records found, refreshing the page');
                window.location.reload();
              } else {
                console.log('No new records found');
              }
            },
            error: (error) => {
              console.error('Error fetching new credit card details:', error);
            },
          });
        } else {
          console.error('Encryption failed, no encrypted result returned.');
        }
      })
      .catch((error) => {
        console.error('Encryption error:', error);
      });
  }

  applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    this.dataSource.filter = filterValue.trim().toLowerCase();

    if (this.dataSource.paginator) {
      this.dataSource.paginator.firstPage();
    }
  }

  private redirectTo(url: string) {
    window.location.href = url; // Redirect to the specified URL
  }

  private flag = false;
  private tokenKey = 'activeToken';

  private redirectToError() {
    //window.location.href = 'https://ansappsuat.sbigen.in/PSH/error/'; // Redirect to error page
    window.location.href = 'https://secure.sbigeneral.in/PSH/error/';
  }

  showTransactionPopup(): void {
    // Define custom encryption key and IV
    const customKey = new Uint8Array([
      1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
    ]);
    const customIV = new Uint8Array([
      16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1,
    ]);

    // Set loading state before encryption and backend call
    this.isLoading = true;
    this.imdCode = localStorage.getItem('parentCode');
    // Encrypt the IMD code
    encryptText({ imdCode: this.imdCode.trim() }, customKey, customIV)
      .then((encryptedResult) => {
        if (encryptedResult) {
          this.showTransactionDetails = true;

          // Fetch transaction details from the backend
          this.Transaction.FetchCreditCardDetailss(
            encryptedResult.encryptedText,
            encryptedResult.key,
            encryptedResult.base64iv
          ).subscribe({
            next: (data) => {
              this.isLoading = false; // Stop loading after receiving the response

              if (data.length === 0) {
                // Handle empty data case
                this.emptyDataMessage =
                  'Policy Details Not Found for the provided Agreement_Code.';
                this.isDataEmptyMessage = true;
              } else {
                // Process and display data if available
                this.reporttransaction = data;
                this.refreshDataTable();
                console.log('Data:', data);

                // Reset empty message indicator
                this.isDataEmptyMessage = false;
              }
            },
            error: (error) => {
              this.isLoading = false; // Stop loading if there’s an error
              console.error('Error fetching transaction details:', error);
              if (error.status === 404) {
                alert('Session has been Expired  .');
              } else {
                alert('An error occurred while verifying the token.');
              }
              this.redirectToError();
              // Display error message or handle it as needed
              alert('Error fetching transaction details. Please try again.');
            },
          });
        } else {
          console.error('Encryption failed: No encrypted result.');
          this.isLoading = false; // Stop loading if encryption fails
        }
      })
      .catch((error) => {
        console.error('Error during encryption:', error);
        this.isLoading = false; // Stop loading on encryption error
      });
  }
  goBack() {
    this.FetchCreditCardPage(this.imdCode);
    this.showTransactionDetails = false;
  }
  isReadOnly = false;
  openPaymentPopup() {
    if (this.selectedPremiumSum > 0) {
      this.isReadOnly = true; // Make fields read-only
      this.ispaymentPopupOpen = true; // Open the modal
    } else {
      console.log('No transactions selected for payment');
    }
  }

  // Initialize these arrays somewhere in your component to store checked dates
  checkedTranDates: Date[] = [];
  checkedInsuranceDates: Date[] = [];
  onCheckboxClick(transaction: any, event: any) {
    const premiumvalue = Number(transaction.premium);
    const insurencedate = new Date(transaction.insurenceDate);
    const tranDate = new Date(transaction.tran_date);

    if (event.target.checked) {
      // Add the selected transaction's premium to the total sum
      this.selectedPremiumSum += premiumvalue;

      // Store the acd_number of the current selected transaction
      this.lastSelectedAcdNumber = transaction.acd_number;
      this.parentcode = transaction.imd_parent_code;
      this.agrementcode = transaction.imd_child_code;

      // Add tranDate and insurencedate to the checked lists
      this.checkedTranDates.push(tranDate);
      this.checkedInsuranceDates.push(insurencedate);

      // Add policy number to the list (duplicates are allowed)
      this.policynumbers.push(transaction.policyNumber);

      // Add the premium to the selected amounts list (duplicates are allowed)
      this.selectedAmount.push(transaction.premium);
    } else {
      // Subtract the transaction's premium from the total sum
      this.selectedPremiumSum -= premiumvalue;

      // Remove tranDate and insurencedate from the checked lists
      this.checkedTranDates = this.checkedTranDates.filter(
        (date) => date.getTime() !== tranDate.getTime()
      );
      this.checkedInsuranceDates = this.checkedInsuranceDates.filter(
        (date) => date.getTime() !== insurencedate.getTime()
      );

      // Remove the policy number from the list (only the first match)
      const policyIndex = this.policynumbers.indexOf(transaction.policyNumber);
      if (policyIndex > -1) {
        this.policynumbers.splice(policyIndex, 1);
      }

      // Remove the premium from the selected amounts list (only the first match)
      const premiumIndex = this.selectedAmount.indexOf(transaction.premium);
      if (premiumIndex > -1) {
        this.selectedAmount.splice(premiumIndex, 1);
      }
    }

    // Determine the oldest tranDate and insurencedate among checked policies
    const oldestTranDate =
      this.checkedTranDates.length > 0
        ? new Date(
            Math.min(...this.checkedTranDates.map((date) => date.getTime()))
          )
        : null;
    const oldestInsuranceDate =
      this.checkedInsuranceDates.length > 0
        ? new Date(
            Math.min(
              ...this.checkedInsuranceDates.map((date) => date.getTime())
            )
          )
        : null;

    const formattedOldestTranDate = oldestTranDate
      ? this.formatDate(oldestTranDate)
      : 'N/A';
    const formattedOldestInsuranceDate = oldestInsuranceDate
      ? this.formatDate(oldestInsuranceDate)
      : 'N/A';

    console.log('Selected Total Premium:', this.selectedPremiumSum);
    console.log('Last Selected ACD Number:', this.lastSelectedAcdNumber);
    console.log('Oldest Transaction Date (Checked):', formattedOldestTranDate);
    console.log(
      'Oldest Insurance Date (Checked):',
      formattedOldestInsuranceDate
    );

    // Save oldest dates in localStorage
    localStorage.setItem('oldestTranDate', formattedOldestTranDate);
    localStorage.setItem('oldestInsuranceDate', formattedOldestInsuranceDate);
  }

  formatDate(date: Date): string {
    const day = String(date.getDate()).padStart(2, '0');
    const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are zero-indexed
    const year = date.getFullYear();
    return `${day}-${month}-${year}`;
  }

  FetchParentCardDetails(imdCode: string) {
    const customKey = new Uint8Array([
      1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
    ]);
    const customIV = new Uint8Array([
      16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1,
    ]);

    encryptText({ imdCode: imdCode.trim() }, customKey, customIV)
      .then((encryptedResult) => {
        if (encryptedResult) {
          this.Credit.FetchParentCardDetails(
            encryptedResult.encryptedText,
            encryptedResult.key,
            encryptedResult.base64iv
          ).subscribe({
            next: (data) => {
              this.report1 = data;
              this.refreshDataTable();
              this.isLoading = false;
              this.isDataEmptyMessage = false;
              console.log(this.report1);
              localStorage.setItem('cdcode', this.report1[0].cdcode);
              console.log('cdcode', this.report1[0].cdcode);
            },
            error: (error) => {
              console.error('Error creating Fetch Parent page:', error);
              this.isLoading = false;
            },
          });
        }
      })
      .catch((error) => {
        console.error('Encryption failed:', error);
        this.isLoading = false;
      });
  }

  refreshDataTable(): void {
    if (this.dataTable) {
      this.dataTable.destroy();
      this.dataTable = null;
    }

    // setTimeout(() => {
    //   this.dataTable = ($('#filtertable1')as any).DataTable({
    //     scrollX: true,
    //     scrollY: 250,
    //     paging: true,
    //     ordering: false,
    //     serverSide: false,
    //     stateSave: true, // Prevents auto width adjustment by DataTable
    //   });

    // Use CSS to make the table adjust height and width dynamically
    //   $('#filtertable_wrapper').css({
    //     'width': '100%',   // Full width to accommodate the content
    //     'height': 'auto',  // Automatic height adjustment based on content
    //   });
    // }, 0);
  }

  FetchCreditCardPage1(imdCode: string) {
    const customKey = new Uint8Array([
      1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
    ]);
    const customIV = new Uint8Array([
      16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1,
    ]);

    // Encrypting the IMD code
    encryptText({ imdCode: imdCode.trim() }, customKey, customIV)
      .then((encryptedResult) => {
        if (encryptedResult) {
          this.Credit.FetchCreditCardDetails(
            encryptedResult.encryptedText,
            encryptedResult.key,
            encryptedResult.base64iv
          ).subscribe({
            next: (data: any[]) => {
              this.intialrecordcount = data.length;
              console.log('Initial record count:', this.intialrecordcount);
              // Optionally, you can call FetchCreditCardPage2 here if you want to fetch records immediately after the first call
              this.FetchCreditCardPage2(imdCode);
            },
            error: (error) => {
              console.error(
                'Error fetching initial credit card details:',
                error
              );
            },
          });
        } else {
          console.error('Encryption failed, no encrypted result returned.');
        }
      })
      .catch((error) => {
        console.error('Encryption error:', error);
      });
  }

  FetchCreditCardPage(imdCode: string) {
    const customKey = new Uint8Array([
      1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
    ]);
    const customIV = new Uint8Array([
      16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1,
    ]);

    // Encrypting the IMD code
    encryptText({ imdCode: imdCode.trim() }, customKey, customIV)
      .then((encryptedResult) => {
        if (encryptedResult) {
          this.Credit.FetchCreditCardDetails(
            encryptedResult.encryptedText,
            encryptedResult.key,
            encryptedResult.base64iv
          ).subscribe({
            next: (data) => {
              if (!data || data.length === 0) {
                // Data is empty or not defined
                this.emptyDataMessage =
                  'Policy Details Not Found for the Given Agreement Code.';
                this.isLoading = false;
                this.isDataEmptyMessage = true;
              } else {
                // Data is not empty
                this.report = data;
                // this.refreshDataTable();
                //this.isLoading = false;
                this.isDataEmptyMessage = false;
                console.log('Credit Card Limit:', this.report);
                // Additional logic if needed
              }
            },
            error: (error) => {
              console.error('Error fetching child page:', error);
              if (error.status === 404) {
                alert('Session has been Expired  .');
              } else {
                alert('An error occurred while verifying the token.');
              }
              this.redirectToError();
              // Handle the error as needed
              this.isLoading = false;
              // Optionally display an error message to the user
            },
          });
        } else {
          console.error('Encryption failed, no encrypted result returned.');
          this.isLoading = false; // Ensure loading is stopped if encryption fails
        }
      })
      .catch((error) => {
        console.error('Encryption error:', error);
        this.isLoading = false;
        if (error.status === 403) {
          alert('Access denied: This token has already been used.');
        } else {
          alert('An error occurred while verifying the token.');
        }
        this.redirectToError(); // Ensure loading is stopped if there's an encryption error
      });
  }

  // Load data only after token is verified and a valid parent code is received
  private loadData(parentCode: string) {
    this.parentCode1 = parentCode;
    this.FetchParentCardDetails(this.parentCode1);
    this.FetchCreditCardPage(this.parentCode1);
    this.FetchCreditCardPage1(this.parentCode1);
    // this.FetchCreditCardPage2(this.parentCode1);
  }

  private validateTokenWithBackend(token: string) {
    this.Credit.getDetailsByToken(token).subscribe({
      next: (response) => {
        if (response && typeof response === 'object') {
          const {
            encryptionText: encryptedData,
            base64Key: customKey,
            base64IV: customIV,
          } = response;

          // Use decryptText utility function to decrypt the response
          decryptText(encryptedData, customKey, customIV)
            .then((data) => {
              try {
                const {
                  childCode = null,
                  parentCode = null,
                  userTypeId = null,
                  userId = null,
                } = data;

                // Store necessary data in localStorage and sessionStorage
                localStorage.setItem('UserId', userId);
                localStorage.setItem('userTypeId', userTypeId);
                sessionStorage.setItem('isTokenVerified', 'true'); // Mark token as verified

                // Handle redirection based on userTypeId
                if (userTypeId == 6) {
                  localStorage.setItem('childCode', childCode);
                  this.redirectTo(
                    'https://secure.sbigeneral.in/PSH/creditchild/'
                  );
                  //this.redirectTo('https://ansappsuat.sbigen.in/PSH/creditchild/');
                  //this.redirectTo('http://localhost:4200/creditchild/');
                } else if (userTypeId == 2) {
                  localStorage.setItem('parentCode', parentCode);
                  this.loadData(parentCode);
                } else {
                  console.warn(
                    'Invalid response: Both parentCode and childCode are missing.'
                  );
                  this.redirectToError();
                }
              } catch (error) {
                console.error('Error parsing decrypted data:', error);
                this.redirectToError();
              }
            })
            .catch((error) => {
              console.error('Error decrypting data:', error);
              this.redirectToError();
            });
        } else {
          console.error('No valid data received from backend.');
          this.redirectToError();
        }
      },
      error: (error) => {
        console.error('Error fetching token details from backend:', error);
        if (error.status === 403) {
          alert('Access denied: This token has already been used.');
        } else {
          alert('An error occurred while verifying the token.');
        }
        this.redirectToError(); // Redirect to error on any backend error
      },
    });
  }

  // Other methods (FetchCreditCardPage, FetchCreditCardPage1, etc.) remain unchanged
}
 this is my current html and ts file where data is not populating in table parent info or set new limit is not opening popup which was opening earlier also parent info had Parent Code:,Name:
Credit Limit:Available Limit:Credit Period: below is the code which was earlier working for all the above things which are not working aftrer changing table to sorting and pagination make things work here in the above code and give entire code i am pasting earlier code which was working and dont skip any code while giving code back to me give entire complete working code <nav class="navbar navbar-expand-lg navbar-light Navbar-top px-0 sticky-top shadow">
    <div>
        <a role="button" class="btn-open first ps-3 payment-page-hide"><span
                class="fas fa-bars fa-lg text-secondary"></span></a>
    </div>
    <!-- <div class="d-flex align-items-center nav-logo-responsive payment-page-remove-link">
        <div class="Nvest-Solutions-Priv partnerLogo  p-md-0 ps-md-4 py-1 ps-3 textWhtClr">
            <img onclick="redirectToDash()" class="align-self-center cursor-pointer contain-fit">
        </div>
        <div class="textWhtClr m-0 ps-md-3 ps-1 pe-3">
            
            <img onclick="redirectToDash()" src="/assets/images/simbalogo.png" style=" max-width: 100px;" class="contain-fit cursor-pointer ms-auto">
        </div>

        
        
    </div> -->

    <div class="d-flex align-items-center nav-logo-responsive payment-page-remove-link" >
        <div class="Nvest-Solutions-Priv partnerLogo p-md-0 ps-md-4 py-1 ps-3 textWhtClr">
            <img class="align-self-center contain-fit">
        </div>
        <!-- <div class="textWhtClr m-0 ps-md-3 ps-1 pe-3">
            <img src="/assets/images/simbaaaa.svg" style="max-width: 130px;" class="contain-fit ms-auto">
        </div>

        <div class="textWhtClr m-0 ps-md-3 ps-1 pe-3">
            <img src="/assets/images/simbaaaa.svg" style="max-width: 130px;" class="contain-fit ms-auto">
        </div> -->


        <div class="textWhtClr m-0 ps-md-3 ps-1 pe-3">
            <img
              src="https://dip.sbigeneral.in/Content/images/PartnerLogo/partner_logo.png"
              style="max-width: 130px"
              class="contain-fit me-auto"
            />
          </div>

        <div class="textWhtClr m-0 ps-md-3 ps-1 pe-3"></div>
        <div class="textWhtClr m-0 ps-md-3 ps-1 pe-3"></div>
        <div class="textWhtClr m-0 ps-md-3 ps-1 pe-3"></div>
        <div class="textWhtClr m-0 ps-md-3 ps-1 pe-3"></div>
        <div class="textWhtClr m-0 ps-md-3 ps-1 pe-3"></div>
        <div class="textWhtClr m-0 ps-md-3 ps-1 pe-3"></div>
        <div class="textWhtClr m-0 ps-md-3 ps-1 pe-3"></div>
        <div class="textWhtClr m-0 ps-md-3 ps-1 pe-3"></div>
        <div class="textWhtClr m-0 ps-md-3 ps-1 pe-3"></div>
        <div class="textWhtClr m-0 ps-md-3 ps-1 pe-3"></div>
        
        <div class="textWhtClr m-0 ps-md-3 ps-1 pe-3"></div>
        <div class="textWhtClr m-0 ps-md-3 ps-1 pe-3"></div>
        <div class="textWhtClr m-0 ps-md-3 ps-1 pe-3"></div>
        <div class="textWhtClr m-0 ps-md-3 ps-1 pe-3"></div>
        <div class="textWhtClr m-0 ps-md-3 ps-1 pe-3"></div>
        <div class="textWhtClr m-0 ps-md-3 ps-1 pe-3"></div>
        <div class="textWhtClr m-0 ps-md-3 ps-1 pe-3"></div>
        <div class="textWhtClr m-0 ps-md-3 ps-1 pe-3"></div>
        <div class="textWhtClr m-0 ps-md-3 ps-1 pe-3"></div>
        <div class="textWhtClr m-0 ps-md-3 ps-1 pe-3"></div>
        <div class="textWhtClr m-0 ps-md-3 ps-1 pe-3"></div>
        <div class="textWhtClr m-0 ps-md-3 ps-1 pe-3"></div>
        <div class="textWhtClr m-0 ps-md-3 ps-1 pe-3"></div>
        <div class="textWhtClr m-0 ps-md-3 ps-1 pe-3"></div>
        <div class="textWhtClr m-0 ps-md-3 ps-1 pe-3"></div>
        <div class="textWhtClr m-0 ps-md-3 ps-1 pe-3"></div>
        <div class="textWhtClr m-0 ps-md-3 ps-1 pe-3"></div>
        
       

        <div class="textWhtClr m-2 ps-md-3 ps-2 pe-3 d-flex justify-content-end">
            <img onclick="redirectToDash()" src="https://dip.sbigeneral.in/Content/images/logo.svg"
                style="max-width: 120px;" class="contain-fit cursor-pointer">
        </div>



        <!-- <div class="textWhtClr m-2 ps-md-3 ps-1 pe-3">            
        <img onclick="redirectToDash()" src="https://dip.sbigeneral.in/Content/images/logo.svg" style=" max-width: 100px;" class="contain-fit cursor-pointer ms-auto">
    </div> -->

    </div>


    <div>
        <button class="navbar-toggler collapsed border-0 payment-page-hide"
            onclick="$('#page-wrapper').toggleClass('blurContent');" type="button"
            data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false"
            aria-label="Toggle navigation" data-bs-toggle="collapse">
            <span class="navbar-toggler-icon"></span>

        </button>
    </div>
    <!-- Rest of your navbar code here -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav ms-auto bg-white header-navbar" style="align-items: center;">
            <div id="filter-Drawer" style="display: none">
                <div class="d-flex">
                    <div class="drawer-controls d-flex">
                        <a href="#filterDrawer" data-toggle="drawer" aria-foldedopen="false"
                            aria-controls="filterDrawer" class="btnSecondry filter-icon"><i
                                class="fa fa-solid fa-filter"></i></a>
                    </div>
                </div>
            </div>
            <li class="nav-item ps-3 d-lg-none d-block mt-1">
                <a onclick="redirectHome()" class=" waves-effect waves-light">Home</a>
            </li>
            <li class="nav-item ps-3 mt-1" style="display:none;" id="optOurPlan">
                <a target="_blank" onclick="redirectOurPlans()" class=" waves-effect waves-light">Our Plans</a>
            </li>
            <li class="nav-item ps-3 mt-1" style="display:none;" id="optRetrieve">
                <a target="_blank" onclick="redirectRetriveQuote()" class=" waves-effect waves-light">Retrieve Quote</a>
            </li>
            <li class="nav-item ps-3 mt-1" id="contactNumber" style="display: none;">

                <div class="fw-bold">
                    For any Assistance
                </div>
                <div><i class="fa fa-phone"></i>&nbsp &nbsp+0XX-0XXXXXXXX</div>
            </li>
            <li class="nav-item pl-1 mt-1 dropdown hide" id="notificationWrapper">
                <a class="fs-20 position-relative overflow-visible" data-bs-toggle="dropdown">
                    <i class="fa fa-bell-o" id="Notification-icon"></i>
                    <span class="notification-badge">&nbsp;</span>
                </a>
                <ul class="dropdown-menu dropdown-menu-end ps-0 rounded-0 shadow"
                    aria-labelledby="navbarDropdownMenuLink" id="noti-content" onclick="event.stopPropagation();">


                    <li id="notificationText"></li>
                </ul>
            </li>
            <li class="nav-item ps-1 mt-1">
                <a class="fs-20" onclick="redirectToSearch()"><i class="fa fa-search payment-page-hide"></i></a>
            </li>
            <li class="nav-item ps-1 me-2 mt-1 payment-page-hide">
                <a href="/Login/Logout" id="logoutOption" class="fs-20 text-decoration-none"><i
                        class="icon-logout"></i></a>
            </li>


        </ul>
    </div>
</nav>

<div class="col-12 header-title">
    <h5 class="fw-bold mb-0 cursor-pointer" onclick="goBack()"> <i ></i>
        &nbsp;&nbsp; Limit Allocation Creation </h5>
</div>

<!-- <div class="watermark1"></div> -->

<div class="main-content" >
    <!-- <div id="page-wrapper" class="px-md-4 pb-4 container-fluid">
        <input type="hidden" id="hdnSelectedProdID" value="" />
        <input type="hidden" id="hdnCatID" value="" />
        <input type="hidden" id="hdnProductType" value="" />
        <input type="hidden" id="hdnDashboardData"
            value="[{&quot;ProposalUniqueId&quot;:null,&quot;FK_QuotationId&quot;:null,&quot;IsPaymentDone&quot;:null,&quot;IsPFSubmitted&quot;:null,&quot;IsRenewalDone&quot;:null,&quot;ProductID&quot;:0,&quot;ProductName&quot;:&quot;Super Top Up&quot;,&quot;ProductId&quot;:1016,&quot;ProductCategory&quot;:&quot;HLTH&quot;,&quot;CategoryId&quot;:&quot;INDI&quot;,&quot;ProductURL&quot;:&quot;/Content/images/SuperTopUp.svg&quot;,&quot;QuotationCount&quot;:0,&quot;PendingDocumentCount&quot;:0,&quot;PendingPaymentCount&quot;:0,&quot;UpcomingRenewalCount&quot;:0,&quot;RejectedQuotesCount&quot;:0,&quot;InprogressQuotesCount&quot;:0},{&quot;ProposalUniqueId&quot;:null,&quot;FK_QuotationId&quot;:null,&quot;IsPaymentDone&quot;:null,&quot;IsPFSubmitted&quot;:null,&quot;IsRenewalDone&quot;:null,&quot;ProductID&quot;:0,&quot;ProductName&quot;:&quot;Four Wheeler&quot;,&quot;ProductId&quot;:40001,&quot;ProductCategory&quot;:&quot;MOTO&quot;,&quot;CategoryId&quot;:&quot;1&quot;,&quot;ProductURL&quot;:&quot;/Content/images/fourwheeler.svg&quot;,&quot;QuotationCount&quot;:0,&quot;PendingDocumentCount&quot;:0,&quot;PendingPaymentCount&quot;:0,&quot;UpcomingRenewalCount&quot;:0,&quot;RejectedQuotesCount&quot;:0,&quot;InprogressQuotesCount&quot;:0}]" />
        <input type="hidden" id="hdnPassword" />
        <input type="hidden" id="hdnUserType" value="1" />
    


    </div> -->


</div>



<!-- <div class="loader-bg hide">
    <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel" data-pause="false" data-interval="2500" data-wrap="true">
        <div class="carousel-inner">
            <div class="carousel-item active">
                <div class="loader-bor">
                    <i class="fa fa-spinner fa-spin" style="font-size:24px"></i>
                </div>
                <div class="f-18 fw-bold text-sentence-case mt-3">Please wait it may take few Moments.</div>
            </div>
        </div>
    </div>
</div> -->


<!-- 

<!-- <div class="container-fluid">
    <div class="row justify-content-center mt-5 mb-5">
        <div class="col-md-12 col-lg-10">
            
            
            <div class="d-flex justify-content-between align-items-center mb-3">
                <button class="btn btn-primary" id="setNewLimitBtn">Set New Limit</button>
            </div>

            <table id="filtertable1" class="table table-bordered table-striped table-sm">
                <thead>
                    <tr class="header">
                        <th class="th-sm text-center" style="border-right: 1px solid #ffffffff; border-left: 1px solid #4e73df;">IMD Code</th>
                        <th class="th-sm text-center" style="border-right: 1px solid #ffffffff; border-left: 1px solid #4e73df;">Child Code</th>
                        <th class="th-sm text-center" style="border-right: 1px solid #ffffffff; border-left: 1px solid #4e73df;">Name</th>
                        <th class="th-sm text-center" style="border-right: 1px solid #ffffffff; border-left: 1px solid #4e73df;">ACD Number</th>
                        <th class="th-sm text-center" style="border-right: 1px solid #ffffffff; border-left: 1px solid #4e73df;">Credit Limit</th>
                        <th class="th-sm text-center" style="border-right: 1px solid #ffffffff; border-left: 1px solid #4e73df;">Available Limit</th>
                        <th class="th-sm text-center" style="border-right: 1px solid #ffffffff; border-left: 1px solid #4e73df;">Activation Status</th>
                        <th class="th-sm text-center" style="border-right: 1px solid #ffffffff; border-left: 1px solid #4e73df;">Action</th>
                    </tr>
                </thead>
                <tbody id="dataTableBody">
                    
                </tbody>
            </table>
        </div>
    </div>
</div>  -->


<div class="container-fluid"  style="height: 100vh; background: linear-gradient(rgb(255, 225, 255),rgb(248, 248, 248),rgb(156, 240, 255));">
    <div class="row justify-content-center mt-5 mb-5">
        <div class="col-md-12 col-lg-10">

            <div class="d-flex justify-content-between align-items-center mb-3"></div>

            

            <!-- <div class="d-flex justify-content-between align-items-center mb-3">
                <button class="btn btn-primary" id="setNewLimitBtn">Set New Limit</button>
            </div> -->

            

            <div class="d-flex justify-content-between align-items-center mb-3">
                <button class="btn btn-primary set-new-limit-btn" id="setNewLimitBtn" (click)="openPopup()">Set New Limit</button>
                <!-- <button class="btn btn-primary set-new-limit-btn" id="setNewLimitBtn" (click)="showTransactionPopup()">View Transaction Details</button> -->
                <div class="button-container">
                    <div *ngIf="!showTransactionDetails">
                      <button
                        class="btn btn-primary set-new-limit-btn"
                        id="setNewLimitBtn"
                        (click)="showTransactionPopup()"
                      >
                        View Parent Transaction Details
                      </button>
                    </div>
                    <div *ngIf="showTransactionDetails">
                      <button
                        class="btn btn-primary go-back-btn"
                        id="goBackBtn"
                        (click)="goBack()"
                      >
                        Check Credit Limit
                      </button>
                    </div>
                  </div>
                
                <div class="container-fluid">
                    <div class="row justify-content-end">
                        <div class="col-md-12 col-lg-3">
                            <table id="filtertable2" class="table table-bordered table-striped table-sm" >
                                <thead>
                                    <tr  >
                                        <th colspan="7">Parent Info</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr class="parent-info-row " *ngFor="let item1 of report1; let i = index">
                                        <td colspan="8" style="display: flex; justify-content: space-between;">
                                            <div class="text-secondary" style="font-weight: bold;">Parent Code:</div>
                                            <div class="text-primary">{{item1.imd_PARENT_CODE}}</div>
                                        </td>
                                        <td colspan="5" style="display: flex; justify-content: space-between;">
                                            <div class="text-secondary" style="font-weight: bold;">Name:</div>
                                            <div class="text-primary">{{item1.customerName}}</div>
                                        </td>
                                        <td colspan="5" style="display: flex; justify-content: space-between;">
                                            <div class="text-secondary" style="font-weight: bold;">Credit Limit:</div>
                                            <div class="text-primary">{{item1.parent_CREDIT_LIMIT|currency:'INR' }}</div>
                                        </td>
                                        <td colspan="5" style="display: flex; justify-content: space-between;">
                                            <div class="text-secondary" style="font-weight: bold;">Available Limit:</div>
                                            <div class="text-primary">{{item1.availabaleAmount|currency:'INR'}}</div>
                                        </td>
                                        <td colspan="5" style="display: flex; justify-content: space-between;">
                                            <div class="text-secondary" style="font-weight: bold;">Credit Period:</div>
                                            <div class="text-primary">{{item1.creditperiod}}</div>
                                        </td>
                                    </tr>
                                    
                                    <!-- Existing child rows -->
                                   
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            

            
            <app-creditlimit-popup [isPopupOpen]="isPopupOpen" (closePopupEvent)="handlePopupClose()"></app-creditlimit-popup>

            <!-- <div class="d-flex justify-content-between align-items-center mb-3">
                <button class="btn btn-primary" id="setNewLimitBtn" (click)="openNewLimitDialog()">Set New Limit</button>
            </div> -->

            <div class="d-flex justify-content-between align-items-center mb-3"></div>

            

            <!-- <button type="button" class="btnPrimary p-ripple me-2 " id="refreshDash">
                Refresh Dashboard
            </button> -->

            <!-- <div class="d-flex justify-content-between align-items-center mb-3">
                <button class="btn btn-16" id="setNewLimitBtn">Set New Limit</button>
            </div> -->


            <table id="filtertable1" class="table table-bordered table-striped table-sm">
                <thead>
                    <tr class="header">
                      <!-- Original Table Headers -->
                      <th *ngIf="!showTransactionDetails" class="th-sm text-center" style="border-right: 1px solid #ffffffff; border-left: 1px solid #4e73df;">Child  Code</th>
                      <th *ngIf="!showTransactionDetails" class="th-sm text-center" style="border-right: 1px solid #ffffffff; border-left: 1px solid #4e73df;">Name</th>
                      <th *ngIf="!showTransactionDetails" class="th-sm text-center" style="border-right: 1px solid #ffffffff; border-left: 1px solid #4e73df;">ACD Number</th>
                      <th *ngIf="!showTransactionDetails" class="th-sm text-center" style="border-right: 1px solid #ffffffff; border-left: 1px solid #4e73df;">Allocate Limit(INR)</th>
                      <th *ngIf="!showTransactionDetails" class="th-sm text-center" style="border-right: 1px solid #ffffffff; border-left: 1px solid #4e73df;">Used Limit(INR)</th>
                      <th *ngIf="!showTransactionDetails" class="th-sm text-center" style="border-right: 1px solid #ffffffff; border-left: 1px solid #4e73df;">Balance Limit(INR)</th>
                       <th *ngIf="!showTransactionDetails" class="th-sm text-center" style="border-right: 1px solid #ffffffff; border-left: 1px solid #4e73df;">Credit Days</th> 
                      <th *ngIf="!showTransactionDetails" class="th-sm text-center" style="border-right: 1px solid #ffffffff; border-left: 1px solid #4e73df;">Edit Action</th>
                      <th *ngIf="!showTransactionDetails" class="th-sm text-center" style="border-right: 1px solid #ffffffff; border-left: 1px solid #4e73df;">View Transaction</th>
                
                      <!-- New Table Headers -->
                      <th *ngIf="showTransactionDetails" class="th-sm text-center" style="border-right: 1px solid #ffffffff; border-left: 1px solid #4e73df;">Select</th>
                      <!-- <th *ngIf="showTransactionDetails" class="th-sm text-center" style="border-right: 1px solid #ffffffff; border-left: 1px solid #4e73df;">Tran ID</th> -->
                      <th *ngIf="showTransactionDetails" class="th-sm text-center" style="border-right: 1px solid #ffffffff; border-left: 1px solid #4e73df;">Policy Number</th>
                      <th *ngIf="showTransactionDetails" class="th-sm text-center" style="border-right: 1px solid #ffffffff; border-left: 1px solid #4e73df;">Customer Name</th>
                      <th *ngIf="showTransactionDetails" class="th-sm text-center" style="border-right: 1px solid #ffffffff; border-left: 1px solid #4e73df;">Quote Number</th>
                      <th *ngIf="showTransactionDetails" class="th-sm text-center" style="border-right: 1px solid #ffffffff; border-left: 1px solid #4e73df;">Issuance Date</th>
                      <th *ngIf="showTransactionDetails" class="th-sm text-center" style="border-right: 1px solid #ffffffff; border-left: 1px solid #4e73df;">Risk Start Date</th>
                      <th *ngIf="showTransactionDetails" class="th-sm text-center" style="border-right: 1px solid #ffffffff; border-left: 1px solid #4e73df;">Premium Amount</th>
                      <th *ngIf="showTransactionDetails" class="th-sm text-center" style="border-right: 1px solid #ffffffff; border-left: 1px solid #4e73df;">Elapsed Days</th>
                      <th *ngIf="showTransactionDetails" class="th-sm text-center" style="border-right: 1px solid #ffffffff; border-left: 1px solid #4e73df;">ACD Number</th>
                      <th *ngIf="showTransactionDetails" class="th-sm text-center" style="border-right: 1px solid #ffffffff; border-left: 1px solid #4e73df;">Replenish Status</th>
                      <th *ngIf="showTransactionDetails" class="th-sm text-center" style="border-right: 1px solid #ffffffff; border-left: 1px solid #4e73df;">Replenish Date</th>
                      <th *ngIf="showTransactionDetails" class="th-sm text-center" style="border-right: 1px solid #ffffffff; border-left: 1px solid #4e73df;">Vehicle No</th> 
                    </tr>
                  </thead>
                  <tbody *ngIf="!showTransactionDetails">
                    <tr *ngFor="let item of report ">
                      <td class="text-center owner-account text-font" style="border: 1px solid #858796;">{{item.imd_child_code}}</td>
                      <td class="text-center text-font" style="border: 1px solid #858796;width: 10px;">{{item.imd_Name}}</td>
                      <td class="text-center text-font" style="border: 1px solid #858796;">{{item.acd_number}}</td>
                      <td class="text-center text-font" style="border: 1px solid #858796;">{{item.credit_Limit|currency:'INR'}}</td>
                      <td class="text-center text-font" style="border: 1px solid #858796;">{{item.usedLimit|currency:'INR'}}</td>
                      <td class="text-center text-font" style="border: 1px solid #858796;">{{item.balanceLimit|currency:'INR'}}</td>
                      <td class="text-center text-font" style="border: 1px solid #858796;">{{item.credit_period}}</td>
                      <!-- <td class="text-center text-font" style="border: 1px solid #858796;"
                        [ngStyle]="{'color': item.active_status === 'ACTIVE'? 'green' :'red'}">{{ item.active_status }}</td> -->
                        <td class="text-center" style="border: 1px solid #858796;">
                            <button (click)="openPopupForEdit(item)">
                              <p class="required"><i class="fas fa-edit"></i></p>
                            </button>
                        </td>
                           
                          
                      <td class="text-center" style="border: 1px solid #858796;">
                        <button class="button-solid" (click)="navigateToTransaction(item)"
                               >
                          <p class="required"><i class="fas fa-eye"></i></p>
                        </button>
                      </td>
                    </tr>
                  </tbody>
                  <tbody *ngIf="showTransactionDetails">
                    <tr *ngFor="let transaction of reporttransaction | paginate: { itemsPerPage: 5, currentPage: page }">
                        <td class="text-center text-font" style="border: 1px solid #858796;">
                            <input
                              type="checkbox"
                              (change)="onCheckboxClick(transaction, $event)"
                              [disabled]="transaction.replenish_status === 'Y'"
                            >
                          </td>
                      <!-- <td class="text-center text-font" style="border: 1px solid #858796;">{{transaction.tran_id}}</td> -->
                      <td class="text-center text-font" style="border: 1px solid #858796;">{{transaction.policyNumber}}</td>
                      <td class="text-center text-font" style="border: 1px solid #858796;">{{transaction.customerName }}</td>
                      <td class="text-center text-font" style="border: 1px solid #858796;">{{transaction.quoteNumber}}</td>
                      <td class="text-center text-font" style="border: 1px solid #858796;">{{transaction.insurenceDate| date: 'dd-MM-yyyy'}}</td>
                      <td class="text-center text-font" style="border: 1px solid #858796;">{{transaction.tran_date| date: 'dd-MM-yyyy'}}</td>
                      <td class="text-center text-font" style="border: 1px solid #858796;">{{transaction.premium|currency:'INR'}}</td>
                      <td class="text-center text-font" style="border: 1px solid #858796;">{{transaction.replenish_status === 'Y' ? '0' : transaction.elapsed_days}}</td> 
                      <td class="text-center text-font" style="border: 1px solid #858796;"align-items="Rights">{{transaction.acd_number}}</td>
                      <td class="text-center text-font" style="border: 1px solid #858796;"
                      [ngStyle]="{'color': transaction.replenish_status === 'Y' ? 'green' : 'red'}">
                      {{ transaction.replenish_status === 'Y' ? 'Success Payment' : 'Pending' }}
                    </td>
                    <td class="text-center text-font" style="border: 1px solid #858796;"
                      [ngStyle]="{'color': transaction.replenish_status === 'Y' ? 'green' : 'red'}">
                      {{ transaction.replenishDate | date: 'dd-MM-yyyy'}}
                    </td>
                    <td class="text-center text-font" style="border: 1px solid #858796;">{{transaction.vehicleNo}}</td>
                    </tr>
                  </tbody>
            </table>
        </div>
            <div *ngIf="showTransactionDetails" style="display: flex; justify-content: flex-end; margin-top: 5px;">
                <pagination-controls (pageChange)="onPageChange($event)"></pagination-controls>
              </div>
             

            
     <app-credit-update-popup
  [isupdatePopupOpen]="isupdatePopupOpen"
  [ImdCode]="selectedImdCode"
  [AgreementCode]="selectedAgreementCode"
  [ACDNumber]="selectedAcdNumber"
  [CreditLimit]="selectedCreditLimit"
  (closePopupEvent)="handlePopupClose()">
</app-credit-update-popup>
</div>
    <div *ngIf="isDataEmptyMessage" class="required">{{emptyDataMessage}}</div>
    
    
        <app-makepaymentpopup
        [ispaymentPopupOpen]="ispaymentPopupOpen"
        [totalAmount]="selectedPremiumSum"
        [Amount]="selectedAmount"
        [acdNumber]="lastSelectedAcdNumber"
        [Imd_code]="parentcode"
        [child_code]="childcode"
        [policyNumber]="policynumbers"
        [Agrement_code]="agrementcode"
        [userId]="UserId"
        [insurenceDate]="insurenceDate"
        [tran_date]="tran_date"
        [cdcode]="cdcode"
        (closePopupEvent)="handlePopupClose()">
      </app-makepaymentpopup>
   
      <div style="display: flex; justify-content: center; margin-top: 15px;position: relative;z-index: 1;">
        <p *ngIf="showTransactionDetails">         
        <button  class="btn btn-primary set-new-limit-btn" (click)="openPaymentPopup()">Make Payment</button>
        </p></div>
    </div>
<div class="footer position-fixed bottom-0 w-100" style="height: 40px;">
    <div class="footer-content d-flex flex-column align-items-center pb-1">
        <p class="text-muted mb-1">SBIGI does not accept Cash for Premium Payments against the Policy. 2024 SBI General Insurance Company Limited All Rights Reserved</p>
        <div class="d-flex flex-wrap gap-1">
            <!-- <span class="text-muted">&copy; 2024 SBI General Insurance Company Limited</span> -->
            <span class="text-muted">All Rights Reserved</span>
        </div>
    </div>
</div>import { Component, OnChanges, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { CreditCardLimit } from 'src/app/Model/credit-card-limit';
import { NavigationState } from 'src/app/Model/navigation-state';
import { TransactionCard } from 'src/app/Model/transaction-card';
import { CreditCardLimitServiceService } from 'src/app/Services/credit-card-limit-service.service';
import { RedirectServiceService } from 'src/app/Services/redirect-service.service';
import { TranactionCardServiceService } from 'src/app/Services/tranaction-card-service.service';
import { SharedService } from 'src/app/Utill/shared-service.service';
import { encryptText } from 'src/app/Utill/encryption-utill';
import { decryptText } from 'src/app/Utill/decryption-utill';
@Component({
  selector: 'app-credit-card-limit',
  templateUrl: './credit-card-limit.component.html',
  styleUrls: ['./credit-card-limit.component.css']
})
export class CreditCardLimitComponent implements OnInit,OnChanges {

  isPopupOpen = false; // To control popup visibility
  isLoading = false; 
  ispaymentPopupOpen=false;
  isupdatePopupOpen=false;
  imdcodeParent:string='';
  AgreementchildCode:string='';
  AcdNumbers:string='';
  selectedTransactions: any[] = []; 
  policynumbers:string[]=[];
  selectedAmount:number[]=[];
  selectedPremiumSum: number = 0;  // Store the sum of selected premiums
  lastSelectedAcdNumber: string = '';
  agrementcode:string='';
  insurenceDate:string='';
  tran_date:string='';
  cdcode:string='';
  childcode:string='';
  parentcode:string='';
  CreditLimits:number=0;
  emptyDataMessage:string='';
  isDataEmptyMessage:boolean=false;
  dataTable: any;
  imdCode:any='';
  report:any[]=[];
  report1:any[]=[];
  parentCode1:any|null;
  UserId:string='';
  reporttransaction:any[]=[];
  
creditcardLimit:CreditCardLimit= new CreditCardLimit();
transacationcardLimit:TransactionCard= new TransactionCard();
 navigat:NavigationState=new  NavigationState();
intialrecordcount:number=0;
newrecordcount:number=0;
transactions: any[] = [];
showTransactionDetails = false;
  selectedImdCode: string = '';
  selectedAgreementCode: string = '';
  selectedAcdNumber: string = '';
  selectedCreditLimit: number = 0;
  page:number=1;
  onPageChange(pageNumber: any) {
    this.page = pageNumber;
  }

  openPopup() {
    this.isPopupOpen = true;
    
  }
  updateopenPopup(){
    this.isupdatePopupOpen=true;
  }
  paymentPopupOpen(){
    this.ispaymentPopupOpen=true;
  }
  handlePopupClose() {
    this.isPopupOpen = false;
    this.ispaymentPopupOpen=false;
    this.isupdatePopupOpen=false;
  }
  //parentcode:string='41';
constructor(private Credit:CreditCardLimitServiceService, private redirect:RedirectServiceService,private sharedService: SharedService,private route:ActivatedRoute,private routers:Router,private Transaction:TranactionCardServiceService){

}
private flag=false;
private tokenKey = 'activeToken'; 

ngOnInit(): void {
  if (sessionStorage.getItem('isTokenVerified') === 'true') {
    console.log("Token already verified, skipping ngOnInit logic.");
    return;
  }
  this.checkForToken();
  
}
ngAfterViewInit()
{
  this.FetchCreditCardPage2(this.parentCode1);

}
 ngOnChanges():void{
this.FetchCreditCardPage2(this.parentCode1);
 }

ngOnDestroy(): void {
  if (this.dataTable) {
    this.dataTable.destroy();
  }
  
}


refreshDataTable(): void {
  if (this.dataTable) {
    this.dataTable.destroy();
    this.dataTable=null;
  }

  // setTimeout(() => {
  //   this.dataTable = ($('#filtertable1')as any).DataTable({
  //     scrollX: true,
  //     scrollY: 250,
  //     paging: true,
  //     ordering: false,
  //     serverSide: false,
  //     stateSave: true, // Prevents auto width adjustment by DataTable
  //   });
  
    // Use CSS to make the table adjust height and width dynamically
  //   $('#filtertable_wrapper').css({
  //     'width': '100%',   // Full width to accommodate the content
  //     'height': 'auto',  // Automatic height adjustment based on content
  //   });
  // }, 0);
}




goBack() {
  this.FetchCreditCardPage(this.imdCode);
  this.showTransactionDetails = false;
}

checkForToken() {
  const urlParams = new URLSearchParams(window.location.search);
  const token = urlParams.get('token');

  const activeToken = localStorage.getItem(this.tokenKey);

  // Step 1: Check if token is provided in URL
  if (!token) {
    alert("Token is missing or invalid.");
    this.redirectToError();
    return;
  }

  // Check if the token is already active in another tab
  if (activeToken && activeToken === token) {
    alert('This token is already in use in another tab.');
    this.redirectToError();
    return;
  }

  // Mark the token as active in localStorage
  localStorage.setItem(this.tokenKey, token);
  console.log('Token activated in this tab.');
 
  // Step 2: Validate token with backend before proceeding
  this.validateTokenWithBackend(token);
}

private validateTokenWithBackend(token: string) {
  this.Credit.getDetailsByToken(token).subscribe({
    next: (response) => {
      if (response && typeof response === 'object') {
        const { encryptionText: encryptedData, base64Key: customKey, base64IV: customIV } = response;

        // Use decryptText utility function to decrypt the response
        decryptText(encryptedData, customKey, customIV)
          .then((data) => {
            try {
              const { childCode = null, parentCode = null, userTypeId = null, userId = null } = data;

              // Store necessary data in localStorage and sessionStorage
              localStorage.setItem('UserId', userId);
              localStorage.setItem('userTypeId', userTypeId);
              sessionStorage.setItem('isTokenVerified', 'true'); // Mark token as verified

              // Handle redirection based on userTypeId
              if (userTypeId == 6) {
                localStorage.setItem('childCode', childCode);
               this.redirectTo('https://secure.sbigeneral.in/PSH/creditchild/');
                //this.redirectTo('https://ansappsuat.sbigen.in/PSH/creditchild/');
                //this.redirectTo('http://localhost:4200/creditchild/');
              } else if (userTypeId == 2) {
                localStorage.setItem('parentCode', parentCode);
                this.loadData(parentCode);
              } else {
                console.warn("Invalid response: Both parentCode and childCode are missing.");
                this.redirectToError();
              }
            } catch (error) {
              console.error("Error parsing decrypted data:", error);
              this.redirectToError();
            }
          })
          .catch((error) => {
            console.error("Error decrypting data:", error);
            this.redirectToError();
          });
      } else {
        console.error("No valid data received from backend.");
        this.redirectToError();
      }
    },
    error: (error) => {
      console.error("Error fetching token details from backend:", error);
      if (error.status === 403) {
        alert("Access denied: This token has already been used.");
      } else {
        alert("An error occurred while verifying the token.");
      }
      this.redirectToError(); // Redirect to error on any backend error
    },
  });
}


// Load data only after token is verified and a valid parent code is received
private loadData(parentCode: string) {
  this.parentCode1 = parentCode;
  this.FetchParentCardDetails(this.parentCode1);
  this.FetchCreditCardPage(this.parentCode1);
  this.FetchCreditCardPage1(this.parentCode1);
 // this.FetchCreditCardPage2(this.parentCode1);
  
}

private redirectTo(url: string) {
  window.location.href = url; // Redirect to the specified URL
}

private redirectToError() {
  //window.location.href = 'https://ansappsuat.sbigen.in/PSH/error/'; // Redirect to error page
window.location.href='https://secure.sbigeneral.in/PSH/error/';


}


openPopupForEdit(item: any) {
  this.selectedImdCode = item.imd_paraent_code;
  this.selectedAgreementCode = item.imd_child_code  ; // Assuming 'name' is used for Agreement Code, adjust as needed
  this.selectedAcdNumber = item.acd_number;
  this.selectedCreditLimit = item.credit_Limit;

  // Open the popup
  this.isupdatePopupOpen = true;
}


FetchParentCardDetails(imdCode: string) {
  const customKey = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]);
  const customIV = new Uint8Array([16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]);

  encryptText({ imdCode: imdCode.trim() }, customKey, customIV).then((encryptedResult) => {
    if (encryptedResult) {
      this.Credit.FetchParentCardDetails(encryptedResult.encryptedText,encryptedResult.key,encryptedResult.base64iv).subscribe({
        next: (data) => {
          this.report1 = data;
          this.refreshDataTable();
          this.isLoading = false;
          this.isDataEmptyMessage = false;
          console.log(this.report1);
          localStorage.setItem('cdcode', this.report1[0].cdcode);
          console.log("cdcode",this.report1[0].cdcode);
        },
        error: (error) => {
          console.error('Error creating Fetch Parent page:', error);
          this.isLoading = false;
        }
      });
    }
  }).catch((error) => {
    console.error('Encryption failed:', error);
    this.isLoading = false;
  });
}

FetchCreditCardPage1(imdCode: string) {
  const customKey = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]);
  const customIV = new Uint8Array([16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]);

  // Encrypting the IMD code
  encryptText({ imdCode: imdCode.trim() }, customKey, customIV).then((encryptedResult) => {
    if (encryptedResult) {
      this.Credit.FetchCreditCardDetails(encryptedResult.encryptedText, encryptedResult.key, encryptedResult.base64iv).subscribe({
        next: (data: any[]) => {
          this.intialrecordcount = data.length;
          console.log("Initial record count:", this.intialrecordcount);
          // Optionally, you can call FetchCreditCardPage2 here if you want to fetch records immediately after the first call
          this.FetchCreditCardPage2(imdCode);
        },
        error: (error) => {
          console.error("Error fetching initial credit card details:", error);
        }
      });
    } else {
      console.error("Encryption failed, no encrypted result returned.");
    }
  }).catch((error) => {
    console.error("Encryption error:", error);
  });
}

FetchCreditCardPage2(imdCode: string) {
  const customKey = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]);
  const customIV = new Uint8Array([16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]);

  // Encrypting the IMD code
  encryptText({ imdCode: imdCode.trim() }, customKey, customIV).then((encryptedResult) => {
    if (encryptedResult) {
      this.Credit.FetchCreditCardDetails(encryptedResult.encryptedText, encryptedResult.key, encryptedResult.base64iv).subscribe({
        next: (data: any[]) => {
          this.newrecordcount = data.length;
          console.log("New record count:", this.newrecordcount);

          if (this.newrecordcount > this.intialrecordcount) {
            console.log("New records found, refreshing the page");
            window.location.reload();
          } else {
            console.log("No new records found");
          }
        },
        error: (error) => {
          console.error("Error fetching new credit card details:", error);
        }
      });
    } else {
      console.error("Encryption failed, no encrypted result returned.");
    }
  }).catch((error) => {
    console.error("Encryption error:", error);
  });
}

    FetchCreditCardPage(imdCode: string) {
      const customKey = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]);
      const customIV = new Uint8Array([16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]);
    
      // Encrypting the IMD code
      encryptText({ imdCode: imdCode.trim() }, customKey, customIV).then((encryptedResult) => {
        if (encryptedResult) {
          this.Credit.FetchCreditCardDetails(encryptedResult.encryptedText, encryptedResult.key, encryptedResult.base64iv).subscribe({
            next: (data) => {
              if (!data || data.length === 0) {
                // Data is empty or not defined
                this.emptyDataMessage = 'Policy Details Not Found for the Given Agreement Code.';
                this.isLoading = false;
                this.isDataEmptyMessage = true;
              } else {
                // Data is not empty
                this.report = data;
               // this.refreshDataTable();
                //this.isLoading = false;
                this.isDataEmptyMessage = false;
                console.log('Credit Card Limit:', this.report);
                // Additional logic if needed
              }
            },
            error: (error) => {
              console.error('Error fetching child page:', error);
              if (error.status === 404) {
                alert("Session has been Expired  .");
              } else {
                alert("An error occurred while verifying the token.");
              }
              this.redirectToError();
              // Handle the error as needed
              this.isLoading = false;
              // Optionally display an error message to the user
            }
          });
        } else {
          console.error('Encryption failed, no encrypted result returned.');
          this.isLoading = false; // Ensure loading is stopped if encryption fails
        }
      }).catch((error) => {
        console.error("Encryption error:", error);
        this.isLoading = false; 
        if (error.status === 403) {
          alert("Access denied: This token has already been used.");
        } else {
          alert("An error occurred while verifying the token.");
        }
        this.redirectToError();// Ensure loading is stopped if there's an encryption error
      });
    }
 
    showTransactionPopup(): void {
      // Define custom encryption key and IV
      const customKey = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]);
      const customIV = new Uint8Array([16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]);
    
      // Set loading state before encryption and backend call
      this.isLoading = true;
      this.imdCode = localStorage.getItem("parentCode");
      // Encrypt the IMD code
      encryptText({ imdCode: this.imdCode.trim() }, customKey, customIV)
        .then((encryptedResult) => {
          if (encryptedResult) {
            this.showTransactionDetails = true;
    
            // Fetch transaction details from the backend
            this.Transaction.FetchCreditCardDetailss(
              encryptedResult.encryptedText,
              encryptedResult.key,
              encryptedResult.base64iv
            ).subscribe({
              next: (data) => {
                this.isLoading = false; // Stop loading after receiving the response
    
                if (data.length === 0) {
                  // Handle empty data case
                  this.emptyDataMessage = 'Policy Details Not Found for the provided Agreement_Code.';
                  this.isDataEmptyMessage = true;
                } else {
                  // Process and display data if available
                  this.reporttransaction = data;
                  this.refreshDataTable();
                  console.log("Data:", data);
    
                  // Reset empty message indicator
                  this.isDataEmptyMessage = false;
                }
              },
              error: (error) => {
                this.isLoading = false; // Stop loading if there’s an error
                console.error('Error fetching transaction details:', error);
                if (error.status === 404) {
                  alert("Session has been Expired  .");
                } else {
                  alert("An error occurred while verifying the token.");
                }
                this.redirectToError();
                // Display error message or handle it as needed
                alert('Error fetching transaction details. Please try again.');
              }
            });
          } else {
            console.error("Encryption failed: No encrypted result.");
            this.isLoading = false; // Stop loading if encryption fails
          }
        })
        .catch((error) => {
          console.error("Error during encryption:", error);
          this.isLoading = false; // Stop loading on encryption error
        });
    }

showOriginalTable(): void {
  this.showTransactionDetails = false;
}
fetchViewTransaction(acidNumber:string)
{

  
}

// Initialize these arrays somewhere in your component to store checked dates
checkedTranDates: Date[] = [];
checkedInsuranceDates: Date[] = [];

onCheckboxClick(transaction: any, event: any) {
  const premiumvalue = Number(transaction.premium);
  const insurencedate = new Date(transaction.insurenceDate);
  const tranDate = new Date(transaction.tran_date);

  if (event.target.checked) {
    // Add the selected transaction's premium to the total sum
    this.selectedPremiumSum += premiumvalue;

    // Store the acd_number of the current selected transaction
    this.lastSelectedAcdNumber = transaction.acd_number;
    this.parentcode = transaction.imd_parent_code;
    this.agrementcode = transaction.imd_child_code;

    // Add tranDate and insurencedate to the checked lists
    this.checkedTranDates.push(tranDate);
    this.checkedInsuranceDates.push(insurencedate);

    // Add policy number to the list (duplicates are allowed)
    this.policynumbers.push(transaction.policyNumber);

    // Add the premium to the selected amounts list (duplicates are allowed)
    this.selectedAmount.push(transaction.premium);

  } else {
    // Subtract the transaction's premium from the total sum
    this.selectedPremiumSum -= premiumvalue;

    // Remove tranDate and insurencedate from the checked lists
    this.checkedTranDates = this.checkedTranDates.filter(date => date.getTime() !== tranDate.getTime());
    this.checkedInsuranceDates = this.checkedInsuranceDates.filter(date => date.getTime() !== insurencedate.getTime());

    // Remove the policy number from the list (only the first match)
    const policyIndex = this.policynumbers.indexOf(transaction.policyNumber);
    if (policyIndex > -1) {
      this.policynumbers.splice(policyIndex, 1);
    }

    // Remove the premium from the selected amounts list (only the first match)
    const premiumIndex = this.selectedAmount.indexOf(transaction.premium);
    if (premiumIndex > -1) {
      this.selectedAmount.splice(premiumIndex, 1);
    }
  }

  // Determine the oldest tranDate and insurencedate among checked policies
  const oldestTranDate = this.checkedTranDates.length > 0
    ? new Date(Math.min(...this.checkedTranDates.map(date => date.getTime())))
    : null;
  const oldestInsuranceDate = this.checkedInsuranceDates.length > 0
    ? new Date(Math.min(...this.checkedInsuranceDates.map(date => date.getTime())))
    : null;

  const formattedOldestTranDate = oldestTranDate ? this.formatDate(oldestTranDate) : 'N/A';
  const formattedOldestInsuranceDate = oldestInsuranceDate ? this.formatDate(oldestInsuranceDate) : 'N/A';

  console.log('Selected Total Premium:', this.selectedPremiumSum);
  console.log('Last Selected ACD Number:', this.lastSelectedAcdNumber);
  console.log('Oldest Transaction Date (Checked):', formattedOldestTranDate);
  console.log('Oldest Insurance Date (Checked):', formattedOldestInsuranceDate);

  // Save oldest dates in localStorage
  localStorage.setItem('oldestTranDate', formattedOldestTranDate);
  localStorage.setItem('oldestInsuranceDate', formattedOldestInsuranceDate);
}



formatDate(date: Date): string {
  const day = String(date.getDate()).padStart(2, '0');
  const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are zero-indexed
  const year = date.getFullYear();
  return `${day}-${month}-${year}`;
}



isReadOnly = false;
openPaymentPopup() {
  if (this.selectedPremiumSum > 0) {
    this.isReadOnly = true;  // Make fields read-only
    this.ispaymentPopupOpen = true;  // Open the modal
  } else {
    console.log('No transactions selected for payment');
  }
}
navigateToTransaction(item: any): void {
  this.sharedService.setCodes(item.imd_paraent_code, item.imd_child_code);
  this.routers.navigate(['/transactionAcdNumber']);
}


}