document.addEventListener('DOMContentLoaded', function() {
    // Cache DOM elements
    const table = document.getElementById('memberTable');
    const tbody = table.querySelector('tbody');
    const rows = Array.from(tbody.querySelectorAll('tr'));
    const rowsPerPageSelect = document.getElementById('rowsPerPage');
    const paginationControls = document.getElementById('paginationControls');
    const paginationInfo = document.getElementById('paginationInfo');
    const searchInput = document.getElementById('tableSearch');
    const clearSearchBtn = document.getElementById('clearSearch');
    const searchResultsInfo = document.getElementById('searchResultsInfo');
    const toggleAdvancedFiltersBtn = document.getElementById('toggleAdvancedFilters');
    const advancedFiltersSection = document.getElementById('advancedFilters');
    const toggleColumnVisibilityBtn = document.getElementById('toggleColumnVisibility');
    const columnVisibilitySection = document.getElementById('columnVisibilitySection');
    const columnCheckboxesContainer = document.getElementById('columnCheckboxes');
    const applyFiltersBtn = document.getElementById('applyFilters');
    const resetFiltersBtn = document.getElementById('resetFilters');
    const applyColumnVisibilityBtn = document.getElementById('applyColumnVisibility');
    const resetColumnsBtn = document.getElementById('resetColumns');
    const selectAllColumnsBtn = document.getElementById('selectAllColumns');
    const loadingIndicator = document.getElementById('loadingIndicator');
    
    // Export buttons
    const exportExcelBtn = document.getElementById('exportExcel');
    const exportPDFBtn = document.getElementById('exportPDF');
    const printTableBtn = document.getElementById('printTable');
    
    // Filter elements
    const divisionFilter = document.getElementById('divisionFilter');
    const villageFilter = document.getElementById('villageFilter');
    const gnDivisionFilter = document.getElementById('gnDivisionFilter');
    const smallGroupFilter = document.getElementById('smallGroupFilter');
    const professionTypeFilter = document.getElementById('professionTypeFilter');
    const professionFilter = document.getElementById('professionFilter');
    const maritalStatusFilter = document.getElementById('maritalStatusFilter');
    const statusFilter = document.getElementById('statusFilter');
    const statusTypeFilter = document.getElementById('statusTypeFilter');
    const ageFrom = document.getElementById('ageFrom');
    const ageTo = document.getElementById('ageTo');
    
    // Amount range filter elements
    const savingsFrom = document.getElementById('savingsFrom');
    const savingsTo = document.getElementById('savingsTo');
    const otherIncomeFrom = document.getElementById('otherIncomeFrom');
    const otherIncomeTo = document.getElementById('otherIncomeTo');
    const deathSubFrom = document.getElementById('deathSubFrom');
    const deathSubTo = document.getElementById('deathSubTo');
    const totalLoansFrom = document.getElementById('totalLoansFrom');
    const totalLoansTo = document.getElementById('totalLoansTo');
    const activeLoanAmountFrom = document.getElementById('activeLoanAmountFrom');
    const activeLoanAmountTo = document.getElementById('activeLoanAmountTo');
    const loanOutstandingFrom = document.getElementById('loanOutstandingFrom');
    const loanOutstandingTo = document.getElementById('loanOutstandingTo');
    const principalArrearsFrom = document.getElementById('principalArrearsFrom');
    const principalArrearsTo = document.getElementById('principalArrearsTo');
    const interestArrearsFrom = document.getElementById('interestArrearsFrom');
    const interestArrearsTo = document.getElementById('interestArrearsTo');
    
    // Summary card elements
    const summaryElements = {
        totalSavings: document.getElementById('totalSavings'),
        totalOtherIncome: document.getElementById('totalOtherIncome'),
        totalDeathSub: document.getElementById('totalDeathSub'),
        totalLoanCount: document.getElementById('totalLoanCount'),
        totalLoansAmount: document.getElementById('totalLoansAmount'),
        activeLoansCount: document.getElementById('activeLoansCount'),
        activeLoansAmount: document.getElementById('activeLoansAmount'),
        loanOutstanding: document.getElementById('loanOutstanding'),
        principalArrears: document.getElementById('principalArrears'),
        interestArrears: document.getElementById('interestArrears')
    };
    
    // State variables
    let currentPage = 1;
    let rowsPerPage = parseInt(rowsPerPageSelect.value);
    let filteredRows = [...rows]; // Start with all rows
    let isProcessing = false;
    let columnVisibility = {}; // Store column visibility state
    
    // Store original summary values
    const originalSummaryValues = {
        totalSavings: summaryElements.totalSavings.textContent,
        totalOtherIncome: summaryElements.totalOtherIncome.textContent,
        totalDeathSub: summaryElements.totalDeathSub.textContent,
        totalLoanCount: summaryElements.totalLoanCount.textContent,
        totalLoansAmount: summaryElements.totalLoansAmount.textContent,
        activeLoansCount: summaryElements.activeLoansCount.textContent,
        activeLoansAmount: summaryElements.activeLoansAmount.textContent,
        loanOutstanding: summaryElements.loanOutstanding.textContent,
        principalArrears: summaryElements.principalArrears.textContent,
        interestArrears: summaryElements.interestArrears.textContent
    };
    
    // Data structures for cascading dropdowns
    const filterData = {
        divisions: new Set(),
        divisionToVillages: {}, // Maps division to Set of villages
        divisionToGnDivisions: {}, // Maps division to Set of GN divisions
        villageToSmallGroups: {}, // Maps village to Set of small groups
        professionTypes: new Set(),
        professionTypeToProfessions: {}, // Maps profession type to Set of professions
        maritalStatuses: new Set(),
        statusTypes: new Set()
    };
    
    // Column names for visibility toggle
    const columnNames = [
        '#', 'Division', 'Village', 'Small Group', 'GN Division', 
        'Member Name', 'NIC Number', 'Unique ID', 'Old Account Number', 
        'Savings', 'Other Income', 'Death Subscription', 'Count of Total Loans', 'Total Loans', 
        'Active Loans', 'Active Loan Amount', 'Loan Outstanding', 'Due Terms', 
        'Principal Arrears', 'Interest Arrears', 'Profession Type', 'Profession', 
        'Phone Number', 'Address', 'NIC Issue Date', 'Marital Status', 'Date Of Birth', 
        'Age', 'Follower Name', 'Follower Address', 'Follower NIC Number', 
        'Follower Issue Date', 'Status', 'Status Type', 'Location'
    ];
    
    // Copyright text
    const copyrightText = '© 2023 Your Organization Name. All rights reserved.';
    
    // Initialize column visibility from localStorage or default to all visible
    function initializeColumnVisibility() {
        const savedVisibility = localStorage.getItem('memberReportColumnVisibility');
        if (savedVisibility) {
            columnVisibility = JSON.parse(savedVisibility);
        } else {
            // Default to all columns visible
            columnNames.forEach((name, index) => {
                columnVisibility[index] = true;
            });
        }
        applyColumnVisibilityState();
    }
    
    // Save column visibility to localStorage
    function saveColumnVisibility() {
        localStorage.setItem('memberReportColumnVisibility', JSON.stringify(columnVisibility));
    }
    
    // Create column checkboxes
    function createColumnCheckboxes() {
        columnCheckboxesContainer.innerHTML = '';
        
        columnNames.forEach((name, index) => {
            const colDiv = document.createElement('div');
            colDiv.className = 'col-md-3 col-sm-4 col-6';
            
            const formCheck = document.createElement('div');
            formCheck.className = 'form-check';
            
            const checkbox = document.createElement('input');
            checkbox.className = 'form-check-input';
            checkbox.type = 'checkbox';
            checkbox.id = `column-${index}`;
            checkbox.checked = columnVisibility[index];
            checkbox.dataset.columnIndex = index;
            
            const label = document.createElement('label');
            label.className = 'form-check-label';
            label.htmlFor = `column-${index}`;
            label.textContent = name;
            
            formCheck.appendChild(checkbox);
            formCheck.appendChild(label);
            colDiv.appendChild(formCheck);
            columnCheckboxesContainer.appendChild(colDiv);
        });
    }
    
    // Apply column visibility state to the table
    function applyColumnVisibilityState() {
        const headerCells = table.querySelectorAll('thead th');
        const bodyCells = table.querySelectorAll('tbody td');
        
        headerCells.forEach((cell, index) => {
            cell.style.display = columnVisibility[index] ? '' : 'none';
        });
        
        bodyCells.forEach(cell => {
            const columnIndex = parseInt(cell.dataset.column);
            cell.style.display = columnVisibility[columnIndex] ? '' : 'none';
        });
    }
    
    // Build filter data structures
    function buildFilterData() {
        rows.forEach(row => {
            const division = row.dataset.division;
            const village = row.dataset.village;
            const smallGroup = row.dataset.smallGroup;
            const gnDivision = row.dataset.gnDivision;
            const professionType = row.dataset.professionType;
            const profession = row.dataset.profession;
            const maritalStatus = row.dataset.maritalStatus;
            const statusType = row.dataset.statusType;
            
            // Add division
            if (division !== '-') {
                filterData.divisions.add(division);
                
                // Initialize division mappings if not exists
                if (!filterData.divisionToVillages[division]) {
                    filterData.divisionToVillages[division] = new Set();
                }
                if (!filterData.divisionToGnDivisions[division]) {
                    filterData.divisionToGnDivisions[division] = new Set();
                }
                
                // Add village to division
                if (village !== '-') {
                    filterData.divisionToVillages[division].add(village);
                    
                    // Initialize village mapping if not exists
                    if (!filterData.villageToSmallGroups[village]) {
                        filterData.villageToSmallGroups[village] = new Set();
                    }
                    
                    // Add small group to village
                    if (smallGroup !== '-') {
                        filterData.villageToSmallGroups[village].add(smallGroup);
                    }
                }
                
                // Add GN division to division
                if (gnDivision !== '-') {
                    filterData.divisionToGnDivisions[division].add(gnDivision);
                }
            }
            
            // Add profession type
            if (professionType !== '-') {
                filterData.professionTypes.add(professionType);
                
                // Initialize profession type mapping if not exists
                if (!filterData.professionTypeToProfessions[professionType]) {
                    filterData.professionTypeToProfessions[professionType] = new Set();
                }
                
                // Add profession to profession type
                if (profession !== '-') {
                    filterData.professionTypeToProfessions[professionType].add(profession);
                }
            }
            
            // Add marital status
            if (maritalStatus !== '-') {
                filterData.maritalStatuses.add(maritalStatus);
            }
            
            // Add status type
            if (statusType !== '-') {
                filterData.statusTypes.add(statusType);
            }
        });
    }
    
    // Debounce function to limit how often a function can be called
    function debounce(func, wait) {
        let timeout;
        return function(...args) {
            clearTimeout(timeout);
            timeout = setTimeout(() => func.apply(this, args), wait);
        };
    }
    
    // Show loading indicator
    function showLoading() {
        loadingIndicator.style.display = 'block';
    }
    
    // Hide loading indicator
    function hideLoading() {
        loadingIndicator.style.display = 'none';
    }
    
    // Toggle advanced filters section
    toggleAdvancedFiltersBtn.addEventListener('click', function() {
        if (advancedFiltersSection.style.display === 'none') {
            // Close column visibility section if it's open
            if (columnVisibilitySection.style.display !== 'none') {
                columnVisibilitySection.style.display = 'none';
                toggleColumnVisibilityBtn.innerHTML = '<i class="ti ti-columns me-1"></i> Columns';
            }
            
            // Open advanced filters section
            advancedFiltersSection.style.display = 'block';
            this.innerHTML = '<i class="ti ti-filter-off me-1"></i> Hide Filters';
        } else {
            advancedFiltersSection.style.display = 'none';
            this.innerHTML = '<i class="ti ti-filter me-1"></i> Filters';
        }
    });
    
    // Toggle column visibility section
    toggleColumnVisibilityBtn.addEventListener('click', function() {
        if (columnVisibilitySection.style.display === 'none') {
            // Close advanced filters section if it's open
            if (advancedFiltersSection.style.display !== 'none') {
                advancedFiltersSection.style.display = 'none';
                toggleAdvancedFiltersBtn.innerHTML = '<i class="ti ti-filter me-1"></i> Filters';
            }
            
            // Open column visibility section
            columnVisibilitySection.style.display = 'block';
            this.innerHTML = '<i class="ti ti-columns-off me-1"></i> Columns';
            createColumnCheckboxes();
        } else {
            columnVisibilitySection.style.display = 'none';
            this.innerHTML = '<i class="ti ti-columns me-1"></i> Columns';
        }
    });
    
    // Populate division filter
    function populateDivisionFilter() {
        divisionFilter.innerHTML = '<option value="">All Divisions</option>';
        Array.from(filterData.divisions).sort().forEach(division => {
            const option = document.createElement('option');
            option.value = division;
            option.textContent = division;
            divisionFilter.appendChild(option);
        });
    }
    
    // Update village filter based on selected division
    function updateVillageFilter() {
        const selectedDivision = divisionFilter.value;
        
        if (!selectedDivision) {
            villageFilter.innerHTML = '<option value="">Select Division First</option>';
            villageFilter.disabled = true;
            return;
        }
        
        villageFilter.disabled = false;
        villageFilter.innerHTML = '<option value="">All Villages</option>';
        
        const villages = filterData.divisionToVillages[selectedDivision];
        if (villages) {
            Array.from(villages).sort().forEach(village => {
                const option = document.createElement('option');
                option.value = village;
                option.textContent = village;
                villageFilter.appendChild(option);
            });
        }
        
        // Reset small group filter when division changes
        smallGroupFilter.innerHTML = '<option value="">Select Village First</option>';
        smallGroupFilter.disabled = true;
    }
    
    // Update GN division filter based on selected division
    function updateGnDivisionFilter() {
        const selectedDivision = divisionFilter.value;
        
        if (!selectedDivision) {
            gnDivisionFilter.innerHTML = '<option value="">Select Division First</option>';
            gnDivisionFilter.disabled = true;
            return;
        }
        
        gnDivisionFilter.disabled = false;
        gnDivisionFilter.innerHTML = '<option value="">All GN Divisions</option>';
        
        const gnDivisions = filterData.divisionToGnDivisions[selectedDivision];
        if (gnDivisions) {
            Array.from(gnDivisions).sort().forEach(gnDivision => {
                const option = document.createElement('option');
                option.value = gnDivision;
                option.textContent = gnDivision;
                gnDivisionFilter.appendChild(option);
            });
        }
    }
    
    // Update small group filter based on selected village
    function updateSmallGroupFilter() {
        const selectedVillage = villageFilter.value;
        
        if (!selectedVillage) {
            smallGroupFilter.innerHTML = '<option value="">Select Village First</option>';
            smallGroupFilter.disabled = true;
            return;
        }
        
        smallGroupFilter.disabled = false;
        smallGroupFilter.innerHTML = '<option value="">All Small Groups</option>';
        
        const smallGroups = filterData.villageToSmallGroups[selectedVillage];
        if (smallGroups) {
            Array.from(smallGroups).sort().forEach(smallGroup => {
                const option = document.createElement('option');
                option.value = smallGroup;
                option.textContent = smallGroup;
                smallGroupFilter.appendChild(option);
            });
        }
    }
    
    // Populate profession type filter
    function populateProfessionTypeFilter() {
        professionTypeFilter.innerHTML = '<option value="">All Profession Types</option>';
        Array.from(filterData.professionTypes).sort().forEach(professionType => {
            const option = document.createElement('option');
            option.value = professionType;
            option.textContent = professionType;
            professionTypeFilter.appendChild(option);
        });
    }
    
    // Update profession filter based on selected profession type
    function updateProfessionFilter() {
        const selectedProfessionType = professionTypeFilter.value;
        
        if (!selectedProfessionType) {
            professionFilter.innerHTML = '<option value="">Select Profession Type First</option>';
            professionFilter.disabled = true;
            return;
        }
        
        professionFilter.disabled = false;
        professionFilter.innerHTML = '<option value="">All Professions</option>';
        
        const professions = filterData.professionTypeToProfessions[selectedProfessionType];
        if (professions) {
            Array.from(professions).sort().forEach(profession => {
                const option = document.createElement('option');
                option.value = profession;
                option.textContent = profession;
                professionFilter.appendChild(option);
            });
        }
    }
    
    // Populate marital status filter
    function populateMaritalStatusFilter() {
        maritalStatusFilter.innerHTML = '<option value="">All Marital Status</option>';
        Array.from(filterData.maritalStatuses).sort().forEach(maritalStatus => {
            const option = document.createElement('option');
            option.value = maritalStatus;
            option.textContent = maritalStatus;
            maritalStatusFilter.appendChild(option);
        });
    }
    
    // Populate status type filter
    function populateStatusTypeFilter() {
        statusTypeFilter.innerHTML = '<option value="">All Status Types</option>';
        Array.from(filterData.statusTypes).sort().forEach(statusType => {
            const option = document.createElement('option');
            option.value = statusType;
            option.textContent = statusType;
            statusTypeFilter.appendChild(option);
        });
    }
    
    // Calculate totals for filtered rows
    function calculateTotalsForFilteredRows() {
        let totals = {
            savings: 0,
            otherIncome: 0,
            deathSub: 0,
            totalLoanCount: 0,
            totalLoans: 0,
            activeLoanCount: 0,
            activeLoanAmount: 0,
            loanOutstanding: 0,
            principalArrears: 0,
            interestArrears: 0
        };

        filteredRows.forEach(row => {
            totals.savings += parseFloat(row.dataset.saving) || 0;
            totals.otherIncome += parseFloat(row.dataset.otherIncome) || 0;
            totals.deathSub += parseFloat(row.dataset.deathSubscription) || 0;
            totals.totalLoanCount += parseInt(row.dataset.totalLoanCount) || 0;
            totals.totalLoans += parseFloat(row.dataset.totalLoans) || 0;
            totals.activeLoanCount += parseInt(row.dataset.activeLoanCount) || 0;
            totals.activeLoanAmount += parseFloat(row.dataset.activeLoanAmount) || 0;
            totals.loanOutstanding += parseFloat(row.dataset.loanOutstanding) || 0;
            totals.principalArrears += parseFloat(row.dataset.principalArrears) || 0;
            totals.interestArrears += parseFloat(row.dataset.interestArrears) || 0;
        });

        return totals;
    }
    
    // Update summary cards based on filtered rows
    function updateSummaryCards() {
        const totals = calculateTotalsForFilteredRows();
        
        // Use requestAnimationFrame for smoother rendering
        requestAnimationFrame(() => {
            summaryElements.totalSavings.textContent = totals.savings.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
            summaryElements.totalOtherIncome.textContent = totals.otherIncome.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
            summaryElements.totalDeathSub.textContent = totals.deathSub.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
            summaryElements.totalLoanCount.textContent = totals.totalLoanCount.toLocaleString();
            summaryElements.totalLoansAmount.textContent = totals.totalLoans.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
            summaryElements.activeLoansCount.textContent = totals.activeLoanCount.toLocaleString();
            summaryElements.activeLoansAmount.textContent = totals.activeLoanAmount.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
            summaryElements.loanOutstanding.textContent = totals.loanOutstanding.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
            summaryElements.principalArrears.textContent = totals.principalArrears.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
            summaryElements.interestArrears.textContent = totals.interestArrears.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
        });
    }
    
    // Function to filter rows based on search term and dropdown filters
    function filterRows() {
        if (isProcessing) return; // Prevent overlapping operations
        
        isProcessing = true;
        showLoading();
        
        // Use setTimeout to allow UI to update before processing
        setTimeout(() => {
            const searchTerm = searchInput.value.toLowerCase();
            const divisionValue = divisionFilter.value;
            const villageValue = villageFilter.value;
            const gnDivisionValue = gnDivisionFilter.value;
            const smallGroupValue = smallGroupFilter.value;
            const professionTypeValue = professionTypeFilter.value;
            const professionValue = professionFilter.value;
            const maritalStatusValue = maritalStatusFilter.value;
            const statusValue = statusFilter.value;
            const statusTypeValue = statusTypeFilter.value;
            
            // Get age range filter values
            const ageFromValue = parseInt(ageFrom.value) || 0;
            const ageToValue = parseInt(ageTo.value) || Number.MAX_VALUE;
            
            // Get amount range filter values
            const savingsFromValue = parseFloat(savingsFrom.value) || 0;
            const savingsToValue = parseFloat(savingsTo.value) || Number.MAX_VALUE;
            const otherIncomeFromValue = parseFloat(otherIncomeFrom.value) || 0;
            const otherIncomeToValue = parseFloat(otherIncomeTo.value) || Number.MAX_VALUE;
            const deathSubFromValue = parseFloat(deathSubFrom.value) || 0;
            const deathSubToValue = parseFloat(deathSubTo.value) || Number.MAX_VALUE;
            const totalLoansFromValue = parseFloat(totalLoansFrom.value) || 0;
            const totalLoansToValue = parseFloat(totalLoansTo.value) || Number.MAX_VALUE;
            const activeLoanAmountFromValue = parseFloat(activeLoanAmountFrom.value) || 0;
            const activeLoanAmountToValue = parseFloat(activeLoanAmountTo.value) || Number.MAX_VALUE;
            const loanOutstandingFromValue = parseFloat(loanOutstandingFrom.value) || 0;
            const loanOutstandingToValue = parseFloat(loanOutstandingTo.value) || Number.MAX_VALUE;
            const principalArrearsFromValue = parseFloat(principalArrearsFrom.value) || 0;
            const principalArrearsToValue = parseFloat(principalArrearsTo.value) || Number.MAX_VALUE;
            const interestArrearsFromValue = parseFloat(interestArrearsFrom.value) || 0;
            const interestArrearsToValue = parseFloat(interestArrearsTo.value) || Number.MAX_VALUE;
            
            // Check if any filters are applied
            const hasSearchFilter = searchTerm !== '';
            const hasLocationFilter = divisionValue || villageValue || gnDivisionValue || smallGroupValue;
            const hasPersonalFilter = professionTypeValue || professionValue || maritalStatusValue || statusValue || statusTypeValue || ageFrom.value || ageTo.value;
            const hasAmountFilter = savingsFrom.value || savingsTo.value || 
                                    otherIncomeFrom.value || otherIncomeTo.value || 
                                    deathSubFrom.value || deathSubTo.value || 
                                    totalLoansFrom.value || totalLoansTo.value || 
                                    activeLoanAmountFrom.value || activeLoanAmountTo.value || 
                                    loanOutstandingFrom.value || loanOutstandingTo.value || 
                                    principalArrearsFrom.value || principalArrearsTo.value || 
                                    interestArrearsFrom.value || interestArrearsTo.value;
            
            if (!hasSearchFilter && !hasLocationFilter && !hasPersonalFilter && !hasAmountFilter) {
                filteredRows = [...rows];
            } else {
                filteredRows = rows.filter(row => {
                    const cells = row.querySelectorAll('td');
                    const text = row.textContent.toLowerCase();
                    
                    // Check if row matches search term
                    const matchesSearch = !hasSearchFilter || text.includes(searchTerm);
                    
                    // Check if row matches division filter
                    const matchesDivision = !divisionValue || cells[1].textContent.trim() === divisionValue;
                    
                    // Check if row matches village filter
                    const matchesVillage = !villageValue || cells[2].textContent.trim() === villageValue;
                    
                    // Check if row matches GN division filter
                    const matchesGnDivision = !gnDivisionValue || cells[4].textContent.trim() === gnDivisionValue;
                    
                    // Check if row matches small group filter
                    const matchesSmallGroup = !smallGroupValue || cells[3].textContent.trim() === smallGroupValue;
                    
                    // Check if row matches profession type filter
                    const matchesProfessionType = !professionTypeValue || row.dataset.professionType === professionTypeValue;
                    
                    // Check if row matches profession filter
                    const matchesProfession = !professionValue || row.dataset.profession === professionValue;
                    
                    // Check if row matches marital status filter
                    const matchesMaritalStatus = !maritalStatusValue || row.dataset.maritalStatus === maritalStatusValue;
                    
                    // Check if row matches status filter
                    const matchesStatus = !statusValue || row.dataset.status === statusValue;
                    
                    // Check if row matches status type filter
                    const matchesStatusType = !statusTypeValue || row.dataset.statusType === statusTypeValue;
                    
                    // Check age range
                    const ageYears = parseInt(row.dataset.ageYears) || 0;
                    const matchesAgeRange = ageYears >= ageFromValue && ageYears <= ageToValue;
                    
                    // Check amount ranges
                    const saving = parseFloat(row.dataset.saving) || 0;
                    const otherIncome = parseFloat(row.dataset.otherIncome) || 0;
                    const deathSub = parseFloat(row.dataset.deathSubscription) || 0;
                    const totalLoans = parseFloat(row.dataset.totalLoans) || 0;
                    const activeLoanAmount = parseFloat(row.dataset.activeLoanAmount) || 0;
                    const loanOutstanding = parseFloat(row.dataset.loanOutstanding) || 0;
                    const principalArrears = parseFloat(row.dataset.principalArrears) || 0;
                    const interestArrears = parseFloat(row.dataset.interestArrears) || 0;
                    
                    const matchesSavingsRange = saving >= savingsFromValue && saving <= savingsToValue;
                    const matchesOtherIncomeRange = otherIncome >= otherIncomeFromValue && otherIncome <= otherIncomeToValue;
                    const matchesDeathSubRange = deathSub >= deathSubFromValue && deathSub <= deathSubToValue;
                    const matchesTotalLoansRange = totalLoans >= totalLoansFromValue && totalLoans <= totalLoansToValue;
                    const matchesActiveLoanAmountRange = activeLoanAmount >= activeLoanAmountFromValue && activeLoanAmount <= activeLoanAmountToValue;
                    const matchesLoanOutstandingRange = loanOutstanding >= loanOutstandingFromValue && loanOutstanding <= loanOutstandingToValue;
                    const matchesPrincipalArrearsRange = principalArrears >= principalArrearsFromValue && principalArrears <= principalArrearsToValue;
                    const matchesInterestArrearsRange = interestArrears >= interestArrearsFromValue && interestArrears <= interestArrearsToValue;
                    
                    return matchesSearch && 
                           matchesDivision && 
                           matchesVillage && 
                           matchesGnDivision && 
                           matchesSmallGroup &&
                           matchesProfessionType &&
                           matchesProfession &&
                           matchesMaritalStatus &&
                           matchesStatus &&
                           matchesStatusType &&
                           matchesAgeRange &&
                           matchesSavingsRange &&
                           matchesOtherIncomeRange &&
                           matchesDeathSubRange &&
                           matchesTotalLoansRange &&
                           matchesActiveLoanAmountRange &&
                           matchesLoanOutstandingRange &&
                           matchesPrincipalArrearsRange &&
                           matchesInterestArrearsRange;
                });
            }
            
            currentPage = 1; // Reset to first page when filtering
            
            // Use requestAnimationFrame for smoother rendering
            requestAnimationFrame(() => {
                displayPage(currentPage);
                updateSearchResultsInfo(searchTerm);
                updateSummaryCards(); // Update summary cards based on filtered data
                hideLoading();
                isProcessing = false;
            });
        }, 0);
    }
    
    // Function to update search results info
    function updateSearchResultsInfo(searchTerm) {
        const hasLocationFilters = divisionFilter.value || villageFilter.value || gnDivisionFilter.value || smallGroupFilter.value;
        const hasPersonalFilters = professionTypeFilter.value || professionFilter.value || maritalStatusFilter.value || statusFilter.value || statusTypeFilter.value || ageFrom.value || ageTo.value;
        
        // Check if any amount filters are applied
        const hasAmountFilters = savingsFrom.value || savingsTo.value || 
                                otherIncomeFrom.value || otherIncomeTo.value || 
                                deathSubFrom.value || deathSubTo.value || 
                                totalLoansFrom.value || totalLoansTo.value || 
                                activeLoanAmountFrom.value || activeLoanAmountTo.value || 
                                loanOutstandingFrom.value || loanOutstandingTo.value || 
                                principalArrearsFrom.value || principalArrearsTo.value || 
                                interestArrearsFrom.value || interestArrearsTo.value;
        
        if (searchTerm || hasLocationFilters || hasPersonalFilters || hasAmountFilters) {
            let infoText = `Found ${filteredRows.length} results`;
            if (searchTerm) {
                infoText += ` for "${searchTerm}"`;
            }
            if (hasLocationFilters || hasPersonalFilters || hasAmountFilters) {
                infoText += ' with active filters';
            }
            searchResultsInfo.textContent = infoText;
        } else {
            searchResultsInfo.textContent = `Showing all ${rows.length} records`;
        }
    }
    
    // Search input event listener
    searchInput.addEventListener('input', debounce(filterRows, 300));
    
    // Clear search button
    clearSearchBtn.addEventListener('click', function() {
        searchInput.value = '';
        filterRows();
    });
    
    // Apply filters button
    applyFiltersBtn.addEventListener('click', filterRows);
    
    // Reset filters button
    resetFiltersBtn.addEventListener('click', function() {
        // Reset location filters
        divisionFilter.value = '';
        villageFilter.value = '';
        gnDivisionFilter.value = '';
        smallGroupFilter.value = '';
        
        // Reset dropdown states
        villageFilter.innerHTML = '<option value="">Select Division First</option>';
        villageFilter.disabled = true;
        
        smallGroupFilter.innerHTML = '<option value="">Select Village First</option>';
        smallGroupFilter.disabled = true;
        
        gnDivisionFilter.innerHTML = '<option value="">Select Division First</option>';
        gnDivisionFilter.disabled = true;
        
        // Reset personal filters
        professionTypeFilter.value = '';
        professionFilter.innerHTML = '<option value="">Select Profession Type First</option>';
        professionFilter.disabled = true;
        
        maritalStatusFilter.value = '';
        statusFilter.value = '';
        statusTypeFilter.value = '';
        ageFrom.value = '';
        ageTo.value = '';
        
        // Reset amount range filters
        savingsFrom.value = '';
        savingsTo.value = '';
        otherIncomeFrom.value = '';
        otherIncomeTo.value = '';
        deathSubFrom.value = '';
        deathSubTo.value = '';
        totalLoansFrom.value = '';
        totalLoansTo.value = '';
        activeLoanAmountFrom.value = '';
        activeLoanAmountTo.value = '';
        loanOutstandingFrom.value = '';
        loanOutstandingTo.value = '';
        principalArrearsFrom.value = '';
        principalArrearsTo.value = '';
        interestArrearsFrom.value = '';
        interestArrearsTo.value = '';
        
        filterRows();
    });
    
    // Apply column visibility button
    applyColumnVisibilityBtn.addEventListener('click', function() {
        // Update column visibility from checkboxes
        const checkboxes = columnCheckboxesContainer.querySelectorAll('input[type="checkbox"]');
        checkboxes.forEach(checkbox => {
            const columnIndex = parseInt(checkbox.dataset.columnIndex);
            columnVisibility[columnIndex] = checkbox.checked;
        });
        
        // Apply the visibility state
        applyColumnVisibilityState();
        
        // Save to localStorage
        saveColumnVisibility();
        
        // Hide the column visibility section
        columnVisibilitySection.style.display = 'none';
        toggleColumnVisibilityBtn.innerHTML = '<i class="ti ti-columns me-1"></i> Columns';
    });
    
    // Reset columns button
    resetColumnsBtn.addEventListener('click', function() {
        // Reset to all columns visible
        columnNames.forEach((name, index) => {
            columnVisibility[index] = true;
        });
        
        // Update checkboxes
        const checkboxes = columnCheckboxesContainer.querySelectorAll('input[type="checkbox"]');
        checkboxes.forEach(checkbox => {
            checkbox.checked = true;
        });
        
        // Apply the visibility state
        applyColumnVisibilityState();
        
        // Save to localStorage
        saveColumnVisibility();
    });
    
    // Select all columns button
    selectAllColumnsBtn.addEventListener('click', function() {
        const checkboxes = columnCheckboxesContainer.querySelectorAll('input[type="checkbox"]');
        checkboxes.forEach(checkbox => {
            checkbox.checked = true;
        });
    });
    
    // Division filter change event listener
    divisionFilter.addEventListener('change', function() {
        updateVillageFilter();
        updateGnDivisionFilter();
        debounce(filterRows, 200)();
    });
    
    // Village filter change event listener
    villageFilter.addEventListener('change', function() {
        updateSmallGroupFilter();
        debounce(filterRows, 200)();
    });
    
    // GN division filter change event listener
    gnDivisionFilter.addEventListener('change', debounce(filterRows, 200));
    
    // Small group filter change event listener
    smallGroupFilter.addEventListener('change', debounce(filterRows, 200));
    
    // Profession type filter change event listener
    professionTypeFilter.addEventListener('change', function() {
        updateProfessionFilter();
        debounce(filterRows, 200)();
    });
    
    // Profession filter change event listener
    professionFilter.addEventListener('change', debounce(filterRows, 200));
    
    // Personal filter change event listeners
    maritalStatusFilter.addEventListener('change', debounce(filterRows, 200));
    statusFilter.addEventListener('change', debounce(filterRows, 200));
    statusTypeFilter.addEventListener('change', debounce(filterRows, 200));
    ageFrom.addEventListener('input', debounce(filterRows, 300));
    ageTo.addEventListener('input', debounce(filterRows, 300));
    
    // Amount range filter event listeners
    const amountFilterInputs = [
        savingsFrom, savingsTo,
        otherIncomeFrom, otherIncomeTo,
        deathSubFrom, deathSubTo,
        totalLoansFrom, totalLoansTo,
        activeLoanAmountFrom, activeLoanAmountTo,
        loanOutstandingFrom, loanOutstandingTo,
        principalArrearsFrom, principalArrearsTo,
        interestArrearsFrom, interestArrearsTo
    ];
    
    amountFilterInputs.forEach(input => {
        input.addEventListener('input', debounce(filterRows, 300));
    });
    
    function displayPage(page) {
        // Hide all rows
        rows.forEach(row => row.style.display = 'none');
        
        // Calculate start and end indices
        const startIndex = (page - 1) * rowsPerPage;
        const endIndex = startIndex + rowsPerPage;
        
        // Show rows for current page
        for (let i = startIndex; i < endIndex && i < filteredRows.length; i++) {
            filteredRows[i].style.display = '';
        }
        
        // Update pagination controls
        renderPagination();
    }
    
    function renderPagination() {
        const totalPages = Math.ceil(filteredRows.length / rowsPerPage);
        paginationControls.innerHTML = '';
        
        // If no results, don't show pagination
        if (filteredRows.length === 0) {
            paginationInfo.textContent = 'No matching records found';
            return;
        }
        
        // Previous button
        const prevBtn = document.createElement('button');
        prevBtn.className = 'btn btn-sm btn-outline-primary me-1';
        prevBtn.textContent = 'Previous';
        prevBtn.disabled = currentPage === 1;
        prevBtn.addEventListener('click', () => {
            if (currentPage > 1) {
                currentPage--;
                displayPage(currentPage);
            }
        });
        paginationControls.appendChild(prevBtn);
        
        // Page numbers
        let startPage = Math.max(1, currentPage - 2);
        let endPage = Math.min(totalPages, startPage + 4);
        
        if (endPage - startPage < 4) {
            startPage = Math.max(1, endPage - 4);
        }
        
        if (startPage > 1) {
            const firstBtn = createPageButton(1);
            paginationControls.appendChild(firstBtn);
            
            if (startPage > 2) {
                const ellipsis = document.createElement('span');
                ellipsis.className = 'mx-1';
                ellipsis.textContent = '...';
                paginationControls.appendChild(ellipsis);
            }
        }
        
        for (let i = startPage; i <= endPage; i++) {
            const pageBtn = createPageButton(i);
            paginationControls.appendChild(pageBtn);
        }
        
        if (endPage < totalPages) {
            if (endPage < totalPages - 1) {
                const ellipsis = document.createElement('span');
                ellipsis.className = 'mx-1';
                ellipsis.textContent = '...';
                paginationControls.appendChild(ellipsis);
            }
            
            const lastBtn = createPageButton(totalPages);
            paginationControls.appendChild(lastBtn);
        }
        
        // Next button
        const nextBtn = document.createElement('button');
        nextBtn.className = 'btn btn-sm btn-outline-primary ms-1';
        nextBtn.textContent = 'Next';
        nextBtn.disabled = currentPage === totalPages;
        nextBtn.addEventListener('click', () => {
            if (currentPage < totalPages) {
                currentPage++;
                displayPage(currentPage);
            }
        });
        paginationControls.appendChild(nextBtn);
        
        // Update pagination info
        const startItem = filteredRows.length > 0 ? (currentPage - 1) * rowsPerPage + 1 : 0;
        const endItem = Math.min(currentPage * rowsPerPage, filteredRows.length);
        paginationInfo.textContent = `Showing ${startItem}-${endItem} of ${filteredRows.length} items`;
    }
    
    function createPageButton(pageNum) {
        const btn = document.createElement('button');
        btn.className = `btn btn-sm ${pageNum === currentPage ? 'btn-primary' : 'btn-outline-primary'} me-1`;
        btn.textContent = pageNum;
        btn.addEventListener('click', () => {
            currentPage = pageNum;
            displayPage(currentPage);
        });
        return btn;
    }
    
    // Rows per page change handler
    rowsPerPageSelect.addEventListener('change', function() {
        rowsPerPage = parseInt(this.value);
        currentPage = 1;
        displayPage(currentPage);
    });
    
    // Export to Excel
    exportExcelBtn.addEventListener('click', function() {
        if (filteredRows.length === 0) {
            alert('No data to export');
            return;
        }
        
        showLoading();
        
        // Get visible column indices
        const visibleColumns = [];
        for (let i = 0; i < columnNames.length; i++) {
            if (columnVisibility[i]) {
                visibleColumns.push(i);
            }
        }
        
        // Prepare data: header and rows
        const header = visibleColumns.map(index => columnNames[index]);
        const data = [];
        
        // Add header row
        data.push(header);
        
        // Add data rows (only visible columns and only filtered rows)
        filteredRows.forEach(row => {
            const rowData = [];
            visibleColumns.forEach(colIndex => {
                // Get the cell with the matching data-column attribute
                const cell = row.querySelector(`td[data-column="${colIndex}"]`);
                if (cell) {
                    rowData.push(cell.textContent.trim());
                } else {
                    rowData.push('');
                }
            });
            data.push(rowData);
        });
        
        // Calculate totals
        const totals = calculateTotalsForFilteredRows();
        
        // Add totals row
        const totalsRow = [];
        visibleColumns.forEach(colIndex => {
            if (colIndex === 9) { // Savings
                totalsRow.push(`Total: ${totals.savings.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`);
            } else if (colIndex === 10) { // Other Income
                totalsRow.push(`Total: ${totals.otherIncome.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`);
            } else if (colIndex === 11) { // Death Subscription
                totalsRow.push(`Total: ${totals.deathSub.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`);
            } else if (colIndex === 12) { // Count of Total Loans
                totalsRow.push(`Total: ${totals.totalLoanCount.toLocaleString()}`);
            } else if (colIndex === 13) { // Total Loans
                totalsRow.push(`Total: ${totals.totalLoans.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`);
            } else if (colIndex === 14) { // Active Loans
                totalsRow.push(`Total: ${totals.activeLoanCount.toLocaleString()}`);
            } else if (colIndex === 15) { // Active Loan Amount
                totalsRow.push(`Total: ${totals.activeLoanAmount.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`);
            } else if (colIndex === 16) { // Loan Outstanding
                totalsRow.push(`Total: ${totals.loanOutstanding.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`);
            } else if (colIndex === 18) { // Principal Arrears
                totalsRow.push(`Total: ${totals.principalArrears.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`);
            } else if (colIndex === 19) { // Interest Arrears
                totalsRow.push(`Total: ${totals.interestArrears.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`);
            } else {
                totalsRow.push('');
            }
        });
        data.push(totalsRow);
        
        // Add copyright row
        const copyrightRow = [];
        visibleColumns.forEach((colIndex, index) => {
            if (index === 0) {
                copyrightRow.push(copyrightText);
            } else {
                copyrightRow.push('');
            }
        });
        data.push(copyrightRow);
        
        // Create a workbook and worksheet
        const ws = XLSX.utils.aoa_to_sheet(data);
        const wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, "Member Report");
        
        // Save the file
        XLSX.writeFile(wb, "member_report.xlsx");
        
        hideLoading();
    });
    
    // Export to PDF
    exportPDFBtn.addEventListener('click', function() {
        if (filteredRows.length === 0) {
            alert('No data to export');
            return;
        }
        
        showLoading();
        
        // Get visible column indices
        const visibleColumns = [];
        for (let i = 0; i < columnNames.length; i++) {
            if (columnVisibility[i]) {
                visibleColumns.push(i);
            }
        }
        
        // Prepare data: header and rows
        const header = visibleColumns.map(index => columnNames[index]);
        const data = [];
        
        // Add data rows (only visible columns and only filtered rows)
        filteredRows.forEach(row => {
            const rowData = [];
            visibleColumns.forEach(colIndex => {
                const cell = row.querySelector(`td[data-column="${colIndex}"]`);
                if (cell) {
                    rowData.push(cell.textContent.trim());
                } else {
                    rowData.push('');
                }
            });
            data.push(rowData);
        });
        
        // Calculate totals
        const totals = calculateTotalsForFilteredRows();
        
        // Create totals row for PDF
        const totalsRow = [];
        visibleColumns.forEach(colIndex => {
            if (colIndex === 9) { // Savings
                totalsRow.push(`Total: ${totals.savings.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`);
            } else if (colIndex === 10) { // Other Income
                totalsRow.push(`Total: ${totals.otherIncome.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`);
            } else if (colIndex === 11) { // Death Subscription
                totalsRow.push(`Total: ${totals.deathSub.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`);
            } else if (colIndex === 12) { // Count of Total Loans
                totalsRow.push(`Total: ${totals.totalLoanCount.toLocaleString()}`);
            } else if (colIndex === 13) { // Total Loans
                totalsRow.push(`Total: ${totals.totalLoans.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`);
            } else if (colIndex === 14) { // Active Loans
                totalsRow.push(`Total: ${totals.activeLoanCount.toLocaleString()}`);
            } else if (colIndex === 15) { // Active Loan Amount
                totalsRow.push(`Total: ${totals.activeLoanAmount.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`);
            } else if (colIndex === 16) { // Loan Outstanding
                totalsRow.push(`Total: ${totals.loanOutstanding.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`);
            } else if (colIndex === 18) { // Principal Arrears
                totalsRow.push(`Total: ${totals.principalArrears.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`);
            } else if (colIndex === 19) { // Interest Arrears
                totalsRow.push(`Total: ${totals.interestArrears.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`);
            } else {
                totalsRow.push('');
            }
        });
        
        // Create a new jsPDF instance with A3 landscape
        const { jsPDF } = window.jspdf;
        const doc = new jsPDF({
            orientation: 'landscape',
            unit: 'mm',
            format: 'a3'
        });
        
        // Add title
        doc.setFontSize(18);
        doc.text('Member Report', 14, 15);
        
        // Add date filter if applied
        const filterDate = document.getElementById('filter_date').value;
        if (filterDate) {
            doc.setFontSize(12);
            doc.text(`As on Date: ${filterDate}`, 14, 25);
        }
        
        // Define column widths to fit all columns on A3 page
        const columnWidths = [
            8,   // 0: #
            12,  // 1: Division
            12,  // 2: Village
            12,  // 3: Small Group
            12,  // 4: GN Division
            18,  // 5: Member Name
            15,  // 6: NIC Number
            12,  // 7: Unique ID
            15,  // 8: Old Account Number
            15,  // 9: Savings (numeric)
            15,  // 10: Other Income (numeric)
            15,  // 11: Death Subscription (numeric)
            15,  // 12: Count of Total Loans (numeric)
            15,  // 13: Total Loans (numeric)
            15,  // 14: Active Loans (numeric)
            15,  // 15: Active Loan Amount (numeric)
            15,  // 16: Loan Outstanding (numeric)
            12,  // 17: Due Terms
            15,  // 18: Principal Arrears (numeric)
            15,  // 19: Interest Arrears (numeric)
            15,  // 20: Profession Type
            15,  // 21: Profession
            15,  // 22: Phone Number
            20,  // 23: Address
            15,  // 24: NIC Issue Date
            15,  // 25: Marital Status
            15,  // 26: Date Of Birth
            12,  // 27: Age
            18,  // 28: Follower Name
            20,  // 29: Follower Address
            15,  // 30: Follower NIC Number
            15,  // 31: Follower Issue Date
            12,  // 32: Status
            15,  // 33: Status Type
            12   // 34: Location
        ];
        
        // Create the table with header only on first page and footer only on last page
        doc.autoTable({
            head: [header],
            body: data,
            foot: [totalsRow],
            startY: 30,
            theme: 'grid',
            styles: {
                fontSize: 7,
                cellPadding: 2
            },
            headStyles: {
                fillColor: [41, 128, 185],
                textColor: 255,
                fontStyle: 'bold',
                fontSize: 8
            },
            footStyles: {
                fillColor: [41, 128, 185],
                textColor: 255,
                fontStyle: 'bold',
                fontSize: 8
            },
            columnStyles: columnWidths.reduce((styles, width, index) => {
                styles[index] = { cellWidth: width };
                if ([9, 10, 11, 12, 13, 14, 15, 16, 18, 19].includes(index)) {
                    styles[index].halign = 'right';
                }
                return styles;
            }, {}),
            showHead: 'firstPage',
            showFoot: 'lastPage',
            margin: { top: 30, right: 10, bottom: 20, left: 10 }
        });
        
        // Add copyright text at the bottom of the last page
        const pageCount = doc.getNumberOfPages();
        doc.setPage(pageCount);
        doc.setFontSize(10);
        doc.setTextColor(100, 100, 100);
        doc.text(copyrightText, doc.internal.pageSize.getWidth() / 2, doc.internal.pageSize.getHeight() - 10, { align: 'center' });
        
        // Save the PDF
        doc.save('member_report.pdf');
        
        hideLoading();
    });
    
    // Print table
    printTableBtn.addEventListener('click', function() {
        if (filteredRows.length === 0) {
            alert('No data to print');
            return;
        }
        
        // Get visible column indices
        const visibleColumns = [];
        for (let i = 0; i < columnNames.length; i++) {
            if (columnVisibility[i]) {
                visibleColumns.push(i);
            }
        }
        
        // Calculate totals
        const totals = calculateTotalsForFilteredRows();
        
        // Create totals row for print
        const totalsRow = [];
        visibleColumns.forEach(colIndex => {
            if (colIndex === 9) { // Savings
                totalsRow.push(`<strong>Total: ${totals.savings.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</strong>`);
            } else if (colIndex === 10) { // Other Income
                totalsRow.push(`<strong>Total: ${totals.otherIncome.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</strong>`);
            } else if (colIndex === 11) { // Death Subscription
                totalsRow.push(`<strong>Total: ${totals.deathSub.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</strong>`);
            } else if (colIndex === 12) { // Count of Total Loans
                totalsRow.push(`<strong>Total: ${totals.totalLoanCount.toLocaleString()}</strong>`);
            } else if (colIndex === 13) { // Total Loans
                totalsRow.push(`<strong>Total: ${totals.totalLoans.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</strong>`);
            } else if (colIndex === 14) { // Active Loans
                totalsRow.push(`<strong>Total: ${totals.activeLoanCount.toLocaleString()}</strong>`);
            } else if (colIndex === 15) { // Active Loan Amount
                totalsRow.push(`<strong>Total: ${totals.activeLoanAmount.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</strong>`);
            } else if (colIndex === 16) { // Loan Outstanding
                totalsRow.push(`<strong>Total: ${totals.loanOutstanding.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</strong>`);
            } else if (colIndex === 18) { // Principal Arrears
                totalsRow.push(`<strong>Total: ${totals.principalArrears.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</strong>`);
            } else if (colIndex === 19) { // Interest Arrears
                totalsRow.push(`<strong>Total: ${totals.interestArrears.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</strong>`);
            } else {
                totalsRow.push('');
            }
        });
        
        // Create a new window for printing
        const printWindow = window.open('', '_blank');
        printWindow.document.write(`
            <!DOCTYPE html>
            <html>
            <head>
                <title>Member Report</title>
                <style>
                    body {
                        font-family: Arial, sans-serif;
                        margin: 20px;
                        font-size: 12px;
                    }
                    table {
                        width: 100%;
                        border-collapse: collapse;
                        margin-bottom: 20px;
                    }
                    th, td {
                        border: 1px solid #ddd;
                        padding: 8px;
                        text-align: left;
                    }
                    th {
                        background-color: #f2f2f2;
                        font-weight: bold;
                    }
                    .header {
                        margin-bottom: 20px;
                    }
                    .header h1 {
                        margin: 0;
                        font-size: 24px;
                    }
                    .header p {
                        margin: 5px 0;
                        font-size: 14px;
                    }
                    .totals-row td {
                        background-color: #f9f9f9;
                        font-weight: bold;
                    }
                    .copyright {
                        margin-top: 30px;
                        text-align: center;
                        font-size: 10px;
                        color: #666;
                    }
                    @media print {
                        .no-print {
                            display: none;
                        }
                    }
                </style>
            </head>
            <body>
                <div class="header">
                    <h1>Member Report</h1>
                    <p>As on Date: ${document.getElementById('filter_date').value}</p>
                </div>
                <table>
                    <thead>
                        <tr>
                            ${visibleColumns.map(index => `<th>${columnNames[index]}</th>`).join('')}
                        </tr>
                    </thead>
                    <tbody>
                        ${filteredRows.map(row => {
                            const cells = visibleColumns.map(colIndex => {
                                const cell = row.querySelector(`td[data-column="${colIndex}"]`);
                                return cell ? `<td>${cell.textContent.trim()}</td>` : '<td></td>';
                            }).join('');
                            return `<tr>${cells}</tr>`;
                        }).join('')}
                        <tr class="totals-row">
                            ${totalsRow.map(cell => `<td>${cell}</td>`).join('')}
                        </tr>
                    </tbody>
                </table>
                <div class="copyright">
                    ${copyrightText}
                </div>
                <div class="no-print" style="margin-top: 20px;">
                    <button onclick="window.print()">Print</button>
                    <button onclick="window.close()">Close</button>
                </div>
            </body>
            </html>
        `);
        printWindow.document.close();
    });
    
    // Initialize filter data structures
    buildFilterData();
    
    // Populate all filters
    populateDivisionFilter();
    populateProfessionTypeFilter();
    populateMaritalStatusFilter();
    populateStatusTypeFilter();
    
    // Initialize column visibility
    initializeColumnVisibility();
    
    // Initialize search results info
    updateSearchResultsInfo('');
    
    // Initialize summary cards with all data
    updateSummaryCards();
    
    // Initial display
    displayPage(currentPage);
});