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>();
  @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;
  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() {
    console.log('1. MatSort initialized:', this.sort);
    console.log('2. MatPaginator initialized:', this.paginator);
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
    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']);
  }
}
<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="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>

      <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;
              "
            >
              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">
              {{ 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" 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.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 solid858796">
              {{ 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>

  <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 *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">All Rights Reserved</span>
    </div>
  </div>
</div>
dont change the button table hide and change functionality just add sorting flitering and pagination in the table Select	Policy Number	Customer Name	Quote Number	Issuance Date	Risk Start Date	Premium Amount	Elapsed Days	ACD Number	Replenish Status	Replenish Date	                   give me entire code for it will just copy paste