        </div>
    </div>

    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        const configs = [
            ['masterBtn', '.master-dropdown-menu'],
            ['loanPrepBtn', '.loanprep-dropdown-menu'],
            ['memberBtn', '.member-dropdown-menu'],
            ['collectorBtn', '.collector-dropdown-menu'],
            ['loanSectionBtn', '.loansection-dropdown-menu'],
            ['modificationBtn', '.modification-dropdown-menu'],
            ['accountsBtn', '.accounts-dropdown-menu'],
            ['reportBtn', '.report-dropdown-menu']
        ];

        const dropdowns = configs.map(([id, selector]) => {
            const btn = document.getElementById(id);
            const menu = document.querySelector(selector);
            if (!btn || !menu) return null;

            btn.addEventListener('click', (e) => {
                e.preventDefault();
                e.stopPropagation();

                // close all others
                dropdowns.forEach(d => d?.menu.classList.remove('show'));

                // toggle current
                menu.classList.toggle('show');
            });

            return { btn, menu };
        });

        // one global outside click handler
        document.addEventListener('click', (e) => {
            dropdowns.forEach(d => {
                if (d && !d.btn.contains(e.target) && !d.menu.contains(e.target)) {
                d.menu.classList.remove('show');
                }
            });
        });
    </script>

    <script>
        // State Master functionality
        let states = [
        { code: "2", name: "WEST BENGAL" }
        ];

        // Function to show State Master
        function showStateMaster() {
            const container = document.getElementById('stateMasterContainer');
            if (container) {
                container.style.display = 'block';
                renderStateTable();
                // Scroll to top smoothly
                container.scrollIntoView({ behavior: 'smooth', block: 'start' });
            }
        }

        // Function to render state table
        function renderStateTable() {
            const tbody = document.getElementById('stateTableBody');
            if (!tbody) return;
            
            tbody.innerHTML = '';
            states.forEach((state, index) => {
                const row = tbody.insertRow();
                row.insertCell(0).textContent = index + 1;
                row.insertCell(1).textContent = state.code;
                row.insertCell(2).textContent = state.name;
                row.insertCell(3).innerHTML = `<button class="btn-delete" onclick="deleteState(${index})"><i class="bi bi-trash"></i> Delete</button>`;
            });
            
            // Update record count
            const recordCount = document.getElementById('recordCount');
            if (recordCount) {
                recordCount.textContent = `${states.length} Record${states.length !== 1 ? 's' : ''}`;
            }
        }

        // Delete state function (make it global)
        window.deleteState = function(index) {
            if (confirm('Are you sure you want to delete this state?')) {
                states.splice(index, 1);
                renderStateTable();
            }
        };

        // Initialize when DOM is ready
        document.addEventListener('DOMContentLoaded', function() {
            // New button
            const newBtn = document.getElementById('newBtn');
            if (newBtn) {
                newBtn.addEventListener('click', function() {
                document.getElementById('stateCode').value = '';
                document.getElementById('stateName').value = '';
                document.getElementById('stateCode').focus();
                });
            }
            
            // Save button
            const saveBtn = document.getElementById('saveBtn');
            if (saveBtn) {
                saveBtn.addEventListener('click', function() {
                const code = document.getElementById('stateCode').value.trim();
                const name = document.getElementById('stateName').value.trim();
                
                if (!code) {
                    alert('Please enter State Code');
                    document.getElementById('stateCode').focus();
                    return;
                }
                
                if (!name) {
                    alert('Please enter State Name');
                    document.getElementById('stateName').focus();
                    return;
                }
                
                // Check for duplicate state code
                if (states.some(state => state.code === code)) {
                    alert('State Code already exists!');
                    return;
                }
                
                states.push({ code: code, name: name.toUpperCase() });
                renderStateTable();
                
                // Clear form after save
                document.getElementById('stateCode').value = '';
                document.getElementById('stateName').value = '';
                document.getElementById('stateCode').focus();
                
                // Show success message
                const saveBtnElement = document.getElementById('saveBtn');
                const originalText = saveBtnElement.innerHTML;
                saveBtnElement.innerHTML = '<i class="bi bi-check-circle"></i> Saved!';
                setTimeout(() => {
                    saveBtnElement.innerHTML = originalText;
                }, 1500);
                });
            }
            
            // Initial render
            renderStateTable();
        });

        // Show/Hide functions for each master
        function showRelationMaster() {
        hideAllContainers();
        document.getElementById('relationMasterContainer').style.display = 'block';
        }

        function showBranchMaster() {
            hideAllContainers();
            document.getElementById('branchMasterContainer').style.display = 'block';

            // Branch Clear button with Prefix
            document.getElementById('branchClearBtn')?.addEventListener('click', function() {
            document.getElementById('branchPrefix').value = '';
            document.getElementById('branchName').value = '';
            document.getElementById('branchCode').value = '';
            document.getElementById('branchAddress').value = '';
            document.getElementById('managerName').value = '';
            document.getElementById('phoneNumber').value = '';
            document.getElementById('openingDate').value = '';
            document.getElementById('next').value = '';
            document.getElementById('previous').value = '';
            });

            // Branch Add button
            document.getElementById('branchAddBtn')?.addEventListener('click', function() {
            const prefix = document.getElementById('branchPrefix').value;
            const branchName = document.getElementById('branchName').value;
            
            if (!prefix || !branchName) {
                alert('Please enter Prefix and Branch Name');
                return;
            }
            
            alert(`Branch Added: ${prefix} - ${branchName}`);
            });
        }

        function showZoneMaster() {
            hideAllContainers();
            document.getElementById('zoneMasterContainer').style.display = 'block';
            // Zone Master functionality
            let zones = [
            { zoneCode: "1", stateCode: "1", zoneName: "ROOTKEY" },
            { zoneCode: "2", stateCode: "1", zoneName: "ROLE/IA" },
            { zoneCode: "", stateCode: "", zoneName: "ROLEA" }
            ];

            function renderZoneTable() {
            const tbody = document.getElementById('zoneTableBody');
            if (!tbody) return;
            
            tbody.innerHTML = '';
            zones.forEach((zone, index) => {
                const row = tbody.insertRow();
                row.insertCell(0).textContent = zone.zoneCode;
                row.insertCell(1).textContent = zone.stateCode;
                row.insertCell(2).textContent = zone.zoneName;
            });
            }

            // Save Zone
            document.getElementById('zoneSaveBtn')?.addEventListener('click', function() {
            const zoneCode = document.getElementById('zoneCode').value.trim();
            const zoneName = document.getElementById('zoneName').value.trim();
            const underState = document.getElementById('underState').value.trim();
            
            if (zoneCode && zoneName) {
                zones.push({ zoneCode: zoneCode, stateCode: underState || '-', zoneName: zoneName });
                renderZoneTable();
                
                // Clear form
                document.getElementById('zoneCode').value = '';
                document.getElementById('zoneName').value = '';
                document.getElementById('underState').value = '';
                
                alert('Zone saved successfully!');
            } else {
                alert('Please enter Zone Code and Zone Name');
            }
            });

            // New Zone button
            document.getElementById('zoneNewBtn')?.addEventListener('click', function() {
            document.getElementById('zoneCode').value = '';
            document.getElementById('zoneName').value = '';
            document.getElementById('underState').value = '';
            document.getElementById('zoneCode').focus();
            });

            // Initial render
            renderZoneTable();
        }

        function hideAllContainers() {
            const containers = ['relationMasterContainer', 'branchMasterContainer', 'zoneMasterContainer'];
            containers.forEach(id => {
                const el = document.getElementById(id);
                if (el) el.style.display = 'none';
            });
        }

        // Relation selection
        document.addEventListener('DOMContentLoaded', function() {
            const relationSpans = document.querySelectorAll('#relationGrid span');
            const selectedDiv = document.getElementById('selectedRelation');
            
            relationSpans.forEach(span => {
                span.addEventListener('click', function() {
                relationSpans.forEach(s => s.classList.remove('active'));
                this.classList.add('active');
                if (selectedDiv) selectedDiv.textContent = this.textContent;
                });
            });
        
            // Exit buttons
            const exitBtns = ['relationExitBtn', 'branchExitBtn'];
            exitBtns.forEach(id => {
                const btn = document.getElementById(id);
                if (btn) {
                btn.addEventListener('click', () => hideAllContainers());
                }
            });
        
            // Clear buttons
            const clearBtn = document.getElementById('relationClearBtn');
            if (clearBtn) {
                clearBtn.addEventListener('click', () => {
                document.getElementById('selectedRelation').textContent = 'Select Relation';
                document.querySelectorAll('#relationGrid span').forEach(s => s.classList.remove('active'));
                });
            }
        });

        // Show Company Profile
        function showCompanyProfile() {
        hideAllContainers();
        document.getElementById('companyProfileContainer').style.display = 'block';
        }

        // Clear Company Profile Form
        document.getElementById('companyClearBtn')?.addEventListener('click', function() {
            document.getElementById('companyName').value = '';
            document.getElementById('shortName').value = '';
            document.getElementById('about').value = '';
            document.getElementById('cin').value = '';
            document.getElementById('pan').value = '';
            document.getElementById('tan').value = '';
            document.getElementById('gstin').value = '';
            document.getElementById('category').value = '';
            document.getElementById('class').value = '';
            document.getElementById('authorizedCapital').value = '';
            document.getElementById('paidUpCapital').value = '';
            document.getElementById('shareValue').value = '';
            document.getElementById('stateRegistration').value = '';
            document.getElementById('incorporationDate').value = '';
            document.getElementById('address').value = '';
            document.getElementById('email').value = '';
            document.getElementById('phoneNo').value = '';
            document.getElementById('landline').value = '';

            // Reset radio buttons
            document.querySelector('input[name="allocateShare"][value="No"]').checked = true;
            document.querySelector('input[name="splitShare"][value="No"]').checked = true;
        });

        // Save Company Profile
        document.getElementById('companySaveBtn')?.addEventListener('click', function() {
            alert('Company Profile Saved Successfully!');
        });

        // Exit
        document.getElementById('companyExitBtn')?.addEventListener('click', function() {
            document.getElementById('companyProfileContainer').style.display = 'none';
        });

        // Rank Master Data
        let ranks = [
        { rank: "1", designation: "CLERICAL" },
        { rank: "2", designation: "RECEPTIONIST" },
        { rank: "3", designation: "BACK OFFICE EXECUTIVE" },
        { rank: "4", designation: "FRONT OFFICE EXECUTIVE" },
        { rank: "5", designation: "BRANCH COORDINATOR" },
        { rank: "6", designation: "HO COORDINATOR" },
        { rank: "7", designation: "FIELD OFFICER" },
        { rank: "8", designation: "LOAN OFFICER" },
        { rank: "9", designation: "" },
        { rank: "10", designation: "" },
        { rank: "11", designation: "" },
        { rank: "12", designation: "ASSISTANT BR MANAGER" },
        { rank: "13", designation: "BRANCH MANAGER" },
        { rank: "14", designation: "BRANCH HEAD" },
        { rank: "15", designation: "CLUSTER HEAD" }
        ];

        function renderRankTable() {
        const tbody = document.getElementById('rankTableBody');
        tbody.innerHTML = '';
        ranks.forEach((rank, index) => {
            tbody.innerHTML += `<tr><td>${rank.rank}</td><td>${rank.designation}</td><td><button class="btn-delete-row" onclick="deleteRank(${index})"><i class="bi bi-trash"></i></button></td></tr>`;
        });
        }

        function deleteRank(index) {
        ranks.splice(index, 1);
        renderRankTable();
        }

        // Add new rank
        document.getElementById('rankAddBtn')?.addEventListener('click', function() {
        const rank = document.getElementById('rankInput').value;
        const designation = document.getElementById('designationInput').value;
        if (rank && designation) {
            ranks.push({ rank: rank, designation: designation });
            renderRankTable();
            document.getElementById('rankInput').value = '';
            document.getElementById('designationInput').value = '';
        } else {
            alert('Please enter both Rank and Designation');
        }
        });

        // Trash Last
        document.getElementById('rankTrashBtn')?.addEventListener('click', function() {
        ranks.pop();
        renderRankTable();
        });

        // Preview Update for Code Sequence
        function updatePreview(type) {
        const prefix = document.getElementById(`${type}Prefix`).value;
        const digits = parseInt(document.getElementById(`${type}Digits`).value);
        const lastNo = parseInt(document.getElementById(`${type}LastNo`).value);
        const padded = String(lastNo + 1).padStart(digits, '0');
        document.getElementById(`${type}Preview`).value = prefix + padded;
        }

        // Show functions
        function showRankMaster() { hideAllContainers(); document.getElementById('rankMasterContainer').style.display = 'block'; }
        function showAccountsCode() { hideAllContainers(); document.getElementById('accountsCodeContainer').style.display = 'block'; }
        function showGlobalConfig() { hideAllContainers(); document.getElementById('globalConfigContainer').style.display = 'block'; }
        
        // Individual Save functions for each section
        function saveRegdFees() {
        const memberFees = document.getElementById('memberFees').value;
        const collectorFees = document.getElementById('collectorFees').value;
        alert(`Regd. Fees Saved!\nMember: ${memberFees}\nCollector: ${collectorFees}`);
        }

        function saveGoldRate() {
        const goldRate = document.getElementById('goldRate').value;
        const silverRate = document.getElementById('silverRate').value;
        alert(`Gold Rate Saved!\nGold: ₹${goldRate}/gm\nSilver: ₹${silverRate}/gm`);
        }

        function saveTDS() {
        const tdsPan = document.getElementById('tdsPan').value;
        const tdsWithoutPan = document.getElementById('tdsWithoutPan').value;
        alert(`TDS Configuration Saved!\nWith PAN: ${tdsPan}%\nWithout PAN: ${tdsWithoutPan}%`);
        }

        function saveLoanFine() {
        const gracePeriod = document.getElementById('gracePeriod').value;
        const finePercent = document.getElementById('finePercent').value;
        const fineInterval = document.getElementById('fineInterval').value;
        alert(`Loan EMI Fine Saved!\nGrace Period: ${gracePeriod} days\nFine: ${finePercent}%\nInterval: ${fineInterval}`);
        }

        function saveOpeningBalance() {
        const openingDate = document.getElementById('openingBalanceDate').value;
        alert(`Opening Balance Date Saved!\nDate: ${openingDate}`);
        }

        function saveNOF() {
        const nof = document.getElementById('nof').value;
        alert(`Net Owned Fund [NOF] Saved!\nNOF: ₹${nof}`);
        }

        // Clear All Configurations
        document.getElementById('configClearBtn')?.addEventListener('click', function() {
        document.getElementById('memberFees').value = '0/500';
        document.getElementById('collectorFees').value = '0';
        document.getElementById('goldRate').value = '3500';
        document.getElementById('silverRate').value = '150';
        document.getElementById('tdsPan').value = '20';
        document.getElementById('tdsWithoutPan').value = '30';
        document.getElementById('gracePeriod').value = '30';
        document.getElementById('finePercent').value = '5';
        document.getElementById('fineInterval').value = '0';
        document.getElementById('openingBalanceDate').value = '02/03/2017';
        document.getElementById('nof').value = '0';
        alert('All configurations cleared!');
        });

        // Exit
        document.getElementById('configExitBtn')?.addEventListener('click', function() {
        document.getElementById('globalConfigContainer').style.display = 'none';
        });

        // Show function
        function showGlobalConfig() {
        hideAllContainers();
        document.getElementById('globalConfigContainer').style.display = 'block';
        }

        // Biometric Scanner - Complete Functionality
        let isInitialized = false;
        let isCapturing = false;
        let capturedFingerprint = null;
        let isoFingerprintData = null;
        let ansiFingerprintData = null;
        let fingerprintImageData = null;

        // Show Biometric Scanner
        function showBiometricScanner() {
            hideAllContainers();
            document.getElementById('biometricScannerContainer').style.display = 'block';
        }

        // Check Device
        document.getElementById('checkDeviceBtn')?.addEventListener('click', function() {
            const deviceVersion = document.getElementById('deviceVersion');
            const deviceName = document.getElementById('deviceName');
            
            deviceVersion.textContent = 'v2.1.0';
            deviceName.textContent = 'DigitalPersona U.are.U 4500';
            
            alert('Device Check Complete!\nDevice: DigitalPersona U.are.U 4500\nVersion: v2.1.0\nStatus: Ready');
        });

        // Init Device
        document.getElementById('initBtn')?.addEventListener('click', function() {
            isInitialized = true;
            document.getElementById('deviceStatus').textContent = 'Initialized';
            document.getElementById('deviceStatus').style.color = '#10b981';
            alert('Device initialized successfully!');
        });

        // Uninit Device
        document.getElementById('uninitBtn')?.addEventListener('click', function() {
            isInitialized = false;
            isCapturing = false;
            document.getElementById('deviceStatus').textContent = 'Not Initialized';
            document.getElementById('deviceStatus').style.color = '#ef4444';
            alert('Device uninitialized.');
        });

        // Start Capture
        document.getElementById('startCaptureBtn')?.addEventListener('click', function() {
            if (!isInitialized) {
                alert('Please initialize the device first (Click Init)');
                return;
            }
            
            isCapturing = true;
            const timeout = parseInt(document.getElementById('timeoutValue').value) || 5000;
            const qualityThreshold = parseInt(document.getElementById('qualityThreshold').value) || 50;
            
            alert(`Capture started!\nTimeout: ${timeout}ms\nQuality Threshold: ${qualityThreshold}%\nPlease place finger on scanner...`);
            
            // Simulate capture after delay
            setTimeout(() => {
                if (isCapturing) {
                simulateFingerprintCapture();
                }
            }, 2000);
        });

        // Stop Capture
        document.getElementById('stopCaptureBtn')?.addEventListener('click', function() {
            isCapturing = false;
            alert('Capture stopped.');
        });

        // Simulate Fingerprint Capture
        function simulateFingerprintCapture() {
            const fingerSelect = document.getElementById('fingerSelect');
            const selectedFinger = fingerSelect.options[fingerSelect.selectedIndex].text;
            const qualityScore = Math.floor(Math.random() * 30) + 65; // Random score 65-95
            
            capturedFingerprint = {
                finger: selectedFinger,
                timestamp: new Date().toLocaleString(),
                quality: qualityScore,
                isoData: 'ISO_' + Math.random().toString(36).substring(2, 20).toUpperCase(),
                ansiData: 'ANSI_' + Math.random().toString(36).substring(2, 20).toUpperCase()
            };
            
            isoFingerprintData = capturedFingerprint.isoData;
            ansiFingerprintData = capturedFingerprint.ansiData;
            
            document.getElementById('isoData').value = isoFingerprintData;
            document.getElementById('ansiData').value = ansiFingerprintData;
        
            // Update detect status
            const detectStatus = document.getElementById('detectStatus');
            detectStatus.innerHTML = '<span>✓ Finger detected - ' + selectedFinger + '</span>';
            detectStatus.classList.add('finger-detected');
            
            alert(`Fingerprint captured!\nFinger: ${selectedFinger}\nQuality: ${qualityScore}%`);
        }

        // Detect Finger
        document.getElementById('detectFingerBtn')?.addEventListener('click', function() {
            if (!isInitialized) {
                alert('Please initialize the device first (Click Init)');
                return;
            }
            
            const detectStatus = document.getElementById('detectStatus');
            
            if (capturedFingerprint) {
                detectStatus.innerHTML = '<span>✓ Finger detected - ' + capturedFingerprint.finger + '</span>';
                detectStatus.classList.add('finger-detected');
                alert('Finger detected on scanner!');
            } else {
                detectStatus.innerHTML = '<span>✗ No finger detected</span>';
                detectStatus.classList.remove('finger-detected');
                alert('No finger detected. Please place finger on scanner.');
            }
        });

        // Clear Image
        document.getElementById('clearImageBtn')?.addEventListener('click', function() {
            capturedFingerprint = null;
            isoFingerprintData = null;
            ansiFingerprintData = null;
            fingerprintImageData = null;
            
            document.getElementById('isoData').value = '';
            document.getElementById('ansiData').value = '';
            document.getElementById('detectStatus').innerHTML = '<span>No finger detected</span>';
            document.getElementById('detectStatus').classList.remove('finger-detected');
            
            const previewDiv = document.getElementById('fingerprintPreview');
            previewDiv.innerHTML = '<div class="preview-placeholder"><i class="bi bi-fingerprint"></i><span>No fingerprint captured</span></div>';
            previewDiv.classList.remove('has-image');
                
            document.getElementById('qualityScore').style.display = 'none';
            
            alert('Fingerprint image cleared!');
        });

        // Show Preview
        document.getElementById('showPreviewBtn')?.addEventListener('click', function() {
            if (!capturedFingerprint) {
                alert('No fingerprint captured. Please capture a fingerprint first.');
                return;
            }
            
            const previewDiv = document.getElementById('fingerprintPreview');
            previewDiv.innerHTML = `<div class="preview-placeholder"><i class="bi bi-fingerprint" style="font-size: 4rem; color: #4f46e5;"></i><span>${capturedFingerprint.finger}</span><small style="display: block; margin-top: 5px;">Captured: ${capturedFingerprint.timestamp}</small></div>`;
            previewDiv.classList.add('has-image');
            
            alert('Fingerprint preview displayed!');
        });

        // Check Quality
        document.getElementById('checkQualityBtn')?.addEventListener('click', function() {
            if (!capturedFingerprint) {
                alert('No fingerprint captured. Please capture a fingerprint first.');
                return;
            }
            
            const qualityScore = capturedFingerprint.quality || Math.floor(Math.random() * 30) + 65;
            const qualityElement = document.getElementById('qualityScore');
            const qualityValue = document.getElementById('qualityValue');
            
            qualityValue.textContent = qualityScore;
            qualityElement.style.display = 'block';
            
            let qualityText = '';
            if (qualityScore >= 80) qualityText = 'Excellent';
            else if (qualityScore >= 60) qualityText = 'Good';
            else if (qualityScore >= 40) qualityText = 'Fair';
            else qualityText = 'Poor';
            
            alert(`Fingerprint Quality: ${qualityScore}% (${qualityText})`);
        });

        // Match ISO
        document.getElementById('matchIsoBtn')?.addEventListener('click', function() {
            if (!isoFingerprintData) {
                alert('No ISO fingerprint data available. Please capture a fingerprint first.');
                return;
            }
            alert(`ISO Matching initiated...\nData: ${isoFingerprintData}\nMatch Result: 98.7% match score`);
        });

        // Match ANSI
        document.getElementById('matchAnsiBtn')?.addEventListener('click', function() {
            if (!ansiFingerprintData) {
                alert('No ANSI fingerprint data available. Please capture a fingerprint first.');
                return;
            }
            alert(`ANSI Matching initiated...\nData: ${ansiFingerprintData}\nMatch Result: 97.2% match score`);
        });

        // Set as User Fingerprint
        document.getElementById('setFingerprintBtn')?.addEventListener('click', function() {
            const userName = document.getElementById('userName').value.trim();
            const fingerSelect = document.getElementById('fingerSelect');
            const selectedFinger = fingerSelect.options[fingerSelect.selectedIndex].text;
            
            if (!userName) {
                alert('Please enter User Name');
                document.getElementById('userName').focus();
                return;
            }
        
            if (!capturedFingerprint) {
                alert('No fingerprint captured. Please capture a fingerprint first.');
                return;
            }
            
            alert(`Fingerprint saved successfully for user: ${userName}\nFinger: ${selectedFinger}\nISO: ${isoFingerprintData}\nANSI: ${ansiFingerprintData}`);
        });

        // Clear All
        document.getElementById('biometricClearBtn')?.addEventListener('click', function() {
            capturedFingerprint = null;
            isoFingerprintData = null;
            ansiFingerprintData = null;
            fingerprintImageData = null;
            isCapturing = false;
            
            document.getElementById('isoData').value = '';
            document.getElementById('ansiData').value = '';
            document.getElementById('userName').value = '';
            document.getElementById('fingerSelect').selectedIndex = 0;
            document.getElementById('timeoutValue').value = '5000';
            document.getElementById('qualityThreshold').value = '50';
            document.getElementById('detectStatus').innerHTML = '<span>No finger detected</span>';
            document.getElementById('detectStatus').classList.remove('finger-detected');
            
            const previewDiv = document.getElementById('fingerprintPreview');
            previewDiv.innerHTML = '<div class="preview-placeholder"><i class="bi bi-fingerprint"></i><span>No fingerprint captured</span></div>';
            previewDiv.classList.remove('has-image');
            
            document.getElementById('qualityScore').style.display = 'none';
            
            alert('All fingerprint data cleared!');
        });

        // Exit
        document.getElementById('biometricExitBtn')?.addEventListener('click', function() {
            document.getElementById('biometricScannerContainer').style.display = 'none';
        });

        // User Master Functionality
        let selectedUserRow = null;

        // Show User Master
        function showUserMaster() {
            hideAllContainers();
            document.getElementById('userMasterContainer').style.display = 'block';
        }

        // Select user from table
        function selectUser(userId, userType, loginBranch, fullName) {
            // Remove previous selection highlight
            if (selectedUserRow) {
                selectedUserRow.classList.remove('selected');
            }
            
            // Highlight current row
            const rows = document.querySelectorAll('#userMasterBody tr');
            for (let row of rows) {
                if (row.cells[0].innerText === userId || 
                    (userId === '' && row.cells[1].innerText === userType)) {
                row.classList.add('selected');
                selectedUserRow = row;
                break;
                }
            }
            
            // Populate form fields
            document.getElementById('userId').value = userId || '';
            document.getElementById('userType').value = userType || '';
                
            // Populate Login Branch checkboxes
            const branchCheckboxes = document.querySelectorAll('.branch-list input');
            branchCheckboxes.forEach(cb => {
                cb.checked = (cb.id === 'branchHowrah' && loginBranch === 'HEAD OFFICE');
            });
            
            // Populate User Type Access checkboxes based on user type
            const accessCheckboxes = document.querySelectorAll('.access-list input');
            accessCheckboxes.forEach(cb => {
                cb.checked = false;
            });
                
            if (userType === 'Administrator') {
                document.getElementById('accessHowrah').checked = true;
                document.getElementById('accessMicroBdl').checked = true;
                document.getElementById('accessMicroBrCoord').checked = true;
                document.getElementById('accessMicroBroHly').checked = true;
                document.getElementById('accessMicroHlyLo').checked = true;
                document.getElementById('accessMicroHoManager').checked = true;
                document.getElementById('accessMicroHoRecept').checked = true;
                document.getElementById('accessMicroNbdLo').checked = true;
            }
            
            // Clear mobile and email
            document.getElementById('mobileNo').value = '';
            document.getElementById('emailId').value = '';
            
            // Set access checkboxes based on user type
            if (userType === 'MICRO HO MANA.' || userType === 'MICRO HO EXE') {
                document.getElementById('allPlanAccess').checked = true;
                document.getElementById('allBranchAccess').checked = true;
            }
        }

        // Save User
        document.getElementById('userSaveBtn')?.addEventListener('click', function() {
            const userId = document.getElementById('userId').value;
            const userType = document.getElementById('userType').value;
            const mobileNo = document.getElementById('mobileNo').value;
            const emailId = document.getElementById('emailId').value;
            
            if (!userId) {
                alert('Please enter User ID');
                return;
            }
            
            // Collect selected branches
            const selectedBranches = [];
            document.querySelectorAll('.branch-list input:checked').forEach(cb => {
                selectedBranches.push(cb.nextElementSibling.innerText);
            });
            
            // Collect selected access types
            const selectedAccess = [];
            document.querySelectorAll('.access-list input:checked').forEach(cb => {
                selectedAccess.push(cb.nextElementSibling.innerText);
            });
            
            // Collect access permissions
            const allPlanAccess = document.getElementById('allPlanAccess').checked;
            const allBranchAccess = document.getElementById('allBranchAccess').checked;
            const rankAuto = document.getElementById('rankAuto').checked;
            const backDate = document.getElementById('backDate').checked;
            const rePrint = document.getElementById('rePrint').checked;
            const allRepBranch = document.getElementById('allRepBranch').checked;
            
            alert(`User Saved Successfully!\n\nUser ID: ${userId}\nUser Type: ${userType}\nMobile: ${mobileNo}\nEmail: ${emailId}\n\nAccess:\n- All Plan Access: ${allPlanAccess ? 'Yes' : 'No'}\n- All Branch Access: ${allBranchAccess ? 'Yes' : 'No'}\n- Rank Auto: ${rankAuto ? 'Yes' : 'No'}\n- Back Date: ${backDate ? 'Yes' : 'No'}\n- Re-Print: ${rePrint ? 'Yes' : 'No'}\n- All Rep Branch: ${allRepBranch ? 'Yes' : 'No'}\n\nBranches: ${selectedBranches.join(', ') || 'None'}\nAccess Types: ${selectedAccess.join(', ') || 'None'}`);
        });

        // Delete User
        document.getElementById('userDeleteBtn')?.addEventListener('click', function() {
            const userId = document.getElementById('userId').value;
            if (!userId) {
                alert('No user selected to delete');
                return;
            }
            
            if (confirm(`Are you sure you want to delete user "${userId}"?`)) {
                // Remove from table
                if (selectedUserRow) {
                selectedUserRow.remove();
                selectedUserRow = null;
                }
                
                // Clear form
                document.getElementById('userId').value = '';
                document.getElementById('password').value = '';
                document.getElementById('userType').value = '';
                document.getElementById('mobileNo').value = '';
                document.getElementById('emailId').value = '';
                
                // Uncheck all checkboxes
                document.querySelectorAll('.access-checkboxes input').forEach(cb => cb.checked = false);
                document.querySelectorAll('.branch-list input').forEach(cb => cb.checked = false);
                document.querySelectorAll('.access-list input').forEach(cb => cb.checked = false);
                
                alert('User deleted successfully!');
            }
        });

        // Clear Form
        document.getElementById('userClearBtn')?.addEventListener('click', function() {
            document.getElementById('userId').value = '';
            document.getElementById('password').value = '';
            document.getElementById('userType').value = '';
            document.getElementById('mobileNo').value = '';
            document.getElementById('emailId').value = '';
            
            // Uncheck all checkboxes
            document.querySelectorAll('.access-checkboxes input').forEach(cb => cb.checked = false);
            document.querySelectorAll('.branch-list input').forEach(cb => cb.checked = false);
            document.querySelectorAll('.access-list input').forEach(cb => cb.checked = false);
            
            // Remove selection highlight
            if (selectedUserRow) {
                selectedUserRow.classList.remove('selected');
                selectedUserRow = null;
            }
            
            alert('Form cleared!');
        });

        // Exit
        document.getElementById('userExitBtn')?.addEventListener('click', function() {
            document.getElementById('userMasterContainer').style.display = 'none';
        });

        // ========== AREA SURVEY MANAGEMENT ==========
        // Function to show Area Survey (call this from your navigation link)
        function showAreaSurvey() {
            // Hide all other content sections if they exist
            const allSections = document.querySelectorAll('.content-section, .branch-master-container');
            allSections.forEach(section => {
                if (section) section.style.display = 'none';
            });
            
            // Show the Area Survey container
            const surveyContainer = document.querySelector('.area-survey-container');
            if (surveyContainer) {
                surveyContainer.style.display = 'block';
            }

            initializeAreaSurvey();
        }

        let areaSurveyInitialized = false;

        // Function to initialize all Area Survey functionality
        function initializeAreaSurvey() {

            if (areaSurveyInitialized) return;
            areaSurveyInitialized = true;

            // Get all form elements
            const zoneCodeInput = document.getElementById('zoneCode');
            const surveyDateInput = document.getElementById('surveyDate');
            const zoneNameInput = document.getElementById('zoneName');
            const villageNameInput = document.getElementById('villageName');
            const branchInput = document.getElementById('branch');
            const areaTypeInput = document.getElementById('areaType');
            const foNameInput = document.getElementById('foName');
            const foCodeInput = document.getElementById('foCode');
            const populationInput = document.getElementById('population');
            const politicalSituationSelect = document.getElementById('politicalSituation');
            const lawOrderSelect = document.getElementById('lawOrder');
            const distanceInput = document.getElementById('distance');
            const centresPossibleInput = document.getElementById('centresPossible');
            const mfiWorkingInput = document.getElementById('mfiWorking');
            const majorOperationInput = document.getElementById('majorOperation');
            const roadStatusSelect = document.getElementById('roadStatus');
            const casteGeneral = document.getElementById('casteGeneral');
            const casteST = document.getElementById('casteST');
            const casteOBC = document.getElementById('casteOBC');
            const casteOthers = document.getElementById('casteOthers');
            const religionHindu = document.getElementById('religionHindu');
            const religionMuslim = document.getElementById('religionMuslim');
            const religionSikh = document.getElementById('religionSikh');
            const religionChristian = document.getElementById('religionChristian');
            const religionOthers = document.getElementById('religionOthers');
            const newBtn = document.getElementById('newBtn');
            const saveBtn = document.getElementById('saveBtn');
            const updateBtn = document.getElementById('updateBtn');
            const deleteBtn = document.getElementById('deleteBtn');
            const messageDiv = document.getElementById('messageArea');
            
            const STORAGE_KEY = 'areaSurvey_currentRecord';

              // Hide all other content sections if they exist
            const allSections = document.querySelectorAll('.content-section, .branch-master-container');
            allSections.forEach(section => {
                if (section) section.style.display = 'none';
            });
            
            // Hide any other visible containers
            const otherContainers = document.querySelectorAll('.some-other-container, .dashboard-container');
            otherContainers.forEach(container => {
                if (container) container.style.display = 'none';
            });
            
            // Show the Area Survey container
            const surveyContainer = document.querySelector('.area-survey-container');
            if (surveyContainer) {
                surveyContainer.style.display = 'block';
            }
            
            // Helper: Show message
            function showMessage(text, isError = false) {
                if (!messageDiv) return;
                messageDiv.innerHTML = text;
                messageDiv.style.borderLeftColor = isError ? '#ef4444' : '#2a7f6e';
                messageDiv.style.backgroundColor = isError ? '#fef2f2' : '#f0fdf9';
                setTimeout(() => {
                    if (messageDiv.innerHTML === text) {
                        messageDiv.innerHTML = '';
                        messageDiv.style.borderLeftColor = '#2a7f6e';
                        messageDiv.style.backgroundColor = '#f8fafc';
                    }
                }, 3000);
            }
            
            // Helper: Get current form data
            function getCurrentFormData() {
                return {
                    zoneCode: zoneCodeInput ? zoneCodeInput.value.trim() : '',
                    surveyDate: surveyDateInput ? surveyDateInput.value : '',
                    zoneName: zoneNameInput ? zoneNameInput.value.trim() : '',
                    villageName: villageNameInput ? villageNameInput.value.trim() : '',
                    branch: branchInput ? branchInput.value.trim() : '',
                    areaType: areaTypeInput ? areaTypeInput.value.trim() : 'FULAL',
                    foName: foNameInput ? foNameInput.value.trim() : '',
                    foCode: foCodeInput ? foCodeInput.value.trim() : '',
                    population: populationInput && populationInput.value ? parseInt(populationInput.value) : '',
                    politicalSituation: politicalSituationSelect ? politicalSituationSelect.value : '',
                    lawOrder: lawOrderSelect ? lawOrderSelect.value : '',
                    distance: distanceInput && distanceInput.value ? parseFloat(distanceInput.value) : '',
                    centresPossible: centresPossibleInput && centresPossibleInput.value ? parseInt(centresPossibleInput.value) : '',
                    mfiWorking: mfiWorkingInput && mfiWorkingInput.value ? parseInt(mfiWorkingInput.value) : '',
                    majorOperation: majorOperationInput ? majorOperationInput.value.trim() : '',
                    roadStatus: roadStatusSelect ? roadStatusSelect.value : '',
                    caste: {
                        general: casteGeneral && casteGeneral.value ? parseInt(casteGeneral.value) : '',
                        st: casteST && casteST.value ? parseInt(casteST.value) : '',
                        obc: casteOBC && casteOBC.value ? parseInt(casteOBC.value) : '',
                        others: casteOthers && casteOthers.value ? parseInt(casteOthers.value) : ''
                    },
                    religion: {
                        hindu: religionHindu && religionHindu.value ? parseInt(religionHindu.value) : '',
                        muslim: religionMuslim && religionMuslim.value ? parseInt(religionMuslim.value) : '',
                        sikh: religionSikh && religionSikh.value ? parseInt(religionSikh.value) : '',
                        christian: religionChristian && religionChristian.value ? parseInt(religionChristian.value) : '',
                        others: religionOthers && religionOthers.value ? parseInt(religionOthers.value) : ''
                    }
                };
            }
            
            // Helper: Populate form with data
            function populateForm(data) {
                if (!data) return;
                if (zoneCodeInput) zoneCodeInput.value = data.zoneCode || '';
                if (surveyDateInput) surveyDateInput.value = data.surveyDate || '2024-01-29';
                if (zoneNameInput) zoneNameInput.value = data.zoneName || '';
                if (villageNameInput) villageNameInput.value = data.villageName || '';
                if (branchInput) branchInput.value = data.branch || '';
                if (areaTypeInput) areaTypeInput.value = data.areaType || 'FULAL';
                if (foNameInput) foNameInput.value = data.foName || '';
                if (foCodeInput) foCodeInput.value = data.foCode || '';
                if (populationInput) populationInput.value = data.population !== '' && data.population !== undefined ? data.population : '';
                if (politicalSituationSelect) politicalSituationSelect.value = data.politicalSituation || '';
                if (lawOrderSelect) lawOrderSelect.value = data.lawOrder || '';
                if (distanceInput) distanceInput.value = data.distance !== '' && data.distance !== undefined ? data.distance : '';
                if (centresPossibleInput) centresPossibleInput.value = data.centresPossible !== '' && data.centresPossible !== undefined ? data.centresPossible : '';
                if (mfiWorkingInput) mfiWorkingInput.value = data.mfiWorking !== '' && data.mfiWorking !== undefined ? data.mfiWorking : '';
                if (majorOperationInput) majorOperationInput.value = data.majorOperation || '';
                if (roadStatusSelect) roadStatusSelect.value = data.roadStatus || '';
                if (data.caste) {
                    if (casteGeneral) casteGeneral.value = data.caste.general !== '' && data.caste.general !== undefined ? data.caste.general : '';
                    if (casteST) casteST.value = data.caste.st !== '' && data.caste.st !== undefined ? data.caste.st : '';
                    if (casteOBC) casteOBC.value = data.caste.obc !== '' && data.caste.obc !== undefined ? data.caste.obc : '';
                    if (casteOthers) casteOthers.value = data.caste.others !== '' && data.caste.others !== undefined ? data.caste.others : '';
                }
                if (data.religion) {
                    if (religionHindu) religionHindu.value = data.religion.hindu !== '' && data.religion.hindu !== undefined ? data.religion.hindu : '';
                    if (religionMuslim) religionMuslim.value = data.religion.muslim !== '' && data.religion.muslim !== undefined ? data.religion.muslim : '';
                    if (religionSikh) religionSikh.value = data.religion.sikh !== '' && data.religion.sikh !== undefined ? data.religion.sikh : '';
                    if (religionChristian) religionChristian.value = data.religion.christian !== '' && data.religion.christian !== undefined ? data.religion.christian : '';
                    if (religionOthers) religionOthers.value = data.religion.others !== '' && data.religion.others !== undefined ? data.religion.others : '';
                }
            }
            
            // Load from localStorage
            function loadFromLocalStorage() {
                const saved = localStorage.getItem(STORAGE_KEY);
                if (saved) {
                    try {
                        const record = JSON.parse(saved);
                        populateForm(record);
                        showMessage('Loaded previously saved survey data.', false);
                    } catch(e) {
                        console.warn(e);
                    }
                } else {
                    showMessage('Ready to capture new Area Survey.', false);
                }
            }
            
            // Save to localStorage
            function saveToLocalStorage() {
                const formData = getCurrentFormData();
                if (!formData.zoneCode && !formData.villageName && !formData.zoneName) {
                    showMessage('Please fill at least Zone Code or Village Name before saving.', true);
                    return false;
                }
                localStorage.setItem(STORAGE_KEY, JSON.stringify(formData));
                showMessage('Survey data saved successfully!', false);
                return true;
            }
            
            // Update record
            function updateRecord() {
                const formData = getCurrentFormData();
                if (!formData.zoneCode && !formData.villageName) {
                    showMessage('Cannot update empty record. Provide at least Zone Code / Village.', true);
                    return;
                }
                localStorage.setItem(STORAGE_KEY, JSON.stringify(formData));
                showMessage('Survey record updated successfully!', false);
            }
            
            // Delete record
            function deleteRecord() {
                if (confirm('Are you sure you want to DELETE the entire Area Survey record? This action cannot be undone.')) {
                    localStorage.removeItem(STORAGE_KEY);
                    if (zoneCodeInput) zoneCodeInput.value = '';
                    if (surveyDateInput) surveyDateInput.value = '2024-01-29';
                    if (zoneNameInput) zoneNameInput.value = '';
                    if (villageNameInput) villageNameInput.value = '';
                    if (branchInput) branchInput.value = '';
                    if (areaTypeInput) areaTypeInput.value = 'FULAL';
                    if (foNameInput) foNameInput.value = '';
                    if (foCodeInput) foCodeInput.value = '';
                    if (populationInput) populationInput.value = '';
                    if (politicalSituationSelect) politicalSituationSelect.value = '';
                    if (lawOrderSelect) lawOrderSelect.value = '';
                    if (distanceInput) distanceInput.value = '';
                    if (centresPossibleInput) centresPossibleInput.value = '';
                    if (mfiWorkingInput) mfiWorkingInput.value = '';
                    if (majorOperationInput) majorOperationInput.value = '';
                    if (roadStatusSelect) roadStatusSelect.value = '';
                    if (casteGeneral) casteGeneral.value = '';
                    if (casteST) casteST.value = '';
                    if (casteOBC) casteOBC.value = '';
                    if (casteOthers) casteOthers.value = '';
                    if (religionHindu) religionHindu.value = '';
                    if (religionMuslim) religionMuslim.value = '';
                    if (religionSikh) religionSikh.value = '';
                    if (religionChristian) religionChristian.value = '';
                    if (religionOthers) religionOthers.value = '';
                    showMessage('Survey record deleted. Form cleared.', false);
                }
            }
            
            // Reset form for new entry
            function resetFormForNew() {
                if (confirm('Create new form? Unsaved changes will be lost if not saved. Current data will be cleared.')) {
                    if (zoneCodeInput) zoneCodeInput.value = '';
                    if (surveyDateInput) surveyDateInput.value = new Date().toISOString().slice(0,10);
                    if (zoneNameInput) zoneNameInput.value = '';
                    if (villageNameInput) villageNameInput.value = '';
                    if (branchInput) branchInput.value = '';
                    if (areaTypeInput) areaTypeInput.value = 'FULAL';
                    if (foNameInput) foNameInput.value = '';
                    if (foCodeInput) foCodeInput.value = '';
                    if (populationInput) populationInput.value = '';
                    if (politicalSituationSelect) politicalSituationSelect.value = '';
                    if (lawOrderSelect) lawOrderSelect.value = '';
                    if (distanceInput) distanceInput.value = '';
                    if (centresPossibleInput) centresPossibleInput.value = '';
                    if (mfiWorkingInput) mfiWorkingInput.value = '';
                    if (majorOperationInput) majorOperationInput.value = '';
                    if (roadStatusSelect) roadStatusSelect.value = '';
                    if (casteGeneral) casteGeneral.value = '';
                    if (casteST) casteST.value = '';
                    if (casteOBC) casteOBC.value = '';
                    if (casteOthers) casteOthers.value = '';
                    if (religionHindu) religionHindu.value = '';
                    if (religionMuslim) religionMuslim.value = '';
                    if (religionSikh) religionSikh.value = '';
                    if (religionChristian) religionChristian.value = '';
                    if (religionOthers) religionOthers.value = '';
                    showMessage('Form cleared. You can start a fresh survey.', false);
                }
            }
            
            // Validate percentages and show warning
            function validatePercentages() {
                const casteTotal = (parseInt(casteGeneral?.value || 0) || 0) + 
                                (parseInt(casteST?.value || 0) || 0) + 
                                (parseInt(casteOBC?.value || 0) || 0) + 
                                (parseInt(casteOthers?.value || 0) || 0);
                const religionTotal = (parseInt(religionHindu?.value || 0) || 0) + 
                                    (parseInt(religionMuslim?.value || 0) || 0) + 
                                    (parseInt(religionSikh?.value || 0) || 0) + 
                                    (parseInt(religionChristian?.value || 0) || 0) + 
                                    (parseInt(religionOthers?.value || 0) || 0);
                
                if (casteTotal > 0 && casteTotal !== 100) {
                    showMessage(`Caste total: ${casteTotal}% (recommended 100%)`, true);
                    setTimeout(() => {
                        if(messageDiv && messageDiv.innerHTML.includes('Caste total')) {
                            messageDiv.innerHTML = '';
                        }
                    }, 2500);
                } else if (religionTotal > 0 && religionTotal !== 100) {
                    showMessage(`Religion total: ${religionTotal}% (recommended 100%)`, true);
                    setTimeout(() => {
                        if(messageDiv && messageDiv.innerHTML.includes('Religion total')) {
                            messageDiv.innerHTML = '';
                        }
                    }, 2500);
                }
            }
            
            // Attach event listeners to buttons
            if (saveBtn) saveBtn.addEventListener('click', saveToLocalStorage);
            if (updateBtn) updateBtn.addEventListener('click', updateRecord);
            if (deleteBtn) deleteBtn.addEventListener('click', deleteRecord);
            if (newBtn) newBtn.addEventListener('click', resetFormForNew);
            
            // Attach percentage validation on blur
            const percInputs = [casteGeneral, casteST, casteOBC, casteOthers, religionHindu, religionMuslim, religionSikh, religionChristian, religionOthers];
            percInputs.forEach(inp => {
                if(inp) inp.addEventListener('blur', validatePercentages);
            });
            
            // Load saved data on initialization
            loadFromLocalStorage();
            
            // Set default date if empty
            if (surveyDateInput && !surveyDateInput.value) {
                surveyDateInput.value = new Date().toISOString().slice(0,10);
            }
        }

        // ========== CENTER MASTER MANAGEMENT ==========
        // Function to show Center Master
        function showCenterMaster() {
            const allSections = document.querySelectorAll('.content-section, .branch-master-container, .area-survey-container');
            allSections.forEach(section => {
                if (section) section.style.display = 'none';
            });
            
            const centerContainer = document.querySelector('.center-master-container');
            if (centerContainer) {
                centerContainer.style.display = 'block';
            }
        }

        // Center Master Data Array
        let centerMasterData = [
            { bcode: 'C001', centerName: 'CENTER1', phoneNo: '5455545', centerHead: '5454544445', capacity: '5' }
        ];

        let selectedRowIndex = null;

        // Function to render table
        function renderCenterTable() {
            const tbody = document.getElementById('cmTableBody');
            if (!tbody) return;
            
            tbody.innerHTML = '';
            centerMasterData.forEach((item, index) => {
                const row = tbody.insertRow();
                row.setAttribute('data-index', index);
                row.innerHTML = `
                    <td>${escapeHtml(item.bcode)}</td>
                    <td>${escapeHtml(item.centerName)}</td>
                    <td>${escapeHtml(item.phoneNo)}</td>
                    <td>${escapeHtml(item.centerHead)}</td>
                    <td>${escapeHtml(item.capacity)}</td>
                `;
                row.addEventListener('click', () => selectRow(index));
            });
        }

        // Helper to escape HTML
        function escapeHtml(str) {
            if (!str) return '';
            return str.replace(/[&<>]/g, function(m) {
                if (m === '&') return '&amp;';
                if (m === '<') return '&lt;';
                if (m === '>') return '&gt;';
                return m;
            });
        }

        // Select row and populate form
        function selectRow(index) {
            selectedRowIndex = index;
            const item = centerMasterData[index];
            
            // Remove selected class from all rows
            document.querySelectorAll('#cmTableBody tr').forEach(row => {
                row.classList.remove('selected-row');
            });
            // Add selected class to clicked row
            const rows = document.querySelectorAll('#cmTableBody tr');
            if (rows[index]) rows[index].classList.add('selected-row');
            
            // Populate form
            document.getElementById('cmCenterCode').value = item.bcode || '';
            document.getElementById('cmCenterName').value = item.centerName || '';
            document.getElementById('cmPhoneNo').value = item.phoneNo || '';
            document.getElementById('cmCenterHeadName').value = item.centerHead || '';
            document.getElementById('cmGroupCapacity').value = item.capacity || '';
        }

        // Clear form
        function clearCenterForm() {
            document.getElementById('cmCenterCode').value = '';
            document.getElementById('cmCenterName').value = '';
            document.getElementById('cmUnderBranch').value = '';
            document.getElementById('cmZone').value = '';
            document.getElementById('cmAddress').value = '';
            document.getElementById('cmPincode').value = '';
            document.getElementById('cmPhoneNo').value = '';
            document.getElementById('cmFOCode').value = '';
            document.getElementById('cmCenterHeadName').value = '';
            document.getElementById('cmGroupCapacity').value = '';
            
            // Remove selection
            selectedRowIndex = null;
            document.querySelectorAll('#cmTableBody tr').forEach(row => {
                row.classList.remove('selected-row');
            });
        }

        // Show message
        function showCenterMessage(text, isError = false) {
            const msgDiv = document.getElementById('cmMessageArea');
            if (!msgDiv) return;
            msgDiv.innerHTML = text;
            msgDiv.style.borderLeftColor = isError ? '#ef4444' : '#2a7f6e';
            msgDiv.style.backgroundColor = isError ? '#fef2f2' : '#f0fdf9';
            setTimeout(() => {
                if (msgDiv.innerHTML === text) {
                    msgDiv.innerHTML = '';
                    msgDiv.style.borderLeftColor = '#2a7f6e';
                    msgDiv.style.backgroundColor = '#f8fafc';
                }
            }, 3000);
        }

        // Save new center
        function saveCenter() {
            const centerCode = document.getElementById('cmCenterCode').value.trim();
            const centerName = document.getElementById('cmCenterName').value.trim();
            const phoneNo = document.getElementById('cmPhoneNo').value.trim();
            const centerHead = document.getElementById('cmCenterHeadName').value.trim();
            const capacity = document.getElementById('cmGroupCapacity').value.trim();
            
            if (!centerCode) {
                showCenterMessage('Please enter Center Code', true);
                return;
            }
            if (!centerName) {
                showCenterMessage('Please enter Center Name', true);
                return;
            }
            
            // Check for duplicate center code
            if (centerMasterData.some(item => item.bcode === centerCode)) {
                showCenterMessage('Center Code already exists!', true);
                return;
            }
            
            centerMasterData.push({
                bcode: centerCode,
                centerName: centerName,
                phoneNo: phoneNo || '',
                centerHead: centerHead || '',
                capacity: capacity || ''
            });
            
            renderCenterTable();
            clearCenterForm();
            showCenterMessage('Center saved successfully!');
        }

        // Update selected center
        function updateCenter() {
            if (selectedRowIndex === null) {
                showCenterMessage('Please select a center to update', true);
                return;
            }
            
            const centerCode = document.getElementById('cmCenterCode').value.trim();
            const centerName = document.getElementById('cmCenterName').value.trim();
            const phoneNo = document.getElementById('cmPhoneNo').value.trim();
            const centerHead = document.getElementById('cmCenterHeadName').value.trim();
            const capacity = document.getElementById('cmGroupCapacity').value.trim();
            
            if (!centerCode) {
                showCenterMessage('Please enter Center Code', true);
                return;
            }
            if (!centerName) {
                showCenterMessage('Please enter Center Name', true);
                return;
            }
            
            // Check if trying to change to existing code (excluding current)
            const duplicateIndex = centerMasterData.findIndex((item, idx) => item.bcode === centerCode && idx !== selectedRowIndex);
            if (duplicateIndex !== -1) {
                showCenterMessage('Center Code already exists on another record!', true);
                return;
            }
            
            centerMasterData[selectedRowIndex] = {
                bcode: centerCode,
                centerName: centerName,
                phoneNo: phoneNo || '',
                centerHead: centerHead || '',
                capacity: capacity || ''
            };
            
            renderCenterTable();
            clearCenterForm();
            showCenterMessage('Center updated successfully!');
        }

        // Delete selected center
        function deleteCenter() {
            if (selectedRowIndex === null) {
                showCenterMessage('Please select a center to delete', true);
                return;
            }
            
            if (confirm('Are you sure you want to delete this center?')) {
                centerMasterData.splice(selectedRowIndex, 1);
                renderCenterTable();
                clearCenterForm();
                showCenterMessage('Center deleted successfully!');
            }
        }

        // Refresh form
        function refreshCenter() {
            clearCenterForm();
            showCenterMessage('Form has been refreshed');
        }

        // Close/hide Center Master
        function closeCenterMaster() {
            const centerContainer = document.querySelector('.center-master-container');
            if (centerContainer) {
                centerContainer.style.display = 'none';
            }
            clearCenterForm();
        }

        // Initialize Center Master
        function initializeCenterMaster() {
            renderCenterTable();
            
            const saveBtn = document.getElementById('cmSaveBtn');
            const updateBtn = document.getElementById('cmUpdateBtn');
            const deleteBtn = document.getElementById('cmDeleteBtn');
            const refreshBtn = document.getElementById('cmRefreshBtn');
            const closeBtn = document.getElementById('cmCloseBtn');
            
            if (saveBtn) saveBtn.addEventListener('click', saveCenter);
            if (updateBtn) updateBtn.addEventListener('click', updateCenter);
            if (deleteBtn) deleteBtn.addEventListener('click', deleteCenter);
            if (refreshBtn) refreshBtn.addEventListener('click', refreshCenter);
            if (closeBtn) closeBtn.addEventListener('click', closeCenterMaster);
            
            // Set default date
            const openingDate = document.getElementById('cmOpeningDate');
            if (openingDate && !openingDate.value) {
                openingDate.value = '2026-04-02';
            }
        }

        // Initialize when DOM is ready
        document.addEventListener('DOMContentLoaded', function() {
            initializeCenterMaster();
        });

        // ========== LEAD GENERATION MANAGEMENT (UPDATED) ==========
        // Store lead data
        let leadDataArray = [];
        let currentEditIndex = null;
        let leadInitialized = false;

        // Function to show Lead Generation
        function showLeadGeneration() {
            const allSections = document.querySelectorAll('.content-section, .branch-master-container, .area-survey-container, .center-master-container');
            allSections.forEach(section => {
                if (section) section.style.display = 'none';
            });
            
            const leadContainer = document.querySelector('.lead-generation-container');
            if (leadContainer) {
                leadContainer.style.display = 'block';
            }

            if (!leadInitialized) {
                initializeLeadGeneration();
                leadInitialized = true;
            }
        }

        // Show message function
        function showLeadMessage(text, isError = false) {
            const msgDiv = document.getElementById('lgMessageArea');
            if (!msgDiv) return;
            msgDiv.innerHTML = text;
            msgDiv.style.borderLeftColor = isError ? '#ef4444' : '#2a7f6e';
            msgDiv.style.backgroundColor = isError ? '#fef2f2' : '#f0fdf9';
            setTimeout(() => {
                if (msgDiv.innerHTML === text) {
                    msgDiv.innerHTML = '';
                    msgDiv.style.borderLeftColor = '#2a7f6e';
                    msgDiv.style.backgroundColor = '#f8fafc';
                }
            }, 3000);
        }

        // Calculate age from date of birth
        function calculateAge() {
            const dobInput = document.getElementById('lgDob');
            const ageDisplay = document.getElementById('lgAgeDisplay');
            const ageField = document.getElementById('lgAge');
            
            if (!dobInput || !dobInput.value) {
                if (ageDisplay) ageDisplay.textContent = 'Age: -- years';
                if (ageField) ageField.value = '';
                return;
            }
            
            const birthDate = new Date(dobInput.value);
            const today = new Date();
            
            let age = today.getFullYear() - birthDate.getFullYear();
            const monthDiff = today.getMonth() - birthDate.getMonth();
            
            if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
                age--;
            }
            
            if (ageDisplay) ageDisplay.textContent = `Age: ${age} years`;
            if (ageField) ageField.value = age;
        }

        // Toggle Permanent Address field based on checkbox
        function togglePermanentAddress() {
            const sameAsResidential = document.getElementById('lgSameAsResidential');
            const permanentGroup = document.getElementById('lgPermanentAddressGroup');
            const permanentAddress = document.getElementById('lgPermanentAddress');
            const residentialAddress = document.getElementById('lgResidentialAddress');
            
            if (sameAsResidential && sameAsResidential.checked) {
                if (permanentGroup) permanentGroup.style.display = 'none';
                if (permanentAddress && residentialAddress) {
                    permanentAddress.value = residentialAddress.value;
                }
            } else {
                if (permanentGroup) permanentGroup.style.display = 'block';
            }
        }

        // Copy residential to permanent when checkbox is checked
        function copyResidentialToPermanent() {
            const sameAsResidential = document.getElementById('lgSameAsResidential');
            const residentialAddress = document.getElementById('lgResidentialAddress');
            const permanentAddress = document.getElementById('lgPermanentAddress');
            
            if (sameAsResidential && sameAsResidential.checked && residentialAddress && permanentAddress) {
                permanentAddress.value = residentialAddress.value;
            }
        }

        // Get form data as object
        function getLeadFormData() {
            return {
                branchName: document.getElementById('lgBranchName')?.value || '',
                center: document.getElementById('lgCenter')?.value || '',
                loanType: document.getElementById('lgLoanType')?.value || '',
                proposedAmount: document.getElementById('lgProposedAmount')?.value || '',
                fieldOfficer: document.getElementById('lgFieldOfficer')?.value || '',
                aadharNo: document.getElementById('lgAadharNo')?.value || '',
                voterId: document.getElementById('lgVoterId')?.value || '',
                name: document.getElementById('lgName')?.value || '',
                guardianName: document.getElementById('lgGuardianName')?.value || '',
                gender: document.getElementById('lgGender')?.value || '',
                dob: document.getElementById('lgDob')?.value || '',
                nomineeName: document.getElementById('lgNomineeName')?.value || '',
                nomineeRelation: document.getElementById('lgNomineeRelation')?.value || '',
                age: document.getElementById('lgAge')?.value || '',
                phoneNo: document.getElementById('lgPhoneNo')?.value || '',
                applicationDate: document.getElementById('lgApplicationDate')?.value || '',
                requestFormNo: document.getElementById('lgRequestFormNo')?.value || '',
                residentialAddress: document.getElementById('lgResidentialAddress')?.value || '',
                pincode: document.getElementById('lgPincode')?.value || '',
                permanentAddress: document.getElementById('lgPermanentAddress')?.value || '',
                monthlySavings: document.getElementById('lgMonthlySavings')?.value || '',
                activeLoans: document.getElementById('lgActiveLoans')?.value || '',
                borrowFrequently: document.getElementById('lgBorrowFrequently')?.value || '',
                livingType: document.getElementById('lgLivingType')?.value || '',
                familyMembers: document.getElementById('lgFamilyMembers')?.value || '',
                monthlyIncome: document.getElementById('lgMonthlyIncome')?.value || '',
                religion: document.getElementById('lgReligion')?.value || '',
                maritalStatus: document.getElementById('lgMaritalStatus')?.value || '',
                houseStability: document.getElementById('lgHouseStability')?.value || '',
                bankName: document.getElementById('lgBankName')?.value || '',
                bankBranch: document.getElementById('lgBankBranch')?.value || '',
                accountNo: document.getElementById('lgAccountNo')?.value || '',
                ifscCode: document.getElementById('lgIfscCode')?.value || '',
                loanPurpose: document.getElementById('lgLoanPurpose')?.value || '',
                addressProof: document.getElementById('lgAddressProof')?.value || '',
                addressProofNumber: document.getElementById('lgAddressProofNumber')?.value || '',
                idProof: document.getElementById('lgIdProof')?.value || '',
                idProofNumber: document.getElementById('lgIdProofNumber')?.value || '',
                nomineeIdProof: document.getElementById('lgNomineeIdProof')?.value || '',
                nomineeIdProofNumber: document.getElementById('lgNomineeIdProofNumber')?.value || '',
                nomineeAadhar: document.getElementById('lgNomineeAadhar')?.value || ''
            };
        }

        // Populate form with data
        function populateLeadForm(data) {
            if (!data) return;
            document.getElementById('lgBranchName').value = data.branchName || 'HEAD OFFICE - 001';
            document.getElementById('lgCenter').value = data.center || 'CENTER1';
            document.getElementById('lgLoanType').value = data.loanType || 'GROUP LOAN';
            document.getElementById('lgProposedAmount').value = data.proposedAmount || '';
            document.getElementById('lgFieldOfficer').value = data.fieldOfficer || 'ARITRA DAS - C000';
            document.getElementById('lgAadharNo').value = data.aadharNo || '';
            document.getElementById('lgVoterId').value = data.voterId || '';
            document.getElementById('lgName').value = data.name || '';
            document.getElementById('lgGuardianName').value = data.guardianName || 'CO';
            document.getElementById('lgGender').value = data.gender || 'FEMALE';
            document.getElementById('lgDob').value = data.dob || '2026-04-02';
            document.getElementById('lgNomineeName').value = data.nomineeName || '';
            document.getElementById('lgNomineeRelation').value = data.nomineeRelation || '';
            document.getElementById('lgAge').value = data.age || '';
            document.getElementById('lgPhoneNo').value = data.phoneNo || '';
            document.getElementById('lgApplicationDate').value = data.applicationDate || '2026-04-02';
            document.getElementById('lgRequestFormNo').value = data.requestFormNo || '';
            document.getElementById('lgResidentialAddress').value = data.residentialAddress || '';
            document.getElementById('lgPincode').value = data.pincode || '';
            document.getElementById('lgPermanentAddress').value = data.permanentAddress || '';
            document.getElementById('lgMonthlySavings').value = data.monthlySavings || '';
            document.getElementById('lgActiveLoans').value = data.activeLoans || '';
            document.getElementById('lgBorrowFrequently').value = data.borrowFrequently || '';
            document.getElementById('lgLivingType').value = data.livingType || '';
            document.getElementById('lgFamilyMembers').value = data.familyMembers || '';
            document.getElementById('lgMonthlyIncome').value = data.monthlyIncome || '';
            document.getElementById('lgReligion').value = data.religion || '';
            document.getElementById('lgMaritalStatus').value = data.maritalStatus || '';
            document.getElementById('lgHouseStability').value = data.houseStability || '';
            document.getElementById('lgBankName').value = data.bankName || '';
            document.getElementById('lgBankBranch').value = data.bankBranch || '';
            document.getElementById('lgAccountNo').value = data.accountNo || '';
            document.getElementById('lgIfscCode').value = data.ifscCode || '';
            document.getElementById('lgLoanPurpose').value = data.loanPurpose || '';
            document.getElementById('lgAddressProof').value = data.addressProof || 'NoID';
            document.getElementById('lgAddressProofNumber').value = data.addressProofNumber || '';
            document.getElementById('lgIdProof').value = data.idProof || 'NoID';
            document.getElementById('lgIdProofNumber').value = data.idProofNumber || '';
            document.getElementById('lgNomineeIdProof').value = data.nomineeIdProof || 'No/ID';
            document.getElementById('lgNomineeIdProofNumber').value = data.nomineeIdProofNumber || '';
            document.getElementById('lgNomineeAadhar').value = data.nomineeAadhar || '';
            
            // Update age display
            calculateAge();
        }

        // Clear form
        function clearLeadForm() {
            document.getElementById('lgProposedAmount').value = '';
            document.getElementById('lgAadharNo').value = '';
            document.getElementById('lgVoterId').value = '';
            document.getElementById('lgName').value = '';
            document.getElementById('lgGuardianName').value = 'CO';
            document.getElementById('lgGender').value = 'FEMALE';
            document.getElementById('lgDob').value = '2026-04-02';
            document.getElementById('lgNomineeName').value = '';
            document.getElementById('lgNomineeRelation').value = '';
            document.getElementById('lgAge').value = '';
            document.getElementById('lgPhoneNo').value = '';
            document.getElementById('lgApplicationDate').value = '2026-04-02';
            document.getElementById('lgRequestFormNo').value = '';
            document.getElementById('lgResidentialAddress').value = '';
            document.getElementById('lgPincode').value = '';
            document.getElementById('lgPermanentAddress').value = '';
            document.getElementById('lgMonthlySavings').value = '';
            document.getElementById('lgActiveLoans').value = '';
            document.getElementById('lgBorrowFrequently').value = '';
            document.getElementById('lgLivingType').value = '';
            document.getElementById('lgFamilyMembers').value = '';
            document.getElementById('lgMonthlyIncome').value = '';
            document.getElementById('lgReligion').value = '';
            document.getElementById('lgMaritalStatus').value = '';
            document.getElementById('lgHouseStability').value = '';
            document.getElementById('lgBankName').value = '';
            document.getElementById('lgBankBranch').value = '';
            document.getElementById('lgAccountNo').value = '';
            document.getElementById('lgIfscCode').value = '';
            document.getElementById('lgLoanPurpose').value = '';
            document.getElementById('lgAddressProof').value = 'NoID';
            document.getElementById('lgAddressProofNumber').value = '';
            document.getElementById('lgIdProof').value = 'NoID';
            document.getElementById('lgIdProofNumber').value = '';
            document.getElementById('lgNomineeIdProof').value = 'No/ID';
            document.getElementById('lgNomineeIdProofNumber').value = '';
            document.getElementById('lgNomineeAadhar').value = '';
            
            // Clear file inputs
            const fileInputs = ['lgAddressProofDoc', 'lgIdProofDoc', 'lgPassbookFront', 'lgPassportPhoto', 'lgJointPhoto', 'lgNomineeIdDoc', 'lgNomineeAadharDoc'];
            fileInputs.forEach(id => {
                const input = document.getElementById(id);
                if (input) input.value = '';
            });
            
            const sameAsResidential = document.getElementById('lgSameAsResidential');
            if (sameAsResidential) {
                sameAsResidential.checked = false;
                document.getElementById('lgPermanentAddressGroup').style.display = 'block';
            }
            
            // Reset age display
            const ageDisplay = document.getElementById('lgAgeDisplay');
            if (ageDisplay) ageDisplay.textContent = 'Age: 0 years';
            
            currentEditIndex = null;
        }

        // Save lead data to localStorage
        function saveLeadData() {
            const formData = getLeadFormData();
            
            if (!formData.name) {
                showLeadMessage('Please enter the applicant name', true);
                return;
            }
            if (!formData.phoneNo) {
                showLeadMessage('Please enter phone number', true);
                return;
            }
            
            let leads = JSON.parse(localStorage.getItem('leadGenerationData') || '[]');
            leads.push(formData);
            localStorage.setItem('leadGenerationData', JSON.stringify(leads));
            
            showLeadMessage('Lead saved successfully!');
            clearLeadForm();
        }

        // Update lead data
        function updateLeadData() {
            if (currentEditIndex === null) {
                showLeadMessage('No record selected for update', true);
                return;
            }
            
            const formData = getLeadFormData();
            let leads = JSON.parse(localStorage.getItem('leadGenerationData') || '[]');
            
            if (currentEditIndex < leads.length) {
                leads[currentEditIndex] = formData;
                localStorage.setItem('leadGenerationData', JSON.stringify(leads));
                showLeadMessage('Lead updated successfully!');
                clearLeadForm();
                currentEditIndex = null;
            } else {
                showLeadMessage('Record not found', true);
            }
        }

        // Delete lead data
        function deleteLeadData() {
            if (currentEditIndex === null) {
                showLeadMessage('No record selected for deletion', true);
                return;
            }
            
            if (confirm('Are you sure you want to delete this lead?')) {
                let leads = JSON.parse(localStorage.getItem('leadGenerationData') || '[]');
                leads.splice(currentEditIndex, 1);
                localStorage.setItem('leadGenerationData', JSON.stringify(leads));
                showLeadMessage('Lead deleted successfully!');
                clearLeadForm();
                currentEditIndex = null;
            }
        }

        // Refresh form
        function refreshLeadForm() {
            clearLeadForm();
            showLeadMessage('Form has been refreshed');
        }

        // Close Lead Generation
        function closeLeadGeneration() {
            const leadContainer = document.querySelector('.lead-generation-container');
            if (leadContainer) {
                leadContainer.style.display = 'none';
            }
            clearLeadForm();
        }

        // Initialize Lead Generation
        function initializeLeadGeneration() {
            // Set default date values
            const today = new Date().toISOString().slice(0, 10);
            const dobInput = document.getElementById('lgDob');
            const appDateInput = document.getElementById('lgApplicationDate');
            if (dobInput && !dobInput.value) dobInput.value = '2026-04-02';
            if (appDateInput && !appDateInput.value) appDateInput.value = '2026-04-02';
            
            // Add DOB change event to calculate age
            if (dobInput) {
                dobInput.addEventListener('change', calculateAge);
                calculateAge(); // Initial calculation
            }
            
            // Add event listeners
            const sameAsResidential = document.getElementById('lgSameAsResidential');
            if (sameAsResidential) {
                sameAsResidential.addEventListener('change', togglePermanentAddress);
            }
            
            const residentialAddress = document.getElementById('lgResidentialAddress');
            if (residentialAddress) {
                residentialAddress.addEventListener('input', copyResidentialToPermanent);
            }
            
            const refreshBtn = document.getElementById('lgRefreshBtn');
            const saveBtn = document.getElementById('lgSaveBtn');
            const updateBtn = document.getElementById('lgUpdateBtn');
            const deleteBtn = document.getElementById('lgDeleteBtn');
            const closeBtn = document.getElementById('lgCloseBtn');
            
            if (refreshBtn) refreshBtn.addEventListener('click', refreshLeadForm);
            if (saveBtn) saveBtn.addEventListener('click', saveLeadData);
            if (updateBtn) updateBtn.addEventListener('click', updateLeadData);
            if (deleteBtn) deleteBtn.addEventListener('click', deleteLeadData);
            if (closeBtn) closeBtn.addEventListener('click', closeLeadGeneration);
            
            // File browse buttons
            const browseConfigs = [
                { fileId: 'lgAddressProofDoc' },
                { fileId: 'lgIdProofDoc' },
                { fileId: 'lgPassbookFront' },
                { fileId: 'lgPassportPhoto' },
                { fileId: 'lgJointPhoto' },
                { fileId: 'lgNomineeIdDoc' },
                { fileId: 'lgNomineeAadharDoc' }
            ];
            
            browseConfigs.forEach(config => {
                const fileInput = document.getElementById(config.fileId);
                if (fileInput) {
                    fileInput.addEventListener('change', function(e) {
                        if (e.target.files.length > 0) {
                            showLeadMessage(`Selected: ${e.target.files[0].name}`);
                        }
                    });
                }
            });
            
            // Initialize permanent address visibility
            togglePermanentAddress();
        }

        // ========== CGT MANAGEMENT ==========

        // Sample leads data
        let availableLeads = [
            { leadCode: 'LD001', leadName: 'Rajesh Kumar', phoneNo: '9876543210', aadharNo: '123456789012', loanType: 'GROUP LOAN', appliedOn: '2024-01-15' },
            { leadCode: 'LD002', leadName: 'Priya Sharma', phoneNo: '9876543211', aadharNo: '123456789013', loanType: 'INDIVIDUAL LOAN', appliedOn: '2024-01-20' },
            { leadCode: 'LD003', leadName: 'Amit Singh', phoneNo: '9876543212', aadharNo: '123456789014', loanType: 'EMERGENCY LOAN', appliedOn: '2024-02-01' },
            { leadCode: 'LD004', leadName: 'Neha Gupta', phoneNo: '9876543213', aadharNo: '123456789015', loanType: 'GROUP LOAN', appliedOn: '2024-02-10' },
            { leadCode: 'LD005', leadName: 'Vikram Patil', phoneNo: '9876543214', aadharNo: '123456789016', loanType: 'EDUCATION LOAN', appliedOn: '2024-02-15' }
        ];

        let selectedLeads = [];
        let cgtDataList = [
            { 
                cgtCode: 'GT000057', 
                startDate: '01/02/2024', 
                center: 'CENTER1', 
                foCode: 'hok000001', 
                duration: '5', 
                status: 'Closed', 
                leads: [], 
                branch: 'HEAD OFFICE - 001',
                description: 'Sample CGT description'
            }
        ];

        let currentEditCgtCode = null;

        // Function to show CGT Management
        function showCGTManagement() {
            const allSections = document.querySelectorAll('.content-section, .branch-master-container, .area-survey-container, .center-master-container, .lead-generation-container');
            allSections.forEach(section => {
                if (section) section.style.display = 'none';
            });
            
            const cgtContainer = document.querySelector('.cgt-main-container');
            if (cgtContainer) {
                cgtContainer.style.display = 'block';
            }
            
            showCGTListView();
            loadCGTHistory();
        }

        // Show List View
        function showCGTListView() {
            document.getElementById('cgtListView').style.display = 'block';
            document.getElementById('cgtFormView').style.display = 'none';
            loadCGTHistory();
        }

        // Show Form View
        function showCGTFormView() {
            document.getElementById('cgtListView').style.display = 'none';
            document.getElementById('cgtFormView').style.display = 'block';
        }

        // Show message
        function showCGTMessage(text, isError = false) {
            const msgDiv = document.getElementById('cgtMessageArea');
            if (!msgDiv) return;
            msgDiv.innerHTML = text;
            msgDiv.style.borderLeftColor = isError ? '#ef4444' : '#2a7f6e';
            msgDiv.style.backgroundColor = isError ? '#fef2f2' : '#f0fdf9';
            setTimeout(() => {
                if (msgDiv.innerHTML === text) {
                    msgDiv.innerHTML = '';
                }
            }, 3000);
        }

        // Format date to DD/MM/YYYY
        function formatDate(dateString) {
            if (!dateString) return '';
            const date = new Date(dateString);
            if (isNaN(date.getTime())) return dateString;
            const day = String(date.getDate()).padStart(2, '0');
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const year = date.getFullYear();
            return `${day}/${month}/${year}`;
        }

        // Format date to YYYY-MM-DD for input
        function formatDateForInput(dateString) {
            if (!dateString) return '';
            if (dateString.includes('/')) {
                const parts = dateString.split('/');
                if (parts.length === 3) {
                    return `${parts[2]}-${parts[1]}-${parts[0]}`;
                }
            }
            return dateString;
        }

        // Load CGT History Table
        function loadCGTHistory() {
            const tbody = document.getElementById('cgtListBody');
            if (!tbody) return;
            
            tbody.innerHTML = '';
            cgtDataList.forEach(cgt => {
                const row = tbody.insertRow();
                row.innerHTML = `
                    <td>${cgt.cgtCode}</td>
                    <td>${cgt.startDate || formatDate(cgt.startDateInput)}</td>
                    <td>${cgt.center}</td>
                    <td>${cgt.foCode}</td>
                    <td>${cgt.duration}</td>
                    <td><span class="${cgt.status === 'Active' ? 'cgt-status-active' : 'cgt-status-closed'}">${cgt.status}</span></td>
                    <td><button class="cgt-action-btn cgt-edit-btn" onclick="editCGT('${cgt.cgtCode}')">Edit</button></td>
                    <td><button class="cgt-action-btn cgt-close-btn" onclick="closeCGT('${cgt.cgtCode}')">CGT Close</button></td>
                `;
            });
        }

        // Load leads for selected center
        function loadLeadsForCenter() {
            const center = document.getElementById('cgtCenter').value;
            const tbody = document.getElementById('cgtLeadsBody');
            if (!tbody) return;
            
            const available = availableLeads.filter(lead => 
                !selectedLeads.some(selected => selected.leadCode === lead.leadCode)
            );
            
            tbody.innerHTML = '';
            if (available.length === 0) {
                tbody.innerHTML = '<tr><td colspan="8" style="text-align:center">No leads available</td></tr>';
                return;
            }
            
            available.forEach(lead => {
                const row = tbody.insertRow();
                row.innerHTML = `
                    <td><input type="checkbox" class="cgt-checkbox" data-leadcode="${lead.leadCode}" id="chk_${lead.leadCode}"></td>
                    <td>${lead.leadCode}</td>
                    <td>${lead.leadName}</td>
                    <td>${lead.phoneNo}</td>
                    <td>${lead.aadharNo}</td>
                    <td>${lead.loanType}</td>
                    <td>${lead.appliedOn}</td>
                    <td><button class="cgt-add-lead-btn" onclick="addSingleLead('${lead.leadCode}')">Add Lead</button></td>
                `;
            });
        }

        // Add single lead
        function addSingleLead(leadCode) {
            const lead = availableLeads.find(l => l.leadCode === leadCode);
            if (lead && !selectedLeads.some(s => s.leadCode === leadCode)) {
                selectedLeads.push({ ...lead, status: 'Active' });
                loadSelectedLeads();
                loadLeadsForCenter();
                showCGTMessage(`Lead ${lead.leadName} added successfully`);
            }
        }

        // Add selected leads (checkbox)
        function addSelectedLeads() {
            const checkboxes = document.querySelectorAll('#cgtLeadsBody input.cgt-checkbox:checked');
            if (checkboxes.length === 0) {
                showCGTMessage('Please select at least one lead to add', true);
                return;
            }
            
            checkboxes.forEach(cb => {
                const leadCode = cb.getAttribute('data-leadcode');
                const lead = availableLeads.find(l => l.leadCode === leadCode);
                if (lead && !selectedLeads.some(s => s.leadCode === leadCode)) {
                    selectedLeads.push({ ...lead, status: 'Active' });
                }
            });
            
            loadSelectedLeads();
            loadLeadsForCenter();
            showCGTMessage(`${checkboxes.length} lead(s) added successfully`);
        }

        // Load selected leads table
        function loadSelectedLeads() {
            const tbody = document.getElementById('cgtSelectedBody');
            if (!tbody) return;
            
            tbody.innerHTML = '';
            if (selectedLeads.length === 0) {
                tbody.innerHTML = '<tr><td colspan="6" style="text-align:center">No leads selected</td></tr>';
                return;
            }
            
            selectedLeads.forEach((lead, index) => {
                const row = tbody.insertRow();
                row.innerHTML = `
                    <td>${lead.leadCode}</td>
                    <td>${lead.leadName}</td>
                    <td>${lead.phoneNo}</td>
                    <td>${lead.aadharNo}</td>
                    <td><span class="cgt-status-active">${lead.status}</span></td>
                    <td><button class="cgt-remove-lead-btn" onclick="removeLead(${index})">Remove</button></td>
                `;
            });
        }

        // Remove lead from selected list
        function removeLead(index) {
            selectedLeads.splice(index, 1);
            loadSelectedLeads();
            loadLeadsForCenter();
            showCGTMessage('Lead removed successfully');
        }

        // Generate CGT Code
        function generateCGTCode() {
            if (cgtDataList.length === 0) return 'GT000001';
            const lastCGT = cgtDataList[cgtDataList.length - 1];
            const lastNum = parseInt(lastCGT.cgtCode.replace('GT', ''));
            const newNum = lastNum + 1;
            return `GT${String(newNum).padStart(6, '0')}`;
        }

        // Save CGT
        function saveCGT() {
            const branch = document.getElementById('cgtBranch').value;
            const center = document.getElementById('cgtCenter').value;
            const fieldOfficer = document.getElementById('cgtFieldOfficer').value;
            const startDate = document.getElementById('cgtStartDate').value;
            const duration = document.getElementById('cgtDuration').value;
            const description = document.getElementById('cgtDescription').value;
            
            if (!center) {
                showCGTMessage('Please select a center', true);
                return;
            }
            if (!startDate) {
                showCGTMessage('Please select CGT start date', true);
                return;
            }
            if (!duration) {
                showCGTMessage('Please enter number of days for CGT', true);
                return;
            }
            if (selectedLeads.length === 0) {
                showCGTMessage('Please add at least one lead to the CGT', true);
                return;
            }
            
            const newCGT = {
                cgtCode: generateCGTCode(),
                startDate: formatDate(startDate),
                startDateInput: startDate,
                center: center,
                foCode: fieldOfficer || 'Not Assigned',
                duration: duration,
                description: description || '',
                status: 'Active',
                leads: [...selectedLeads],
                branch: branch
            };
            
            cgtDataList.push(newCGT);
            saveCGToLocalStorage();
            loadCGTHistory();
            clearCGTForm();
            showCGTMessage(`CGT ${newCGT.cgtCode} created successfully!`);
            showCGTListView();
        }

        // Edit CGT
        function editCGT(cgtCode) {
            const cgt = cgtDataList.find(c => c.cgtCode === cgtCode);
            if (!cgt) return;
            
            currentEditCgtCode = cgtCode;
            
            document.getElementById('cgtBranch').value = cgt.branch || 'HEAD OFFICE - 001';
            document.getElementById('cgtCenter').value = cgt.center;
            document.getElementById('cgtFieldOfficer').value = cgt.foCode === 'Not Assigned' ? '' : cgt.foCode;
            document.getElementById('cgtStartDate').value = formatDateForInput(cgt.startDate);
            document.getElementById('cgtDuration').value = cgt.duration;
            document.getElementById('cgtDescription').value = cgt.description || '';
            
            selectedLeads = [...cgt.leads];
            loadSelectedLeads();
            loadLeadsForCenter();
            
            // Change save button to update
            const saveBtn = document.getElementById('cgtSaveBtn');
            saveBtn.textContent = 'Update';
            saveBtn.onclick = updateCGT;
            
            showCGTFormView();
            showCGTMessage(`Editing CGT: ${cgtCode}`);
        }

        // Update CGT
        function updateCGT() {
            if (!currentEditCgtCode) {
                showCGTMessage('No CGT selected for update', true);
                return;
            }
            
            const index = cgtDataList.findIndex(c => c.cgtCode === currentEditCgtCode);
            if (index === -1) {
                showCGTMessage('CGT not found', true);
                return;
            }
            
            const branch = document.getElementById('cgtBranch').value;
            const center = document.getElementById('cgtCenter').value;
            const fieldOfficer = document.getElementById('cgtFieldOfficer').value;
            const startDate = document.getElementById('cgtStartDate').value;
            const duration = document.getElementById('cgtDuration').value;
            const description = document.getElementById('cgtDescription').value;
            
            cgtDataList[index] = {
                ...cgtDataList[index],
                branch: branch,
                center: center,
                foCode: fieldOfficer || 'Not Assigned',
                startDate: formatDate(startDate),
                startDateInput: startDate,
                duration: duration,
                description: description || '',
                leads: [...selectedLeads]
            };
            
            saveCGToLocalStorage();
            loadCGTHistory();
            clearCGTForm();
            showCGTMessage(`CGT ${currentEditCgtCode} updated successfully!`);
            
            // Reset save button
            const saveBtn = document.getElementById('cgtSaveBtn');
            saveBtn.textContent = 'Save';
            saveBtn.onclick = saveCGT;
            currentEditCgtCode = null;
            
            showCGTListView();
        }

        // Close CGT
        function closeCGT(cgtCode) {
            if (confirm(`Are you sure you want to close CGT ${cgtCode}?`)) {
                const index = cgtDataList.findIndex(c => c.cgtCode === cgtCode);
                if (index !== -1) {
                    cgtDataList[index].status = 'Closed';
                    saveCGToLocalStorage();
                    loadCGTHistory();
                    showCGTMessage(`CGT ${cgtCode} has been closed`);
                }
            }
        }

        // Search CGT
        function searchCGT() {
            const searchTerm = document.getElementById('cgtSearchInput').value.toLowerCase();
            const showAll = document.getElementById('cgtShowAll').checked;
            
            let filtered = [...cgtDataList];
            
            if (!showAll) {
                filtered = filtered.filter(cgt => cgt.status === 'Active');
            }
            
            if (searchTerm) {
                filtered = filtered.filter(cgt => 
                    cgt.cgtCode.toLowerCase().includes(searchTerm) ||
                    cgt.center.toLowerCase().includes(searchTerm) ||
                    cgt.foCode.toLowerCase().includes(searchTerm)
                );
            }
            
            const tbody = document.getElementById('cgtListBody');
            tbody.innerHTML = '';
            
            filtered.forEach(cgt => {
                const row = tbody.insertRow();
                row.innerHTML = `
                    <td>${cgt.cgtCode}</td>
                    <td>${cgt.startDate || formatDate(cgt.startDateInput)}</td>
                    <td>${cgt.center}</td>
                    <td>${cgt.foCode}</td>
                    <td>${cgt.duration}</td>
                    <td><span class="${cgt.status === 'Active' ? 'cgt-status-active' : 'cgt-status-closed'}">${cgt.status}</span></td>
                    <td><button class="cgt-action-btn cgt-edit-btn" onclick="editCGT('${cgt.cgtCode}')">Edit</button></td>
                    <td><button class="cgt-action-btn cgt-close-btn" onclick="closeCGT('${cgt.cgtCode}')">CGT Close</button></td>
                `;
            });
        }

        // Add New CGT - opens empty form
        function addNewCGT() {
            clearCGTForm();
            showCGTFormView();
        }

        // Clear CGT Form
        function clearCGTForm() {
            document.getElementById('cgtBranch').value = 'HEAD OFFICE - 001';
            document.getElementById('cgtCenter').value = 'CENTER1';
            document.getElementById('cgtFieldOfficer').value = '';
            document.getElementById('cgtStartDate').value = '';
            document.getElementById('cgtDuration').value = '';
            document.getElementById('cgtDescription').value = '';
            selectedLeads = [];
            loadSelectedLeads();
            loadLeadsForCenter();
            
            const saveBtn = document.getElementById('cgtSaveBtn');
            saveBtn.textContent = 'Save';
            saveBtn.onclick = saveCGT;
            currentEditCgtCode = null;
        }

        // Refresh Form
        function refreshCGTForm() {
            clearCGTForm();
            showCGTMessage('Form has been refreshed');
        }

        // Exit Form - goes back to list view
        function exitCGTForm() {
            clearCGTForm();
            showCGTListView();
        }

        // Save to localStorage
        function saveCGToLocalStorage() {
            localStorage.setItem('cgtDataList', JSON.stringify(cgtDataList));
            localStorage.setItem('availableLeads', JSON.stringify(availableLeads));
        }

        // Load from localStorage
        function loadCGFromLocalStorage() {
            const savedCGT = localStorage.getItem('cgtDataList');
            const savedLeads = localStorage.getItem('availableLeads');
            
            if (savedCGT) {
                cgtDataList = JSON.parse(savedCGT);
            }
            if (savedLeads) {
                availableLeads = JSON.parse(savedLeads);
            }
        }

        // Set default start date to today
        function setDefaultStartDate() {
            const startDateInput = document.getElementById('cgtStartDate');
            if (startDateInput && !startDateInput.value) {
                const today = new Date().toISOString().slice(0, 10);
                startDateInput.value = today;
            }
        }

        // Initialize CGT Management
        function initializeCGTManagement() {
            loadCGFromLocalStorage();
            loadCGTHistory();
            loadLeadsForCenter();
            loadSelectedLeads();
            setDefaultStartDate();
            
            // Add "Add Selected" button to leads table header
            const leadsHeader = document.querySelector('#cgtLeadsTable thead tr');
            if (leadsHeader && !document.getElementById('addSelectedBtn')) {
                const addSelectedTh = document.createElement('th');
                addSelectedTh.innerHTML = '<button id="addSelectedBtn" class="cgt-add-lead-btn" style="background:#2a7f6e" onclick="addSelectedLeads()">Add Selected</button>';
                leadsHeader.appendChild(addSelectedTh);
            }
            
            const searchBtn = document.getElementById('cgtSearchBtn');
            const searchInput = document.getElementById('cgtSearchInput');
            const showAllCheckbox = document.getElementById('cgtShowAll');
            const addNewBtn = document.getElementById('cgtAddNewBtn');
            const refreshBtn = document.getElementById('cgtRefreshBtn');
            const exitBtn = document.getElementById('cgtExitBtn');
            const backBtn = document.getElementById('cgtBackBtn');
            
            if (searchBtn) searchBtn.onclick = searchCGT;
            if (searchInput) searchInput.onkeyup = (e) => { if (e.key === 'Enter') searchCGT(); };
            if (showAllCheckbox) showAllCheckbox.onchange = searchCGT;
            if (addNewBtn) addNewBtn.onclick = addNewCGT;
            if (refreshBtn) refreshBtn.onclick = refreshCGTForm;
            if (exitBtn) exitBtn.onclick = exitCGTForm;
            if (backBtn) backBtn.onclick = exitCGTForm;
        }

        // Initialize when DOM is ready
        document.addEventListener('DOMContentLoaded', function() {
            initializeCGTManagement();
        });
    
        // ========== GRT MANAGEMENT ==========
        // Sample leads data
        let grtAvailableLeads = [
            { leadCode: 'LD001', leadName: 'Rajesh Kumar', phoneNo: '9876543210', aadharNo: '123456789012', loanType: 'GROUP LOAN', appliedOn: '2024-01-15' },
            { leadCode: 'LD002', leadName: 'Priya Sharma', phoneNo: '9876543211', aadharNo: '123456789013', loanType: 'INDIVIDUAL LOAN', appliedOn: '2024-01-20' },
            { leadCode: 'LD003', leadName: 'Amit Singh', phoneNo: '9876543212', aadharNo: '123456789014', loanType: 'EMERGENCY LOAN', appliedOn: '2024-02-01' },
            { leadCode: 'LD004', leadName: 'Neha Gupta', phoneNo: '9876543213', aadharNo: '123456789015', loanType: 'GROUP LOAN', appliedOn: '2024-02-10' },
            { leadCode: 'LD005', leadName: 'Vikram Patil', phoneNo: '9876543214', aadharNo: '123456789016', loanType: 'EDUCATION LOAN', appliedOn: '2024-02-15' }
        ];

        let grtSelectedLeads = [];
        let grtDataList = [
            { 
                grtCode: 'GRT000052', 
                startDate: '01/02/2024', 
                center: 'CENTER1', 
                foCode: 'hok000001', 
                duration: '2', 
                status: 'Closed', 
                leads: [], 
                branch: 'HEAD OFFICE - 001',
                description: 'Sample GRT description'
            }
        ];

        let currentEditGrtCode = null;

        // Function to show GRT Management
        function showGRTManagement() {
            const allSections = document.querySelectorAll('.content-section, .branch-master-container, .area-survey-container, .center-master-container, .lead-generation-container, .cgt-main-container');
            allSections.forEach(section => {
                if (section) section.style.display = 'none';
            });
            
            const grtContainer = document.querySelector('.grt-main-container');
            if (grtContainer) {
                grtContainer.style.display = 'block';
            }
            
            showGRTListView();
            loadGRTHistory();
        }

        // Show List View
        function showGRTListView() {
            document.getElementById('grtListView').style.display = 'block';
            document.getElementById('grtFormView').style.display = 'none';
            loadGRTHistory();
        }

        // Show Form View
        function showGRTFormView() {
            document.getElementById('grtListView').style.display = 'none';
            document.getElementById('grtFormView').style.display = 'block';
        }

        // Show message
        function showGRTMessage(text, isError = false) {
            const msgDiv = document.getElementById('grtMessageArea');
            if (!msgDiv) return;
            msgDiv.innerHTML = text;
            msgDiv.style.borderLeftColor = isError ? '#ef4444' : '#2a7f6e';
            msgDiv.style.backgroundColor = isError ? '#fef2f2' : '#f0fdf9';
            setTimeout(() => {
                if (msgDiv.innerHTML === text) {
                    msgDiv.innerHTML = '';
                }
            }, 3000);
        }

        // Format date
        function formatGRTDate(dateString) {
            if (!dateString) return '';
            const date = new Date(dateString);
            if (isNaN(date.getTime())) return dateString;
            const day = String(date.getDate()).padStart(2, '0');
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const year = date.getFullYear();
            return `${day}/${month}/${year}`;
        }

        function formatGRTDateForInput(dateString) {
            if (!dateString) return '';
            if (dateString.includes('/')) {
                const parts = dateString.split('/');
                if (parts.length === 3) {
                    return `${parts[2]}-${parts[1]}-${parts[0]}`;
                }
            }
            return dateString;
        }

        // Load GRT Cards
        function loadGRTHistory() {
            const container = document.getElementById('grtCardsContainer');
            if (!container) return;
            
            container.innerHTML = '';
            
            if (grtDataList.length === 0) {
                container.innerHTML = '<div style="text-align:center; padding:40px;">No GRT records found. Click "Add New GRT" to create one.</div>';
                return;
            }
            
            grtDataList.forEach(grt => {
                const card = document.createElement('div');
                card.className = 'grt-card';
                card.innerHTML = `
                    <div class="grt-card-header">
                        <span class="grt-card-code">${grt.grtCode}</span>
                        <span class="grt-card-status ${grt.status === 'Active' ? 'grt-card-status-active' : 'grt-card-status-closed'}">${grt.status}</span>
                    </div>
                    <div class="grt-card-body">
                        <div class="grt-card-row">
                            <span class="grt-card-label">GRT Start Date:</span>
                            <span class="grt-card-value">${grt.startDate}</span>
                        </div>
                        <div class="grt-card-row">
                            <span class="grt-card-label">Center:</span>
                            <span class="grt-card-value">${grt.center}</span>
                        </div>
                        <div class="grt-card-row">
                            <span class="grt-card-label">FO Code:</span>
                            <span class="grt-card-value">${grt.foCode}</span>
                        </div>
                        <div class="grt-card-row">
                            <span class="grt-card-label">GRT Duration:</span>
                            <span class="grt-card-value">${grt.duration} days</span>
                        </div>
                    </div>
                    <div class="grt-card-actions">
                        <button class="grt-card-edit" onclick="editGRT('${grt.grtCode}')">Edit</button>
                        <button class="grt-card-close" onclick="closeGRT('${grt.grtCode}')">GRT Close</button>
                    </div>
                `;
                container.appendChild(card);
            });
        }

        // Load leads for selected center
        function loadLeadsForGRTCenter() {
            const tbody = document.getElementById('grtLeadsBody');
            if (!tbody) return;
            
            const available = grtAvailableLeads.filter(lead => 
                !grtSelectedLeads.some(selected => selected.leadCode === lead.leadCode)
            );
            
            tbody.innerHTML = '';
            if (available.length === 0) {
                tbody.innerHTML = '<tr><td colspan="8" style="text-align:center">No leads available</td></tr>';
                return;
            }
            
            available.forEach(lead => {
                const row = tbody.insertRow();
                row.innerHTML = `
                    <td><input type="checkbox" class="grt-checkbox" data-leadcode="${lead.leadCode}" id="grtChk_${lead.leadCode}"></td>
                    <td>${lead.leadCode}</td>
                    <td>${lead.leadName}</td>
                    <td>${lead.phoneNo}</td>
                    <td>${lead.aadharNo}</td>
                    <td>${lead.loanType}</td>
                    <td>${lead.appliedOn}</td>
                    <td><button class="grt-add-lead-btn" onclick="addSingleGRTLead('${lead.leadCode}')">Add Lead</button></td>
                `;
            });
        }

        // Add single lead
        function addSingleGRTLead(leadCode) {
            const lead = grtAvailableLeads.find(l => l.leadCode === leadCode);
            if (lead && !grtSelectedLeads.some(s => s.leadCode === leadCode)) {
                grtSelectedLeads.push({ ...lead, status: 'Active' });
                loadSelectedGRTLeads();
                loadLeadsForGRTCenter();
                showGRTMessage(`Lead ${lead.leadName} added successfully`);
            }
        }

        // Add selected leads
        function addSelectedGRTLeads() {
            const checkboxes = document.querySelectorAll('#grtLeadsBody input.grt-checkbox:checked');
            if (checkboxes.length === 0) {
                showGRTMessage('Please select at least one lead to add', true);
                return;
            }
            
            checkboxes.forEach(cb => {
                const leadCode = cb.getAttribute('data-leadcode');
                const lead = grtAvailableLeads.find(l => l.leadCode === leadCode);
                if (lead && !grtSelectedLeads.some(s => s.leadCode === leadCode)) {
                    grtSelectedLeads.push({ ...lead, status: 'Active' });
                }
            });
            
            loadSelectedGRTLeads();
            loadLeadsForGRTCenter();
            showGRTMessage(`${checkboxes.length} lead(s) added successfully`);
        }

        // Load selected leads table
        function loadSelectedGRTLeads() {
            const tbody = document.getElementById('grtSelectedBody');
            if (!tbody) return;
            
            tbody.innerHTML = '';
            if (grtSelectedLeads.length === 0) {
                tbody.innerHTML = '<tr><td colspan="6" style="text-align:center">No leads selected</td></tr>';
                return;
            }
            
            grtSelectedLeads.forEach((lead, index) => {
                const row = tbody.insertRow();
                row.innerHTML = `
                    <td>${lead.leadCode}</td>
                    <td>${lead.leadName}</td>
                    <td>${lead.phoneNo}</td>
                    <td>${lead.aadharNo}</td>
                    <td><span class="grt-status-active">${lead.status}</span></td>
                    <td><button class="grt-remove-lead-btn" onclick="removeGRTLead(${index})">Remove</button></td>
                `;
            });
        }

        // Remove lead
        function removeGRTLead(index) {
            grtSelectedLeads.splice(index, 1);
            loadSelectedGRTLeads();
            loadLeadsForGRTCenter();
            showGRTMessage('Lead removed successfully');
        }

        // Generate GRT Code
        function generateGRTCode() {
            if (grtDataList.length === 0) return 'GRT000001';
            const lastGRT = grtDataList[grtDataList.length - 1];
            const lastNum = parseInt(lastGRT.grtCode.replace('GRT', ''));
            const newNum = lastNum + 1;
            return `GRT${String(newNum).padStart(6, '0')}`;
        }

        // Save GRT
        function saveGRT() {
            const branch = document.getElementById('grtBranch').value;
            const center = document.getElementById('grtCenter').value;
            const fieldOfficer = document.getElementById('grtFieldOfficer').value;
            const startDate = document.getElementById('grtStartDate').value;
            const duration = document.getElementById('grtDuration').value;
            const description = document.getElementById('grtDescription').value;
            
            if (!center) {
                showGRTMessage('Please select a center', true);
                return;
            }
            if (!startDate) {
                showGRTMessage('Please select GRT start date', true);
                return;
            }
            if (!duration) {
                showGRTMessage('Please enter number of days for GRT', true);
                return;
            }
            if (grtSelectedLeads.length === 0) {
                showGRTMessage('Please add at least one lead to the GRT', true);
                return;
            }
            
            const newGRT = {
                grtCode: generateGRTCode(),
                startDate: formatGRTDate(startDate),
                startDateInput: startDate,
                center: center,
                foCode: fieldOfficer || 'Not Assigned',
                duration: duration,
                description: description || '',
                status: 'Active',
                leads: [...grtSelectedLeads],
                branch: branch
            };
            
            grtDataList.push(newGRT);
            saveGRTToLocalStorage();
            loadGRTHistory();
            clearGRTForm();
            showGRTMessage(`GRT ${newGRT.grtCode} created successfully!`);
            showGRTListView();
        }

        // Edit GRT
        function editGRT(grtCode) {
            const grt = grtDataList.find(g => g.grtCode === grtCode);
            if (!grt) return;
            
            currentEditGrtCode = grtCode;
            
            document.getElementById('grtBranch').value = grt.branch || 'HEAD OFFICE - 001';
            document.getElementById('grtCenter').value = grt.center;
            document.getElementById('grtFieldOfficer').value = grt.foCode === 'Not Assigned' ? '' : grt.foCode;
            document.getElementById('grtStartDate').value = formatGRTDateForInput(grt.startDate);
            document.getElementById('grtDuration').value = grt.duration;
            document.getElementById('grtDescription').value = grt.description || '';
            
            grtSelectedLeads = [...grt.leads];
            loadSelectedGRTLeads();
            loadLeadsForGRTCenter();
            
            const saveBtn = document.getElementById('grtSaveBtn');
            saveBtn.textContent = 'Update';
            saveBtn.onclick = updateGRT;
            
            showGRTFormView();
            showGRTMessage(`Editing GRT: ${grtCode}`);
        }

        // Update GRT
        function updateGRT() {
            if (!currentEditGrtCode) {
                showGRTMessage('No GRT selected for update', true);
                return;
            }
            
            const index = grtDataList.findIndex(g => g.grtCode === currentEditGrtCode);
            if (index === -1) {
                showGRTMessage('GRT not found', true);
                return;
            }
            
            const branch = document.getElementById('grtBranch').value;
            const center = document.getElementById('grtCenter').value;
            const fieldOfficer = document.getElementById('grtFieldOfficer').value;
            const startDate = document.getElementById('grtStartDate').value;
            const duration = document.getElementById('grtDuration').value;
            const description = document.getElementById('grtDescription').value;
            
            grtDataList[index] = {
                ...grtDataList[index],
                branch: branch,
                center: center,
                foCode: fieldOfficer || 'Not Assigned',
                startDate: formatGRTDate(startDate),
                startDateInput: startDate,
                duration: duration,
                description: description || '',
                leads: [...grtSelectedLeads]
            };
            
            saveGRTToLocalStorage();
            loadGRTHistory();
            clearGRTForm();
            showGRTMessage(`GRT ${currentEditGrtCode} updated successfully!`);
            
            const saveBtn = document.getElementById('grtSaveBtn');
            saveBtn.textContent = 'Save';
            saveBtn.onclick = saveGRT;
            currentEditGrtCode = null;
            
            showGRTListView();
        }

        // Close GRT
        function closeGRT(grtCode) {
            if (confirm(`Are you sure you want to close GRT ${grtCode}?`)) {
                const index = grtDataList.findIndex(g => g.grtCode === grtCode);
                if (index !== -1) {
                    grtDataList[index].status = 'Closed';
                    saveGRTToLocalStorage();
                    loadGRTHistory();
                    showGRTMessage(`GRT ${grtCode} has been closed`);
                }
            }
        }

        // Search GRT
        function searchGRT() {
            const searchTerm = document.getElementById('grtSearchInput').value.toLowerCase();
            const showAll = document.getElementById('grtShowAll').checked;
            
            let filtered = [...grtDataList];
            
            if (!showAll) {
                filtered = filtered.filter(grt => grt.status === 'Active');
            }
            
            if (searchTerm) {
                filtered = filtered.filter(grt => 
                    grt.grtCode.toLowerCase().includes(searchTerm) ||
                    grt.center.toLowerCase().includes(searchTerm) ||
                    grt.foCode.toLowerCase().includes(searchTerm)
                );
            }
            
            const container = document.getElementById('grtCardsContainer');
            container.innerHTML = '';
            
            if (filtered.length === 0) {
                container.innerHTML = '<div style="text-align:center; padding:40px;">No matching GRT records found.</div>';
                return;
            }
            
            filtered.forEach(grt => {
                const card = document.createElement('div');
                card.className = 'grt-card';
                card.innerHTML = `
                    <div class="grt-card-header">
                        <span class="grt-card-code">${grt.grtCode}</span>
                        <span class="grt-card-status ${grt.status === 'Active' ? 'grt-card-status-active' : 'grt-card-status-closed'}">${grt.status}</span>
                    </div>
                    <div class="grt-card-body">
                        <div class="grt-card-row">
                            <span class="grt-card-label">GRT Start Date:</span>
                            <span class="grt-card-value">${grt.startDate}</span>
                        </div>
                        <div class="grt-card-row">
                            <span class="grt-card-label">Center:</span>
                            <span class="grt-card-value">${grt.center}</span>
                        </div>
                        <div class="grt-card-row">
                            <span class="grt-card-label">FO Code:</span>
                            <span class="grt-card-value">${grt.foCode}</span>
                        </div>
                        <div class="grt-card-row">
                            <span class="grt-card-label">GRT Duration:</span>
                            <span class="grt-card-value">${grt.duration} days</span>
                        </div>
                    </div>
                    <div class="grt-card-actions">
                        <button class="grt-card-edit" onclick="editGRT('${grt.grtCode}')">Edit</button>
                        <button class="grt-card-close" onclick="closeGRT('${grt.grtCode}')">GRT Close</button>
                    </div>
                `;
                container.appendChild(card);
            });
        }

        // Close Search - clears search and shows all
        function closeGRTSearch() {
            document.getElementById('grtSearchInput').value = '';
            document.getElementById('grtShowAll').checked = false;
            loadGRTHistory();
        }

        // Add New GRT
        function addNewGRT() {
            clearGRTForm();
            showGRTFormView();
        }

        // Clear Form
        function clearGRTForm() {
            document.getElementById('grtBranch').value = 'HEAD OFFICE - 001';
            document.getElementById('grtCenter').value = 'CENTER1';
            document.getElementById('grtFieldOfficer').value = '';
            document.getElementById('grtStartDate').value = '';
            document.getElementById('grtDuration').value = '';
            document.getElementById('grtDescription').value = '';
            grtSelectedLeads = [];
            loadSelectedGRTLeads();
            loadLeadsForGRTCenter();
            
            const saveBtn = document.getElementById('grtSaveBtn');
            saveBtn.textContent = 'Save';
            saveBtn.onclick = saveGRT;
            currentEditGrtCode = null;
        }

        // Refresh Form
        function refreshGRTForm() {
            clearGRTForm();
            showGRTMessage('Form has been refreshed');
        }

        // Close Form
        function closeGRTForm() {
            clearGRTForm();
            showGRTListView();
        }

        // Save to localStorage
        function saveGRTToLocalStorage() {
            localStorage.setItem('grtDataList', JSON.stringify(grtDataList));
            localStorage.setItem('grtAvailableLeads', JSON.stringify(grtAvailableLeads));
        }

        // Load from localStorage
        function loadGRTFromLocalStorage() {
            const savedGRT = localStorage.getItem('grtDataList');
            const savedLeads = localStorage.getItem('grtAvailableLeads');
            
            if (savedGRT) {
                grtDataList = JSON.parse(savedGRT);
            }
            if (savedLeads) {
                grtAvailableLeads = JSON.parse(savedLeads);
            }
        }

        // Set default start date
        function setDefaultGRTStartDate() {
            const startDateInput = document.getElementById('grtStartDate');
            if (startDateInput && !startDateInput.value) {
                const today = new Date().toISOString().slice(0, 10);
                startDateInput.value = today;
            }
        }

        // Initialize GRT Management
        function initializeGRTManagement() {
            loadGRTFromLocalStorage();
            loadGRTHistory();
            loadLeadsForGRTCenter();
            loadSelectedGRTLeads();
            setDefaultGRTStartDate();
            
            // Add "Add Selected" button to leads table header
            const leadsHeader = document.querySelector('#grtLeadsTable thead tr');
            if (leadsHeader && !document.getElementById('grtAddSelectedBtn')) {
                const addSelectedTh = document.createElement('th');
                addSelectedTh.innerHTML = '<button id="grtAddSelectedBtn" class="grt-add-lead-btn" style="background:#2a7f6e" onclick="addSelectedGRTLeads()">Add Selected</button>';
                leadsHeader.appendChild(addSelectedTh);
            }
            
            const searchBtn = document.getElementById('grtSearchBtn');
            const searchInput = document.getElementById('grtSearchInput');
            const showAllCheckbox = document.getElementById('grtShowAll');
            const closeSearchBtn = document.getElementById('grtCloseSearchBtn');
            const addNewBtn = document.getElementById('grtAddNewBtn');
            const refreshBtn = document.getElementById('grtRefreshBtn');
            const closeBtn = document.getElementById('grtCloseBtn');
            const backBtn = document.getElementById('grtBackBtn');
            
            if (searchBtn) searchBtn.onclick = searchGRT;
            if (searchInput) searchInput.onkeyup = (e) => { if (e.key === 'Enter') searchGRT(); };
            if (showAllCheckbox) showAllCheckbox.onchange = searchGRT;
            if (closeSearchBtn) closeSearchBtn.onclick = closeGRTSearch;
            if (addNewBtn) addNewBtn.onclick = addNewGRT;
            if (refreshBtn) refreshBtn.onclick = refreshGRTForm;
            if (closeBtn) closeBtn.onclick = closeGRTForm;
            if (backBtn) backBtn.onclick = closeGRTForm;
        }

        // Initialize when DOM is ready
        document.addEventListener('DOMContentLoaded', function() {
            initializeGRTManagement();
        });

        // Group Master Functions - Loan Preparation Module

        // Global variable to store member queue
        let memberQueue = [];
        let groupsDatabase = [];
        let currentEditGroupCode = null;

        // Main function to show Group Master (called from navigation link)
        function showGroupMaster() {
            // Hide all other content sections if you have that pattern
            if (document.querySelectorAll('.content-section').length > 0) {
                document.querySelectorAll('.content-section').forEach(section => {
                    section.style.display = 'none';
                });
            }
            
            // Show the Group Master container
            const groupMasterContainer = document.getElementById('groupMasterContainer');
            if (groupMasterContainer) {
                groupMasterContainer.style.display = 'block';
            }
            
            // Initialize Group Master data and events
            initGroupMasterData();
            attachGroupMasterEvents();
        }

        // Initialize mock data
        function initGroupMasterData() {
            if (groupsDatabase.length === 0) {
                groupsDatabase = [
                    { groupCode: 'GRP-001', groupName: 'Women Prosper', dateOfJoin: '2025-01-10', collector: 'Ramesh K', branch: 'HEAD OFFICE - 001', center: 'CENTER1-001' },
                    { groupCode: 'GRP-002', groupName: 'Green Fields', dateOfJoin: '2025-02-15', collector: 'Sita M', branch: 'BRANCH - 002', center: 'CENTER1-002' },
                    { groupCode: 'GRP-003', groupName: 'Unity Group', dateOfJoin: '2025-03-20', collector: 'John D', branch: 'HEAD OFFICE - 001', center: 'CENTER2-001' }
                ];
            }
            
            // Set opening date to today
            const openingDateInput = document.getElementById('openingDate');
            if (openingDateInput && !openingDateInput.value) {
                openingDateInput.value = new Date().toISOString().slice(0,10);
            }
            
            renderGroupsTable();
            renderQueueTable();
        }

        // Attach all event listeners
        function attachGroupMasterEvents() {
            // Include Lead checkbox toggle
            const includeLeadCheck = document.getElementById('includeLead');
            const leadSection = document.getElementById('leadSection');
            if (includeLeadCheck && leadSection) {
                // Remove old listener to avoid duplicates
                const newCheck = includeLeadCheck.cloneNode(true);
                includeLeadCheck.parentNode.replaceChild(newCheck, includeLeadCheck);
                newCheck.addEventListener('change', function(e) {
                    const leadSectionEl = document.getElementById('leadSection');
                    if (leadSectionEl) {
                        leadSectionEl.style.display = e.target.checked ? 'block' : 'none';
                    }
                    if (!e.target.checked) {
                        const leadCodeInput = document.getElementById('leadCode');
                        const leadNameInput = document.getElementById('leadName');
                        if (leadCodeInput) leadCodeInput.value = '';
                        if (leadNameInput) leadNameInput.value = '';
                    }
                });
            }
            
            // Add to Queue button
            const addToQueueBtn = document.getElementById('addToQueueBtn');
            if (addToQueueBtn) {
                const newBtn = addToQueueBtn.cloneNode(true);
                addToQueueBtn.parentNode.replaceChild(newBtn, addToQueueBtn);
                newBtn.addEventListener('click', addToQueue);
            }
            
            // Confirm And Create button
            const confirmCreateBtn = document.getElementById('confirmCreateBtn');
            if (confirmCreateBtn) {
                const newBtn = confirmCreateBtn.cloneNode(true);
                confirmCreateBtn.parentNode.replaceChild(newBtn, confirmCreateBtn);
                newBtn.addEventListener('click', confirmAndCreateGroup);
            }
            
            // Update Group button
            const updateGroupBtn = document.getElementById('updateGroupBtn');
            if (updateGroupBtn) {
                const newBtn = updateGroupBtn.cloneNode(true);
                updateGroupBtn.parentNode.replaceChild(newBtn, updateGroupBtn);
                newBtn.addEventListener('click', updateGroup);
            }
            
            // Delete Group button
            const deleteGroupBtn = document.getElementById('deleteGroupBtn');
            if (deleteGroupBtn) {
                const newBtn = deleteGroupBtn.cloneNode(true);
                deleteGroupBtn.parentNode.replaceChild(newBtn, deleteGroupBtn);
                newBtn.addEventListener('click', deleteGroup);
            }
            
            // Search Group button
            const searchGroupBtn = document.getElementById('searchGroupBtn');
            if (searchGroupBtn) {
                const newBtn = searchGroupBtn.cloneNode(true);
                searchGroupBtn.parentNode.replaceChild(newBtn, searchGroupBtn);
                newBtn.addEventListener('click', searchGroupByName);
            }
        }

        // Add member to queue
        function addToQueue() {
            const includeLeadCheck = document.getElementById('includeLead');
            const leadCodeInput = document.getElementById('leadCode');
            const leadNameInput = document.getElementById('leadName');
            
            const leadCode = leadCodeInput ? leadCodeInput.value.trim() : '';
            const leadName = leadNameInput ? leadNameInput.value.trim() : '';
            
            if (includeLeadCheck && includeLeadCheck.checked && !leadName) {
                alert('Please enter Lead Name before adding to queue');
                return;
            }
            
            // Generate member code
            const memberCode = 'MEM' + Date.now().toString().slice(-6) + Math.floor(Math.random() * 100);
            
            const newMember = {
                memberCode: memberCode,
                leadCode: (includeLeadCheck && includeLeadCheck.checked) ? leadCode : '',
                memberName: leadName || ((includeLeadCheck && includeLeadCheck.checked) ? 'Lead Member' : 'New Member')
            };
            
            memberQueue.push(newMember);
            renderQueueTable();
            
            // Clear lead fields
            if (includeLeadCheck && includeLeadCheck.checked) {
                if (leadCodeInput) leadCodeInput.value = '';
                if (leadNameInput) leadNameInput.value = '';
            }
            
            showSearchResult(`Added "${newMember.memberName}" to queue`, '#2e7d32');
        }

        // Render member queue table
        function renderQueueTable() {
            const queueBody = document.getElementById('queueBody');
            if (!queueBody) return;
            
            if (memberQueue.length === 0) {
                queueBody.innerHTML = '<tr><td colspan="4" class="empty-row">No members added yet</td></tr>';
                return;
            }
            
            queueBody.innerHTML = memberQueue.map((m, idx) => `
                <tr>
                    <td>${escapeHtml(m.memberCode)}</td>
                    <td>${escapeHtml(m.leadCode || '—')}</td>
                    <td>${escapeHtml(m.memberName)}</td>
                    <td><i class="fas fa-trash-alt delete-icon" data-index="${idx}" style="color:#c0392b; cursor:pointer;"></i></td>
                </tr>
            `).join('');
            
            // Attach delete events
            document.querySelectorAll('.delete-icon[data-index]').forEach(icon => {
                icon.addEventListener('click', function(e) {
                    const idx = parseInt(this.getAttribute('data-index'));
                    if (!isNaN(idx)) {
                        memberQueue.splice(idx, 1);
                        renderQueueTable();
                    }
                    e.stopPropagation();
                });
            });
        }

        // Render existing groups table
        function renderGroupsTable() {
            const groupsListBody = document.getElementById('groupsListBody');
            if (!groupsListBody) return;
            
            if (groupsDatabase.length === 0) {
                groupsListBody.innerHTML = '<tr><td colspan="6" class="empty-row">No groups found</td></tr>';
                return;
            }
            
            groupsListBody.innerHTML = groupsDatabase.map(g => `
                <tr data-groupcode="${g.groupCode}" style="cursor:pointer">
                    <td>${escapeHtml(g.groupCode)}</td>
                    <td>${escapeHtml(g.groupName)}</td>
                    <td>${escapeHtml(g.dateOfJoin)}</td>
                    <td>${escapeHtml(g.collector)}</td>
                    <td>${escapeHtml(g.branch)}</td>
                    <td>${escapeHtml(g.center)}</td>
                </tr>
            `).join('');
            
            // Attach click event to populate form for editing
            document.querySelectorAll('#groupsListBody tr[data-groupcode]').forEach(row => {
                row.addEventListener('click', function(e) {
                    if (e.target.classList && e.target.classList.contains('delete-icon')) return;
                    const groupCode = this.getAttribute('data-groupcode');
                    const group = groupsDatabase.find(g => g.groupCode === groupCode);
                    if (group) populateFormForEdit(group);
                });
            });
        }

        // Populate form for editing
        function populateFormForEdit(group) {
            const groupCodeInput = document.getElementById('groupCode');
            const groupNameInput = document.getElementById('groupName');
            const openingDateInput = document.getElementById('openingDate');
            const branchSelect = document.getElementById('branch');
            const centerSelect = document.getElementById('center');
            const groupHeadInput = document.getElementById('groupHead');
            
            if (groupCodeInput) groupCodeInput.value = group.groupCode;
            if (groupNameInput) groupNameInput.value = group.groupName;
            if (openingDateInput) openingDateInput.value = group.dateOfJoin;
            if (branchSelect) branchSelect.value = group.branch;
            if (centerSelect) centerSelect.value = group.center;
            if (groupHeadInput) groupHeadInput.value = group.collector || '';
            
            currentEditGroupCode = group.groupCode;
            
            // Reset queue and lead section
            memberQueue = [];
            renderQueueTable();
            
            const includeLeadCheck = document.getElementById('includeLead');
            const leadSection = document.getElementById('leadSection');
            if (includeLeadCheck) includeLeadCheck.checked = false;
            if (leadSection) leadSection.style.display = 'none';
            
            showSearchResult(`Editing group: ${group.groupName}`, '#0b5e7e');
        }

        // Confirm and create new group
        function confirmAndCreateGroup() {
            const groupNameInput = document.getElementById('groupName');
            const groupName = groupNameInput ? groupNameInput.value.trim() : '';
            
            if (!groupName) {
                alert('Group Name is required');
                return;
            }
            
            const groupCodeInput = document.getElementById('groupCode');
            const openingDateInput = document.getElementById('openingDate');
            const branchSelect = document.getElementById('branch');
            const centerSelect = document.getElementById('center');
            const groupHeadInput = document.getElementById('groupHead');
            
            const groupCode = (groupCodeInput && groupCodeInput.value.trim()) 
                ? groupCodeInput.value.trim() 
                : 'GRP' + Date.now().toString().slice(-5);
            const openingDate = openingDateInput ? openingDateInput.value : new Date().toISOString().slice(0,10);
            const branch = branchSelect ? branchSelect.value : 'HEAD OFFICE - 001';
            const center = centerSelect ? centerSelect.value : 'CENTER1-001';
            const collector = (groupHeadInput && groupHeadInput.value.trim()) ? groupHeadInput.value.trim() : 'System';
            
            // Check duplicate
            if (groupsDatabase.some(g => g.groupCode === groupCode)) {
                alert(`Group code ${groupCode} already exists. Use update or different code.`);
                return;
            }
            
            const newGroup = {
                groupCode: groupCode,
                groupName: groupName,
                dateOfJoin: openingDate,
                collector: collector,
                branch: branch,
                center: center,
                members: [...memberQueue]
            };
            
            groupsDatabase.push(newGroup);
            renderGroupsTable();
            resetGroupMasterForm();
            memberQueue = [];
            renderQueueTable();
            showSearchResult(`Group "${groupName}" created successfully!`, '#1e6f3f');
        }

        // Update existing group
        function updateGroup() {
            if (!currentEditGroupCode) {
                alert('No group selected for update. Click on a group from the table first.');
                return;
            }
            
            const groupIndex = groupsDatabase.findIndex(g => g.groupCode === currentEditGroupCode);
            if (groupIndex === -1) {
                alert('Group not found in database');
                return;
            }
            
            const groupNameInput = document.getElementById('groupName');
            const openingDateInput = document.getElementById('openingDate');
            const branchSelect = document.getElementById('branch');
            const centerSelect = document.getElementById('center');
            const groupHeadInput = document.getElementById('groupHead');
            
            const updatedGroupName = groupNameInput ? groupNameInput.value.trim() : '';
            if (!updatedGroupName) {
                alert('Group name cannot be empty');
                return;
            }
            
            groupsDatabase[groupIndex].groupName = updatedGroupName;
            groupsDatabase[groupIndex].dateOfJoin = openingDateInput ? openingDateInput.value : groupsDatabase[groupIndex].dateOfJoin;
            groupsDatabase[groupIndex].branch = branchSelect ? branchSelect.value : groupsDatabase[groupIndex].branch;
            groupsDatabase[groupIndex].center = centerSelect ? centerSelect.value : groupsDatabase[groupIndex].center;
            groupsDatabase[groupIndex].collector = (groupHeadInput && groupHeadInput.value.trim()) ? groupHeadInput.value.trim() : groupsDatabase[groupIndex].collector;
            
            renderGroupsTable();
            showSearchResult(`Group "${updatedGroupName}" updated successfully`, '#e67e22');
            resetGroupMasterForm();
            currentEditGroupCode = null;
            memberQueue = [];
            renderQueueTable();
        }

        // Delete group
        function deleteGroup() {
            const groupCodeInput = document.getElementById('groupCode');
            const targetCode = currentEditGroupCode || (groupCodeInput ? groupCodeInput.value.trim() : '');
            
            if (!targetCode) {
                alert('Select a group from the table or enter group code to delete');
                return;
            }
            
            const exists = groupsDatabase.some(g => g.groupCode === targetCode);
            if (!exists) {
                alert(`Group ${targetCode} not found`);
                return;
            }
            
            if (confirm(`Permanently delete group ${targetCode}?`)) {
                groupsDatabase = groupsDatabase.filter(g => g.groupCode !== targetCode);
                renderGroupsTable();
                resetGroupMasterForm();
                currentEditGroupCode = null;
                memberQueue = [];
                renderQueueTable();
                showSearchResult(`Group ${targetCode} deleted`, '#c0392b');
            }
        }

        // Search group by name
        function searchGroupByName() {
            const searchInput = document.getElementById('searchGroupName');
            const searchTerm = searchInput ? searchInput.value.trim().toLowerCase() : '';
            
            if (!searchTerm) {
                showSearchResult('Enter a group name to search', '#e67e22');
                return;
            }
            
            const results = groupsDatabase.filter(g => g.groupName.toLowerCase().includes(searchTerm));
            
            if (results.length === 0) {
                showSearchResult(`No groups found matching "${searchTerm}"`, '#c0392b');
            } else {
                const names = results.map(g => `${g.groupName} (${g.groupCode})`).join(', ');
                showSearchResult(`Found ${results.length} group(s): ${names}`, '#2c7da0');
            }
        }

        // Show search result message
        function showSearchResult(msg, color) {
            const searchResultsDiv = document.getElementById('searchResults');
            if (searchResultsDiv) {
                searchResultsDiv.innerHTML = `<span style="color:${color}">🔍 ${msg}</span>`;
                setTimeout(() => {
                    if (searchResultsDiv) searchResultsDiv.innerHTML = '';
                }, 3000);
            }
        }

        // Reset form
        function resetGroupMasterForm() {
            const groupCodeInput = document.getElementById('groupCode');
            const groupNameInput = document.getElementById('groupName');
            const openingDateInput = document.getElementById('openingDate');
            const branchSelect = document.getElementById('branch');
            const centerSelect = document.getElementById('center');
            const groupHeadInput = document.getElementById('groupHead');
            const phoneInput = document.getElementById('phoneNo');
            const addressInput = document.getElementById('address');
            const idNoInput = document.getElementById('idNo');
            const foCodeInput = document.getElementById('foCode');
            const includeLeadCheck = document.getElementById('includeLead');
            const leadSection = document.getElementById('leadSection');
            const leadCodeInput = document.getElementById('leadCode');
            const leadNameInput = document.getElementById('leadName');
            
            if (groupCodeInput) groupCodeInput.value = '';
            if (groupNameInput) groupNameInput.value = '';
            if (openingDateInput) openingDateInput.value = new Date().toISOString().slice(0,10);
            if (branchSelect) branchSelect.value = 'HEAD OFFICE - 001';
            if (centerSelect) centerSelect.value = 'CENTER1-001';
            if (groupHeadInput) groupHeadInput.value = '';
            if (phoneInput) phoneInput.value = '';
            if (addressInput) addressInput.value = '';
            if (idNoInput) idNoInput.value = '';
            if (foCodeInput) foCodeInput.value = '';
            if (includeLeadCheck) includeLeadCheck.checked = false;
            if (leadSection) leadSection.style.display = 'none';
            if (leadCodeInput) leadCodeInput.value = '';
            if (leadNameInput) leadNameInput.value = '';
        }

        // Helper function to escape HTML
        function escapeHtml(str) {
            if (!str) return '';
            return str.replace(/[&<>]/g, function(m) {
                if (m === '&') return '&amp;';
                if (m === '<') return '&lt;';
                if (m === '>') return '&gt;';
                return m;
            });
        }

        // Member Entry Module Functions

        // Calculate age from date of birth
        function calculateAge() {
            const dobInput = document.getElementById('dob');
            const ageInput = document.getElementById('age');
            
            if (dobInput && dobInput.value && ageInput) {
                const birthDate = new Date(dobInput.value);
                const today = new Date();
                let age = today.getFullYear() - birthDate.getFullYear();
                const monthDiff = today.getMonth() - birthDate.getMonth();
                if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
                    age--;
                }
                ageInput.value = age;
            }
        }

        // Print money receipt
        function printMoneyReceipt() {
            const memberName = document.getElementById('memberName')?.value || 'New Member';
            const membershipCode = document.getElementById('membershipCode')?.value || 'N/A';
            
            const printWindow = window.open('', '_blank');
            printWindow.document.write(`
                <html>
                <head><title>Money Receipt</title>
                <style>
                    body { font-family: Arial; padding: 40px; }
                    .receipt { border: 1px solid #000; padding: 20px; max-width: 400px; margin: auto; }
                    h2 { text-align: center; }
                    hr { margin: 15px 0; }
                </style>
                </head>
                <body>
                <div class="receipt">
                    <h2>MONEY RECEIPT</h2>
                    <hr>
                    <p><strong>Member Name:</strong> ${memberName}</p>
                    <p><strong>Membership Code:</strong> ${membershipCode}</p>
                    <p><strong>Date:</strong> ${new Date().toLocaleDateString()}</p>
                    <hr>
                    <p style="text-align:center">Thank you</p>
                </div>
                </body>
                </html>
            `);
            printWindow.print();
            printWindow.close();
        }

        // Reset entire member form
        function resetMemberForm() {
            document.querySelectorAll('#memberEntryContainer input, #memberEntryContainer select, #memberEntryContainer textarea').forEach(field => {
                if (field.type !== 'file') {
                    field.value = '';
                } else {
                    field.value = '';
                }
            });
            
            // Reset date fields to defaults
            const dojInput = document.getElementById('dateOfJoining');
            const dobInput = document.getElementById('dob');
            if (dojInput) dojInput.value = new Date().toISOString().slice(0,10);
            if (dobInput) dobInput.value = new Date().toISOString().slice(0,10);
            
            const ageInput = document.getElementById('age');
            if (ageInput) ageInput.value = '';
            
            alert('Form reset successfully');
        }

        // Post member data (save to database)
        function postMemberData() {
            const memberName = document.getElementById('memberName')?.value;
            if (!memberName) {
                alert('Please enter Member Name');
                return;
            }
            
            const memberData = {
                membershipCode: document.getElementById('membershipCode')?.value,
                dateOfJoining: document.getElementById('dateOfJoining')?.value,
                secondaryMemberCode: document.getElementById('secondaryMemberCode')?.value,
                memberName: memberName,
                fatherHusbandName: document.getElementById('fatherHusbandName')?.value,
                address: document.getElementById('address')?.value,
                pinCode: document.getElementById('pinCode')?.value,
                email: document.getElementById('email')?.value,
                dob: document.getElementById('dob')?.value,
                age: document.getElementById('age')?.value,
                nomineeName: document.getElementById('nomineeName')?.value,
                nomineeRelation: document.getElementById('nomineeRelation')?.value,
                bloodGroup: document.getElementById('bloodGroup')?.value,
                phoneNo: document.getElementById('phoneNo')?.value,
                education: document.getElementById('education')?.value,
                occupation: document.getElementById('occupation')?.value,
                branchNameCode: document.getElementById('branchNameCode')?.value,
                membershipFees: document.getElementById('membershipFees')?.value,
                remarks: document.getElementById('remarks')?.value,
                accountNo: document.getElementById('accountNo')?.value,
                bankName: document.getElementById('bankName')?.value,
                ifscCode: document.getElementById('ifscCode')?.value,
                bankBranch: document.getElementById('bankBranch')?.value,
                panNo: document.getElementById('panNo')?.value,
                passportNo: document.getElementById('passportNo')?.value,
                rationCardNo: document.getElementById('rationCardNo')?.value,
                aadharNo: document.getElementById('aadharNo')?.value,
                companyCode: document.getElementById('companyCode')?.value
            };
            
            console.log('Member Data Posted:', memberData);
            
            // Here you would send to your backend API
            // Example: fetch('/api/members', { method: 'POST', body: JSON.stringify(memberData) })
            
            alert(`Member "${memberName}" posted successfully!`);
        }

        // Print member details
        function printMemberDetails() {
            const memberName = document.getElementById('memberName')?.value || 'N/A';
            const membershipCode = document.getElementById('membershipCode')?.value || 'N/A';
            
            const printWindow = window.open('', '_blank');
            printWindow.document.write(`
                <html>
                <head><title>Member Details</title>
                <style>
                    body { font-family: Arial; padding: 30px; }
                    .details { border: 1px solid #ccc; padding: 20px; }
                    h2 { text-align: center; color: #2c3e50; }
                    table { width: 100%; border-collapse: collapse; margin-top: 15px; }
                    td { padding: 8px; border-bottom: 1px solid #eee; }
                    td:first-child { font-weight: bold; width: 35%; }
                </style>
                </head>
                <body>
                <div class="details">
                    <h2>MEMBER DETAILS</h2>
                    <table>
                        <tr><td>Member Name:</td><td>${memberName}</td></tr>
                        <tr><td>Membership Code:</td><td>${membershipCode}</td></tr>
                        <tr><td>Father/Husband:</td><td>${document.getElementById('fatherHusbandName')?.value || 'N/A'}</td></tr>
                        <tr><td>Phone No:</td><td>${document.getElementById('phoneNo')?.value || 'N/A'}</td></tr>
                        <tr><td>Email:</td><td>${document.getElementById('email')?.value || 'N/A'}</td></tr>
                        <tr><td>Address:</td><td>${document.getElementById('address')?.value || 'N/A'}</td></tr>
                    </table>
                    <hr>
                    <p style="text-align:center">Printed on ${new Date().toLocaleString()}</p>
                </div>
                </body>
                </html>
            `);
            printWindow.print();
            printWindow.close();
        }

        // Exit member module
        function exitMemberModule() {
            if (confirm('Are you sure you want to exit? Unsaved data will be lost.')) {
                resetMemberForm();
                alert('Exited Member Entry Module');
                // You can also hide the container or redirect
                // document.getElementById('memberEntryContainer').style.display = 'none';
            }
        }

        // Delete member
        function deleteMember() {
            const memberName = document.getElementById('memberName')?.value;
            if (!memberName) {
                alert('No member data to delete');
                return;
            }
            
            if (confirm(`Are you sure you want to delete member "${memberName}"? This action cannot be undone.`)) {
                resetMemberForm();
                alert(`Member "${memberName}" deleted successfully`);
            }
        }

        // Capture fingerprint (simulated)
        function captureFingerprint() {
            alert('Fingerprint capture device initialized. Please place finger on scanner.');
            // In real implementation, this would interface with biometric device
        }

        // Upload document handler
        function uploadDocument(docType) {
            alert(`Upload document for: ${docType}\nPlease select a file.`);
            // Trigger file input or open modal
        }

        // File input display handlers
        document.addEventListener('DOMContentLoaded', function() {
            // Show selected file name for file inputs
            const fileInputs = document.querySelectorAll('.file-input-wrapper input[type="file"]');
            fileInputs.forEach(input => {
                input.addEventListener('change', function(e) {
                    const fileName = this.files[0]?.name || 'Browse';
                    const span = this.parentElement.querySelector('.file-name');
                    if (span) span.textContent = fileName;
                });
            });
            
            // Calculate age on page load if DOB exists
            calculateAge();
        });

        // Main function to show Member Entry (call from navigation)
        function showMemberEntry() {
            // Hide other content sections
            if (document.querySelectorAll('.content-section')) {
                document.querySelectorAll('.content-section').forEach(section => {
                    section.style.display = 'none';
                });
            }
            
            const memberContainer = document.getElementById('memberEntryContainer');
            if (memberContainer) {
                memberContainer.style.display = 'block';
            }
            
            // Reset any unsaved data if needed
            // resetMemberForm();
        }

        // Document Approval Module Functions

        // Sample document data (mock)
        let currentMember = {
            code: '101',
            name: 'RAHUL KUMAR VERMA',
            documents: {
                idProof: { status: 'pending', image: null },
                addressProof: { status: 'pending', image: null },
                photo: { status: 'pending', image: null },
                signature: { status: 'pending', image: null },
                profDoc: { status: 'pending', image: null },
                bankDoc: { status: 'pending', image: null }
            }
        };

        let currentZoomDoc = null;
        let currentZoomDocType = null;

        // Search member
        function searchMember() {
            const memberCode = document.getElementById('memberCode').value;
            const memberNameField = document.getElementById('memberName');
            
            if (!memberCode) {
                alert('Please enter Member Code');
                return;
            }
            
            // Mock search - in real system, fetch from backend
            if (memberCode === '101') {
                memberNameField.value = 'RAHUL KUMAR VERMA';
                currentMember.code = '101';
                currentMember.name = 'RAHUL KUMAR VERMA';
                
                // Load mock documents (sample base64 images would come from server)
                loadMockDocuments();
                updateDocumentStatuses();
            } else {
                memberNameField.value = 'Member Not Found';
                alert('Member not found. Please check the code.');
            }
        }

        // Load mock documents (simulate server data)
        function loadMockDocuments() {
            // For demo, we'll create placeholder images
            // In real system, these would be actual document URLs
            
            // ID Proof - sample
            currentMember.documents.idProof.status = 'pending';
            currentMember.documents.idProof.image = null;
            
            // Address Proof - sample with mock image
            currentMember.documents.addressProof.status = 'pending';
            currentMember.documents.addressProof.image = null;
            
            // Photo - sample
            currentMember.documents.photo.status = 'pending';
            currentMember.documents.photo.image = null;
            
            // Signature - sample
            currentMember.documents.signature.status = 'pending';
            currentMember.documents.signature.image = null;
            
            // Prof. DOC - sample
            currentMember.documents.profDoc.status = 'pending';
            currentMember.documents.profDoc.image = null;
            
            // Bank Doc - sample
            currentMember.documents.bankDoc.status = 'pending';
            currentMember.documents.bankDoc.image = null;
            
            // For demo, show some documents as uploaded
            displayDocumentImages();
        }

        // Display document images
        function displayDocumentImages() {
            // For demo, we'll show a sample document for ID Proof
            // In real system, you would load actual images from server
            
            // Example: If document exists, show image
            const sampleImageUrl = 'https://via.placeholder.com/250x180?text=Sample+Document';
            
            // Uncomment below to simulate documents being present
            // showDocumentImage('idProofImage', 'idProofPlaceholder', sampleImageUrl);
            // showDocumentImage('addressProofImage', 'addressProofPlaceholder', sampleImageUrl);
            // showDocumentImage('photoImage', 'photoPlaceholder', 'https://via.placeholder.com/250x180?text=Member+Photo');
            // showDocumentImage('signatureImage', 'signaturePlaceholder', 'https://via.placeholder.com/250x180?text=Signature');
            // showDocumentImage('profDocImage', 'profDocPlaceholder', sampleImageUrl);
            // showDocumentImage('bankDocImage', 'bankDocPlaceholder', sampleImageUrl);
        }

        // Helper to show document image
        function showDocumentImage(imgId, placeholderId, imageUrl) {
            const img = document.getElementById(imgId);
            const placeholder = document.getElementById(placeholderId);
            if (img && placeholder && imageUrl) {
                img.src = imageUrl;
                img.style.display = 'block';
                placeholder.style.display = 'none';
            }
        }

        // Update document status badges
        function updateDocumentStatuses() {
            updateStatusBadge('idProofStatus', currentMember.documents.idProof.status);
            updateStatusBadge('addressProofStatus', currentMember.documents.addressProof.status);
            updateStatusBadge('photoStatus', currentMember.documents.photo.status);
            updateStatusBadge('signatureStatus', currentMember.documents.signature.status);
            updateStatusBadge('profDocStatus', currentMember.documents.profDoc.status);
            updateStatusBadge('bankDocStatus', currentMember.documents.bankDoc.status);
        }

        function updateStatusBadge(elementId, status) {
            const element = document.getElementById(elementId);
            if (element) {
                element.textContent = status.charAt(0).toUpperCase() + status.slice(1);
                element.className = 'doc-status ' + status;
            }
        }

        // Zoom document function
        let currentDocType = '';
        let currentImageSrc = '';

        function zoomDocument(docTitle, imageElementId) {
            const imgElement = document.getElementById(imageElementId);
            currentDocType = docTitle;
            
            const modal = document.getElementById('zoomModal');
            const zoomTitle = document.getElementById('zoomTitle');
            const zoomImage = document.getElementById('zoomImage');
            
            zoomTitle.textContent = docTitle + ' - Document Preview';
            
            if (imgElement && imgElement.src && imgElement.style.display !== 'none') {
                zoomImage.src = imgElement.src;
            } else {
                // Show placeholder when no document
                zoomImage.src = '';
                zoomImage.alt = 'No document uploaded';
                zoomImage.style.opacity = '0.5';
            }
            
            modal.style.display = 'block';
        }

        // Close zoom modal
        function closeZoomModal() {
            document.getElementById('zoomModal').style.display = 'none';
        }

        // Approve current document from zoom
        function approveCurrentDoc() {
            if (currentDocType) {
                updateDocumentStatus(currentDocType, 'approved');
                closeZoomModal();
                alert(`${currentDocType} has been APPROVED`);
            }
        }

        // Reject current document from zoom
        function rejectCurrentDoc() {
            if (currentDocType) {
                updateDocumentStatus(currentDocType, 'rejected');
                closeZoomModal();
                alert(`${currentDocType} has been REJECTED`);
            }
        }

        // Update document status
        function updateDocumentStatus(docType, status) {
            let docKey = '';
            let statusElementId = '';
            
            switch(docType) {
                case 'ID Proof':
                    docKey = 'idProof';
                    statusElementId = 'idProofStatus';
                    break;
                case 'Address Proof':
                    docKey = 'addressProof';
                    statusElementId = 'addressProofStatus';
                    break;
                case 'Photo':
                    docKey = 'photo';
                    statusElementId = 'photoStatus';
                    break;
                case 'Signature':
                    docKey = 'signature';
                    statusElementId = 'signatureStatus';
                    break;
                case 'Prof. DOC':
                    docKey = 'profDoc';
                    statusElementId = 'profDocStatus';
                    break;
                case 'Bank Doc':
                    docKey = 'bankDoc';
                    statusElementId = 'bankDocStatus';
                    break;
            }
            
            if (docKey && currentMember.documents[docKey]) {
                currentMember.documents[docKey].status = status;
                updateStatusBadge(statusElementId, status);
            }
        }

        // Approve all documents
        function approveDocuments() {
            if (confirm('Approve ALL documents for this member?')) {
                const docTypes = ['idProof', 'addressProof', 'photo', 'signature', 'profDoc', 'bankDoc'];
                const statusElements = ['idProofStatus', 'addressProofStatus', 'photoStatus', 'signatureStatus', 'profDocStatus', 'bankDocStatus'];
                
                docTypes.forEach((doc, index) => {
                    if (currentMember.documents[doc]) {
                        currentMember.documents[doc].status = 'approved';
                        updateStatusBadge(statusElements[index], 'approved');
                    }
                });
                
                alert('All documents have been APPROVED successfully!');
            }
        }

        // Reject all documents
        function rejectDocuments() {
            if (confirm('Reject ALL documents for this member?')) {
                const docTypes = ['idProof', 'addressProof', 'photo', 'signature', 'profDoc', 'bankDoc'];
                const statusElements = ['idProofStatus', 'addressProofStatus', 'photoStatus', 'signatureStatus', 'profDocStatus', 'bankDocStatus'];
                
                docTypes.forEach((doc, index) => {
                    if (currentMember.documents[doc]) {
                        currentMember.documents[doc].status = 'rejected';
                        updateStatusBadge(statusElements[index], 'rejected');
                    }
                });
                
                alert('All documents have been REJECTED!');
            }
        }

        // Close modal when clicking outside
        window.onclick = function(event) {
            const modal = document.getElementById('zoomModal');
            if (event.target == modal) {
                modal.style.display = 'none';
            }
        }

        // Show Document Approval (call from navigation)
        function showDocApproval() {
            // Hide other content sections
            if (document.querySelectorAll('.content-section')) {
                document.querySelectorAll('.content-section').forEach(section => {
                    section.style.display = 'none';
                });
            }
            
            const docContainer = document.getElementById('docApprovalContainer');
            if (docContainer) {
                docContainer.style.display = 'block';
            }
            
            // Reset to default member
            document.getElementById('memberCode').value = '101';
            document.getElementById('memberName').value = '';
            
            // Optionally auto-search
            // searchMember();
        }

        // Credit Score Module Functions

        // Global variables
        let otpSent = false;
        let verifiedOTP = false;
        let currentName = '';
        let currentMobile = '';
        let currentPAN = '';
        let currentDOB = '';

        // Send OTP
        function sendOTP() {
            const name = document.getElementById('fullName').value.trim();
            const mobile = document.getElementById('mobileNumber').value.trim();
            const pan = document.getElementById('panNumber').value.trim().toUpperCase();
            const dob = document.getElementById('dob').value;
            
            // Validation
            if (!name) {
                alert('Please enter full name');
                document.getElementById('fullName').focus();
                return;
            }
            
            if (!mobile) {
                alert('Please enter mobile number');
                document.getElementById('mobileNumber').focus();
                return;
            }
            
            if (mobile.length !== 10) {
                alert('Mobile number must be 10 digits');
                return;
            }
            
            if (!/^[6-9]\d{9}$/.test(mobile)) {
                alert('Please enter a valid 10-digit mobile number starting with 6,7,8, or 9');
                return;
            }
            
            if (!pan) {
                alert('Please enter PAN number');
                document.getElementById('panNumber').focus();
                return;
            }
            
            if (pan.length !== 10) {
                alert('PAN number must be 10 characters');
                return;
            }
            
            const panRegex = /^[A-Z]{5}[0-9]{4}[A-Z]{1}$/;
            if (!panRegex.test(pan)) {
                alert('Please enter a valid PAN number (e.g., ABCDE1234F)');
                return;
            }
            
            if (!dob) {
                alert('Please select Date of Birth');
                return;
            }
            
            // Check wallet balance
            const walletBalance = parseFloat(document.getElementById('walletBalance').innerText);
            const cibilCharges = parseFloat(document.getElementById('cibilCharges').innerText);
            
            if (walletBalance < cibilCharges) {
                alert(`Insufficient wallet balance! Required: ₹${cibilCharges}, Available: ₹${walletBalance}`);
                return;
            }
            
            // Store for verification
            currentName = name;
            currentMobile = mobile;
            currentPAN = pan;
            currentDOB = dob;
            
            // Show loading
            showLoading(true);
            
            // Simulate API call to send OTP
            setTimeout(() => {
                showLoading(false);
                
                // Mock OTP (in real system, OTP would be sent via SMS)
                const mockOTP = Math.floor(100000 + Math.random() * 900000);
                console.log('Mock OTP:', mockOTP);
                
                alert(`✅ OTP sent to ${mobile}\n📱 Demo OTP: ${mockOTP}\n\n(This is a demo. In production, OTP will be sent via SMS.)`);
                otpSent = true;
                
                // Auto-fill OTP for demo (remove in production)
                document.getElementById('otp').value = mockOTP;
                
            }, 1500);
        }

        // Verify OTP
        function verifyOTP() {
            if (!otpSent) {
                alert('Please send OTP first');
                return;
            }
            
            const enteredOTP = document.getElementById('otp').value.trim();
            
            if (!enteredOTP) {
                alert('Please enter OTP');
                return;
            }
            
            showLoading(true);
            
            // Simulate OTP verification
            setTimeout(() => {
                showLoading(false);
                
                // For demo, accept any 6-digit OTP
                if (enteredOTP.length === 6 && /^\d+$/.test(enteredOTP)) {
                    verifiedOTP = true;
                    alert('✅ OTP verified successfully! You can now generate CIBIL report.');
                } else {
                    alert('❌ Invalid OTP. Please try again.');
                    verifiedOTP = false;
                }
            }, 1000);
        }

        // Generate CIBIL Report
        function generateCIBIL() {
            if (!otpSent) {
                alert('Please send OTP first');
                return;
            }
            
            if (!verifiedOTP) {
                alert('Please verify OTP first');
                return;
            }
            
            const walletBalanceElem = document.getElementById('walletBalance');
            const cibilCharges = parseFloat(document.getElementById('cibilCharges').innerText);
            let walletBalance = parseFloat(walletBalanceElem.innerText);
            
            if (walletBalance < cibilCharges) {
                alert(`Insufficient wallet balance! Required: ₹${cibilCharges}, Available: ₹${walletBalance}`);
                return;
            }
            
            showLoading(true);
            
            // Simulate CIBIL generation
            setTimeout(() => {
                // Deduct charges from wallet
                walletBalance = walletBalance - cibilCharges;
                walletBalanceElem.innerText = walletBalance.toFixed(2);
                
                showLoading(false);
                
                // Generate random credit score
                const creditScore = Math.floor(300 + Math.random() * 600);
                let scoreStatus = '';
                let statusColor = '';
                
                if (creditScore >= 750) {
                    scoreStatus = 'Excellent';
                    statusColor = '#28a745';
                } else if (creditScore >= 650) {
                    scoreStatus = 'Good';
                    statusColor = '#17a2b8';
                } else if (creditScore >= 550) {
                    scoreStatus = 'Average';
                    statusColor = '#ffc107';
                } else {
                    scoreStatus = 'Poor';
                    statusColor = '#dc3545';
                }
                
                // Show detailed result
                alert(`✅ CIBIL Report Generated Successfully!\n\n━━━━━━━━━━━━━━━━━━━━━\n📊 Name: ${currentName}\n📱 Mobile: ${currentMobile}\n🆔 PAN: ${currentPAN}\n━━━━━━━━━━━━━━━━━━━━━\n🏦 Credit Score: ${creditScore}\n📈 Status: ${scoreStatus}\n━━━━━━━━━━━━━━━━━━━━━\n💰 Charges Deducted: ₹${cibilCharges}\n💳 Remaining Balance: ₹${walletBalance.toFixed(2)}\n━━━━━━━━━━━━━━━━━━━━━\n📄 Report will be available for download.`);
                
                // Add to last 6 months records
                addToRecords(currentName, currentPAN);
                
                // Reset OTP state
                otpSent = false;
                verifiedOTP = false;
                document.getElementById('otp').value = '';
                
                // Clear sensitive data
                currentMobile = '';
                currentPAN = '';
                currentDOB = '';
                
            }, 2500);
        }

        // Add new record to the table
        function addToRecords(name, pan) {
            const tbody = document.getElementById('recordsTableBody');
            const now = new Date();
            const formattedDate = `${now.getMonth()+1}/${now.getDate()}/${now.getFullYear()} ${now.getHours().toString().padStart(2,'0')}:${now.getMinutes().toString().padStart(2,'0')}:${now.getSeconds().toString().padStart(2,'0')}`;
            
            // Format display name
            const displayName = `${name} [${pan}]`;
            const truncatedName = displayName.length > 35 ? displayName.substring(0, 32) + '...' : displayName;
            
            const newRow = document.createElement('tr');
            newRow.innerHTML = `
                <td>${formattedDate}</td>
                <td>${truncatedName}</td>
                <td><button class="download-btn" onclick="downloadReport(this)"><i class="bi bi-download"></i> Download</button></td>
            `;
            
            // Add at the top
            if (tbody.firstChild) {
                tbody.insertBefore(newRow, tbody.firstChild);
            } else {
                tbody.appendChild(newRow);
            }
            
            // Keep only last 6 records
            while (tbody.children.length > 6) {
                tbody.removeChild(tbody.lastChild);
            }
        }

        // Download report
        function downloadReport(button) {
            const row = button.closest('tr');
            const fileName = row.cells[1].innerText;
            const dateTime = row.cells[0].innerText;
            
            alert(`📥 Downloading report for:\n📄 ${fileName}\n📅 Date: ${dateTime}\n\n(Simulated download - PDF would be generated in production)`);
            
            // In real system, this would trigger file download
            // window.location.href = `/api/download-report?file=${encodeURIComponent(fileName)}`;
        }

        // Update wallet balance (call this when needed)
        function updateWalletBalance(newBalance) {
            const walletElem = document.getElementById('walletBalance');
            if (walletElem) {
                walletElem.innerText = newBalance.toFixed(2);
            }
        }

        // Show/hide loading modal
        function showLoading(show) {
            const modal = document.getElementById('loadingModal');
            if (modal) {
                modal.style.display = show ? 'flex' : 'none';
            }
        }

        // Add event listeners for real-time validation
        document.addEventListener('DOMContentLoaded', function() {
            const mobileInput = document.getElementById('mobileNumber');
            const panInput = document.getElementById('panNumber');
            const nameInput = document.getElementById('fullName');
            
            if (mobileInput) {
                mobileInput.addEventListener('input', function(e) {
                    this.value = this.value.replace(/[^0-9]/g, '').slice(0, 10);
                });
            }
            
            if (panInput) {
                panInput.addEventListener('input', function(e) {
                    this.value = this.value.toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 10);
                });
            }
            
            if (nameInput) {
                nameInput.addEventListener('input', function(e) {
                    this.value = this.value.toUpperCase().replace(/[^A-Z\s]/g, '');
                });
            }
        });

        // Show Credit Score Module (call from navigation)
        function showCreditScore() {
            // Hide other content sections
            if (document.querySelectorAll('.content-section')) {
                document.querySelectorAll('.content-section').forEach(section => {
                    section.style.display = 'none';
                });
            }
            
            const creditContainer = document.getElementById('creditScoreContainer');
            if (creditContainer) {
                creditContainer.style.display = 'block';
            }
            
            // Reset form
            otpSent = false;
            verifiedOTP = false;
            document.getElementById('fullName').value = '';
            document.getElementById('mobileNumber').value = '';
            document.getElementById('panNumber').value = '';
            document.getElementById('dob').value = '';
            document.getElementById('otp').value = '';
        }

        // CKYC Generate Module Functions

        // CKYC Generate Module Functions

        // Sample data for the table with Date of Join, Member Code, Member Name
        let ckycRecords = [
            { 
                dateOfJoin: '2024-01-15', 
                memberCode: 'M001', 
                memberName: 'RAHUL KUMAR VERMA',
                ipPhoto: 'YES', 
                signature: 'YES', 
                doc: 'YES', 
                genOrNot: 'Pending', 
                selected: false 
            },
            { 
                dateOfJoin: '2024-02-20', 
                memberCode: 'M002', 
                memberName: 'PRIYA SHARMA',
                ipPhoto: 'NO', 
                signature: 'YES', 
                doc: 'YES', 
                genOrNot: 'Generated', 
                selected: false 
            },
            { 
                dateOfJoin: '2024-03-10', 
                memberCode: 'M003', 
                memberName: 'AMIT PATEL',
                ipPhoto: 'YES', 
                signature: 'NO', 
                doc: 'YES', 
                genOrNot: 'Pending', 
                selected: false 
            },
            { 
                dateOfJoin: '2024-04-05', 
                memberCode: 'M004', 
                memberName: 'SUNITA SINGH',
                ipPhoto: 'YES', 
                signature: 'YES', 
                doc: 'YES', 
                genOrNot: 'Pending', 
                selected: false 
            },
            { 
                dateOfJoin: '2024-05-12', 
                memberCode: 'M005', 
                memberName: 'VIKAS GUPTA',
                ipPhoto: 'NO', 
                signature: 'NO', 
                doc: 'YES', 
                genOrNot: 'Generated', 
                selected: false 
            },
            { 
                dateOfJoin: '2024-06-18', 
                memberCode: 'M006', 
                memberName: 'NEHA VERMA',
                ipPhoto: 'YES', 
                signature: 'YES', 
                doc: 'NO', 
                genOrNot: 'Pending', 
                selected: false 
            }
        ];

        // Load table on page load
        function loadCkycTable() {
            const tbody = document.getElementById('ckycTableBody');
            if (!tbody) return;
            
            tbody.innerHTML = '';
            
            ckycRecords.forEach((record, index) => {
                const row = tbody.insertRow();
                
                // Checkbox cell
                const cellCheckbox = row.insertCell(0);
                const checkbox = document.createElement('input');
                checkbox.type = 'checkbox';
                checkbox.className = 'row-checkbox';
                checkbox.dataset.index = index;
                checkbox.checked = record.selected;
                checkbox.onchange = function() { toggleRowSelection(index, this.checked); };
                cellCheckbox.appendChild(checkbox);
                
                // Date of Join cell
                const cellDoj = row.insertCell(1);
                cellDoj.innerHTML = record.dateOfJoin;
                
                // Member Code cell
                const cellMemberCode = row.insertCell(2);
                cellMemberCode.innerHTML = record.memberCode;
                
                // Member Name cell
                const cellMemberName = row.insertCell(3);
                cellMemberName.innerHTML = record.memberName;
                
                // IP Photo cell
                const cellIpPhoto = row.insertCell(4);
                cellIpPhoto.innerHTML = `<span class="status-badge status-${record.ipPhoto === 'YES' ? 'yes' : 'no'}">${record.ipPhoto}</span>`;
                
                // Signature cell
                const cellSignature = row.insertCell(5);
                cellSignature.innerHTML = `<span class="status-badge status-${record.signature === 'YES' ? 'yes' : 'no'}">${record.signature}</span>`;
                
                // Doc cell
                const cellDoc = row.insertCell(6);
                cellDoc.innerHTML = `<span class="status-badge status-${record.doc === 'YES' ? 'yes' : 'no'}">${record.doc}</span>`;
                
                // GenOrNot cell
                const cellGen = row.insertCell(7);
                const genStatus = record.genOrNot === 'Generated' ? 'yes' : 'pending';
                cellGen.innerHTML = `<span class="status-badge status-${genStatus}">${record.genOrNot}</span>`;
                
                // Selection cell
                const cellSelection = row.insertCell(8);
                const selectBtn = document.createElement('button');
                selectBtn.innerHTML = '<i class="bi bi-check-square"></i> Select';
                selectBtn.className = 'select-row-btn';
                selectBtn.onclick = function() { selectRow(index); };
                cellSelection.appendChild(selectBtn);
            });
            
            updateSelectAllCheckboxes();
        }

        // Toggle Search Section
        function toggleSearchSection() {
            const searchContent = document.getElementById('searchContent');
            const toggleIcon = document.getElementById('searchToggleIcon');
            
            if (searchContent.classList.contains('hide')) {
                searchContent.classList.remove('hide');
                toggleIcon.classList.remove('bi-chevron-down');
                toggleIcon.classList.add('bi-chevron-up');
            } else {
                searchContent.classList.add('hide');
                toggleIcon.classList.remove('bi-chevron-up');
                toggleIcon.classList.add('bi-chevron-down');
            }
        }

        // Toggle row selection
        function toggleRowSelection(index, isChecked) {
            ckycRecords[index].selected = isChecked;
            updateSelectAllCheckboxes();
        }

        // Toggle Select All Pending (only selects records with GenOrNot = 'Pending')
        function toggleSelectAllPending() {
            const checkbox = document.getElementById('selectAllPendingCheckbox');
            const isChecked = checkbox.checked;
            
            ckycRecords.forEach((record, index) => {
                if (record.genOrNot === 'Pending') {
                    record.selected = isChecked;
                }
            });
            
            // Update all row checkboxes
            const rowCheckboxes = document.querySelectorAll('.row-checkbox');
            rowCheckboxes.forEach((checkbox, idx) => {
                if (ckycRecords[idx].genOrNot === 'Pending') {
                    checkbox.checked = isChecked;
                }
            });
            
            updateSelectAllCheckboxes();
        }

        // Toggle Select All (selects all records)
        function toggleSelectAll() {
            const checkbox = document.getElementById('selectAllCheckbox');
            const isChecked = checkbox.checked;
            
            ckycRecords.forEach((record, index) => {
                record.selected = isChecked;
            });
            
            // Update all row checkboxes
            const rowCheckboxes = document.querySelectorAll('.row-checkbox');
            rowCheckboxes.forEach(checkbox => {
                checkbox.checked = isChecked;
            });
            
            updateSelectAllCheckboxes();
        }

        // Toggle Select All from header
        function toggleSelectAllFromHeader() {
            const headerCheckbox = document.getElementById('headerSelectAll');
            const isChecked = headerCheckbox.checked;
            
            ckycRecords.forEach((record, index) => {
                record.selected = isChecked;
            });
            
            // Update all row checkboxes
            const rowCheckboxes = document.querySelectorAll('.row-checkbox');
            rowCheckboxes.forEach(checkbox => {
                checkbox.checked = isChecked;
            });
            
            updateSelectAllCheckboxes();
        }

        // Update Select All checkboxes state
        function updateSelectAllCheckboxes() {
            const selectAllCheckbox = document.getElementById('selectAllCheckbox');
            const selectAllPendingCheckbox = document.getElementById('selectAllPendingCheckbox');
            const headerSelectAll = document.getElementById('headerSelectAll');
            
            const allSelected = ckycRecords.every(record => record.selected === true);
            const anySelected = ckycRecords.some(record => record.selected === true);
            
            // Pending records check
            const pendingRecords = ckycRecords.filter(record => record.genOrNot === 'Pending');
            const allPendingSelected = pendingRecords.length > 0 && pendingRecords.every(record => record.selected === true);
            const anyPendingSelected = pendingRecords.some(record => record.selected === true);
            
            if (selectAllCheckbox) {
                selectAllCheckbox.checked = allSelected;
                selectAllCheckbox.indeterminate = anySelected && !allSelected;
            }
            
            if (selectAllPendingCheckbox) {
                selectAllPendingCheckbox.checked = allPendingSelected;
                selectAllPendingCheckbox.indeterminate = anyPendingSelected && !allPendingSelected;
            }
            
            if (headerSelectAll) {
                headerSelectAll.checked = allSelected;
                headerSelectAll.indeterminate = anySelected && !allSelected;
            }
        }

        // Select individual row
        function selectRow(index) {
            ckycRecords[index].selected = true;
            const checkbox = document.querySelector(`.row-checkbox[data-index="${index}"]`);
            if (checkbox) checkbox.checked = true;
            updateSelectAllCheckboxes();
            alert(`Row ${index + 1} selected for generation`);
        }

        // Browse folder
        function browseFolder() {
            const folderPath = prompt('Enter output folder path:', 'C:\\CKYC_Output\\');
            if (folderPath) {
                document.getElementById('outputFolder').value = folderPath;
            }
        }

        // Confirm and Generate
        function confirmAndGenerate() {
            const outputFolder = document.getElementById('outputFolder').value.trim();
            const headerBranch = document.getElementById('headerBranch').value;
            const flCode = document.getElementById('flCode').value;
            const batchNo = document.getElementById('batchNo').value;
            const userId = document.getElementById('userId').value;
            const fromDate = document.getElementById('fromDate').value;
            const toDate = document.getElementById('toDate').value;
            const branch = document.getElementById('branch').value;
            
            // Validate output folder
            if (!outputFolder) {
                alert('Please select output folder');
                return;
            }
            
            // Check for spaces or special characters in folder name
            if (/[\s!@#$%^&*()+=<>?:"|]/.test(outputFolder)) {
                alert('Output folder name should not contain any space or special characters');
                return;
            }
            
            // Get selected records
            const selectedRecords = ckycRecords.filter((record) => record.selected);
            
            if (selectedRecords.length === 0) {
                alert('Please select at least one record to generate');
                return;
            }
            
            // Update timestamp
            const now = new Date();
            const timestamp = `${now.getDate().toString().padStart(2,'0')}${(now.getMonth()+1).toString().padStart(2,'0')}${now.getFullYear()}${now.getHours().toString().padStart(2,'0')}${now.getMinutes().toString().padStart(2,'0')}${now.getSeconds().toString().padStart(2,'0')}`;
            document.getElementById('timestamp').value = timestamp;
            
            // Show confirmation
            const confirmMsg = `📁 CKYC Generation\n\n` +
                `Branch: ${branch}\n` +
                `Header Branch: ${headerBranch}\n` +
                `Date Range: ${fromDate} to ${toDate}\n` +
                `FL Code: ${flCode}\n` +
                `Batch No: ${batchNo || 'N/A'}\n` +
                `UserID: ${userId || 'N/A'}\n` +
                `Output Folder: ${outputFolder}\n` +
                `Records Selected: ${selectedRecords.length}\n\n` +
                `Proceed with generation?`;
            
            if (confirm(confirmMsg)) {
                showCkycLoading(true);
                
                setTimeout(() => {
                    showCkycLoading(false);
                    
                    // Update GenOrNot status for selected records
                    selectedRecords.forEach(record => {
                        record.genOrNot = 'Generated';
                    });
                    
                    // Reload table
                    loadCkycTable();
                    
                    alert(`✅ CKYC Generation Completed!\n\n` +
                        `Generated ${selectedRecords.length} records\n` +
                        `Output saved to: ${outputFolder}\n` +
                        `Timestamp: ${timestamp}`);
                    
                    // Reset selections
                    ckycRecords.forEach(record => {
                        record.selected = false;
                    });
                    loadCkycTable();
                    
                }, 2000);
            }
        }

        // Show loading
        function showCkycLoading(show) {
            const modal = document.getElementById('ckycLoadingModal');
            if (modal) {
                modal.style.display = show ? 'flex' : 'none';
            }
        }

        // Sync branch from search to header
        function syncBranch() {
            const searchBranch = document.getElementById('branch');
            const headerBranch = document.getElementById('headerBranch');
            if (searchBranch && headerBranch) {
                headerBranch.value = searchBranch.value;
            }
        }

        // Show CKYC Generate module
        function showCkycGenerate() {
            if (document.querySelectorAll('.content-section')) {
                document.querySelectorAll('.content-section').forEach(section => {
                    section.style.display = 'none';
                });
            }
            
            const ckycContainer = document.getElementById('ckycGenerateContainer');
            if (ckycContainer) {
                ckycContainer.style.display = 'block';
            }
            
            loadCkycTable();
        }

        // Event listeners
        document.addEventListener('DOMContentLoaded', function() {
            loadCkycTable();
            
            // Sync branch when changed
            const branchSelect = document.getElementById('branch');
            if (branchSelect) {
                branchSelect.addEventListener('change', syncBranch);
            }
        });


        // Member Synopsis Functions

        // Sample member data
        let currentMemberData = null;

        // Mock member database
        const membersDatabase = {
            '1001': {
                memberCode: '1001',
                memberName: 'RAHUL KUMAR VERMA',
                fatherName: 'RAMESH KUMAR VERMA',
                dateOfJoin: '2024-01-15',
                address: '123, Main Street, Near Temple, New Delhi - 110001',
                pinCode: '110001',
                dob: '1990-05-15',
                nomineeName: 'SITA VERMA',
                nomineeRelation: 'Wife',
                phoneNo: '9876543210',
                identityProof: 'Aadhar Card - XXXX-XXXX-1234',
                branch: 'HEAD OFFICE - 001',
                age: 35
            },
            '1002': {
                memberCode: '1002',
                memberName: 'PRIYA SHARMA',
                fatherName: 'RAJESH SHARMA',
                dateOfJoin: '2024-02-20',
                address: '456, Park Avenue, South Extension, New Delhi - 110049',
                pinCode: '110049',
                dob: '1988-08-22',
                nomineeName: 'AMIT SHARMA',
                nomineeRelation: 'Husband',
                phoneNo: '9876543211',
                identityProof: 'PAN Card - ABCDE1234F',
                branch: 'BRANCH - 002',
                age: 37
            }
        };

        // Search member
        function searchMemberDetails() {
            const memberCode = document.getElementById('memberCodeSearch').value.trim();
            
            if (!memberCode) {
                alert('Please enter Member Code');
                return;
            }
            
            const member = membersDatabase[memberCode];
            
            if (!member) {
                alert(`Member with code ${memberCode} not found`);
                return;
            }
            
            currentMemberData = member;
            
            // Update display fields
            document.getElementById('displayMemberCode').innerText = member.memberCode;
            document.getElementById('displayMemberName').innerText = member.memberName;
            document.getElementById('displayFatherName').innerText = member.fatherName;
            document.getElementById('displayDateOfJoin').innerText = member.dateOfJoin;
            document.getElementById('displayAddress').innerText = member.address;
            document.getElementById('displayPinCode').innerText = member.pinCode;
            document.getElementById('displayDob').innerText = member.dob;
            document.getElementById('displayNomineeName').innerText = member.nomineeName;
            document.getElementById('displayNomineeRelation').innerText = member.nomineeRelation;
            document.getElementById('displayPhoneNo').innerText = member.phoneNo;
            document.getElementById('displayIdentityProof').innerText = member.identityProof;
            document.getElementById('displayBranch').innerText = member.branch;
            
            // Calculate and set age
            const age = calculateAgeFromDOB(member.dob);
            document.getElementById('age').value = age;
            
            // Show success message
            alert(`✅ Member found: ${member.memberName}`);
        }

        // Calculate age from DOB
        function calculateAgeFromDOB(dob) {
            if (!dob) return '';
            const birthDate = new Date(dob);
            const today = new Date();
            let age = today.getFullYear() - birthDate.getFullYear();
            const monthDiff = today.getMonth() - birthDate.getMonth();
            if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
                age--;
            }
            return age;
        }

        // Save loan details
        function saveLoanDetails() {
            if (!currentMemberData) {
                alert('Please search and select a member first');
                return;
            }
            
            const loanData = {
                memberCode: currentMemberData.memberCode,
                memberName: currentMemberData.memberName,
                personalRecurringDeposits: document.getElementById('personalRecurringDeposits').value || 0,
                personalLoanAmount: document.getElementById('personalLoanAmount').value || 0,
                personalTenure: document.getElementById('personalTenure').value || 0,
                groupLongTermDeposits: document.getElementById('groupLongTermDeposits').value || 0,
                groupLoanAmount: document.getElementById('groupLoanAmount').value || 0,
                groupTenure: document.getElementById('groupTenure').value || 0,
                age: document.getElementById('age').value,
                nAge: document.getElementById('nAge').value || ''
            };
            
            console.log('Loan Details Saved:', loanData);
            
            // Save to localStorage for demo
            localStorage.setItem(`loan_${currentMemberData.memberCode}`, JSON.stringify(loanData));
            
            alert(`✅ Loan details saved for ${currentMemberData.memberName}`);
        }

        // Calculate loan eligibility
        function calculateLoanEligibility() {
            if (!currentMemberData) {
                alert('Please search and select a member first');
                return;
            }
            
            const age = parseInt(document.getElementById('age').value) || 0;
            const personalDeposits = parseInt(document.getElementById('personalRecurringDeposits').value) || 0;
            const groupDeposits = parseInt(document.getElementById('groupLongTermDeposits').value) || 0;
            
            // Simple eligibility calculation
            let personalEligibility = 0;
            let groupEligibility = 0;
            let totalEligibility = 0;
            
            if (age >= 21 && age <= 60) {
                personalEligibility = personalDeposits * 50;
                groupEligibility = groupDeposits * 100;
                totalEligibility = personalEligibility + groupEligibility;
            } else if (age > 60) {
                personalEligibility = personalDeposits * 30;
                groupEligibility = groupDeposits * 60;
                totalEligibility = personalEligibility + groupEligibility;
            } else {
                alert('Member age must be at least 21 years for loan eligibility');
                return;
            }
            
            alert(`🏦 LOAN ELIGIBILITY CALCULATION\n\n` +
                `Member: ${currentMemberData.memberName}\n` +
                `Age: ${age} years\n` +
                `━━━━━━━━━━━━━━━━━━━━━\n` +
                `Personal Loan Eligibility: ₹${personalEligibility.toLocaleString()}\n` +
                `Group Loan Eligibility: ₹${groupEligibility.toLocaleString()}\n` +
                `━━━━━━━━━━━━━━━━━━━━━\n` +
                `Total Eligibility: ₹${totalEligibility.toLocaleString()}\n\n` +
                `Note: This is an approximate calculation based on deposits.`);
        }

        // Load saved loan data if exists
        function loadSavedLoanData() {
            if (currentMemberData) {
                const savedData = localStorage.getItem(`loan_${currentMemberData.memberCode}`);
                if (savedData) {
                    const data = JSON.parse(savedData);
                    document.getElementById('personalRecurringDeposits').value = data.personalRecurringDeposits;
                    document.getElementById('personalLoanAmount').value = data.personalLoanAmount;
                    document.getElementById('personalTenure').value = data.personalTenure;
                    document.getElementById('groupLongTermDeposits').value = data.groupLongTermDeposits;
                    document.getElementById('groupLoanAmount').value = data.groupLoanAmount;
                    document.getElementById('groupTenure').value = data.groupTenure;
                    document.getElementById('nAge').value = data.nAge;
                }
            }
        }

        // Show Member Loan Module
        function showMemberLoan() {
            if (document.querySelectorAll('.content-section')) {
                document.querySelectorAll('.content-section').forEach(section => {
                    section.style.display = 'none';
                });
            }
            
            const memberLoanContainer = document.getElementById('memberLoanContainer');
            if (memberLoanContainer) {
                memberLoanContainer.style.display = 'block';
            }
        }


        // Member Details Report Functions

        // Sample member report data
        let memberReportData = [
            {
                slNo: 1,
                memberNo: 'MA000096',
                memberName: 'NALP DUTTA',
                doj: '26/03/2026',
                age: 55,
                father: 'LT SUNIL KUMAR DUTTA',
                address: 'NEPLAR MATH, IRAT, HOOHOLY, WEST BENGAL-7',
                pin: '712501',
                pan: 'AORPD670H',
                branch: 'HEAD OFFICE - 001'
            },
            {
                slNo: 2,
                memberNo: 'MA000097',
                memberName: 'RAHUL VERMA',
                doj: '15/01/2026',
                age: 35,
                father: 'RAMESH VERMA',
                address: '123, MAIN STREET, NEW DELHI',
                pin: '110001',
                pan: 'ABCDE1234F',
                branch: 'HEAD OFFICE - 001'
            },
            {
                slNo: 3,
                memberNo: 'MA000098',
                memberName: 'PRIYA SHARMA',
                doj: '20/02/2026',
                age: 32,
                father: 'RAJESH SHARMA',
                address: '456, PARK AVENUE, SOUTH EXTENSION',
                pin: '110049',
                pan: 'XYZAB5678G',
                branch: 'BRANCH - 002'
            },
            {
                slNo: 4,
                memberNo: 'MA000099',
                memberName: 'AMIT PATEL',
                doj: '10/03/2026',
                age: 40,
                father: 'SURESH PATEL',
                address: '789, SECTOR 15, NOIDA',
                pin: '201301',
                pan: 'PATEL1234H',
                branch: 'BRANCH - 003'
            },
            {
                slNo: 5,
                memberNo: 'MA000100',
                memberName: 'SUNITA SINGH',
                doj: '05/04/2026',
                age: 28,
                father: 'MANOJ SINGH',
                address: '321, LAJPAT NAGAR, LUCKNOW',
                pin: '226001',
                pan: 'SINGH5678I',
                branch: 'HEAD OFFICE - 001'
            }
        ];

        // Load member report table
        function loadMemberReportTable(data) {
            const tbody = document.getElementById('memberReportTableBody');
            if (!tbody) return;
            
            if (!data || data.length === 0) {
                tbody.innerHTML = '<tr><td colspan="10" style="text-align:center">No records found</td></tr>';
                return;
            }
            
            tbody.innerHTML = '';
            
            data.forEach((record) => {
                const row = tbody.insertRow();
                row.insertCell(0).innerHTML = record.slNo;
                row.insertCell(1).innerHTML = record.memberNo;
                row.insertCell(2).innerHTML = record.memberName;
                row.insertCell(3).innerHTML = record.doj;
                row.insertCell(4).innerHTML = record.age;
                row.insertCell(5).innerHTML = record.father;
                row.insertCell(6).innerHTML = record.address;
                row.insertCell(7).innerHTML = record.pin;
                row.insertCell(8).innerHTML = record.pan;
                row.insertCell(9).innerHTML = record.branch;
            });
        }

        // Show member report based on filters
        function showMemberReport() {
            const branch = document.getElementById('reportBranch').value;
            const fromDate = document.getElementById('reportDate').value;
            const toDate = document.getElementById('reportToDate').value;
            
            let filteredData = [...memberReportData];
            
            // Filter by branch
            if (branch !== 'HEAD OFFICE - 001' || branch !== 'all') {
                filteredData = filteredData.filter(record => record.branch === branch);
            }
            
            // Filter by date range (convert dd/mm/yyyy to compare)
            if (fromDate && toDate) {
                const fromDateObj = new Date(fromDate);
                const toDateObj = new Date(toDate);
                
                filteredData = filteredData.filter(record => {
                    const [day, month, year] = record.doj.split('/');
                    const recordDate = new Date(`${year}-${month}-${day}`);
                    return recordDate >= fromDateObj && recordDate <= toDateObj;
                });
            }
            
            // Reset SL NO
            filteredData.forEach((record, index) => {
                record.slNo = index + 1;
            });
            
            loadMemberReportTable(filteredData);
            
            alert(`Showing ${filteredData.length} member records`);
        }

        // Close/Reset member report
        function closeMemberReport() {
            // Reset filters to default
            document.getElementById('reportBranch').value = 'HEAD OFFICE - 001';
            document.getElementById('reportDate').value = '2026-04-02';
            document.getElementById('reportToDate').value = '2026-04-02';
            
            // Reload all data
            memberReportData.forEach((record, index) => {
                record.slNo = index + 1;
            });
            loadMemberReportTable(memberReportData);
            
            alert('Report closed. Filters reset.');
        }

        // Show Member Details Report module
        function showMemberDetailsReport() {
            if (document.querySelectorAll('.content-section')) {
                document.querySelectorAll('.content-section').forEach(section => {
                    section.style.display = 'none';
                });
            }
            
            const reportContainer = document.getElementById('memberDetailsReportContainer');
            if (reportContainer) {
                reportContainer.style.display = 'block';
            }
            
            // Load initial data
            memberReportData.forEach((record, index) => {
                record.slNo = index + 1;
            });
            loadMemberReportTable(memberReportData);
        }

        // Member Search Functions

        // Sample member search data
        let memberSearchData = [
            {
                slNo: 1,
                memberCode: 'MA000096',
                memberName: 'NALP DUTTA',
                gender: 'Male',
                doj: '26/03/2026',
                memberType: 'Regular',
                panNo: 'AORPD670H',
                phoneNo: '9876543210',
                nominee: 'SUNIL DUTTA',
                branch: 'HEAD OFFICE - 001',
                status: 'Active',
                selected: false
            },
            {
                slNo: 2,
                memberCode: 'MA000097',
                memberName: 'RAHUL VERMA',
                gender: 'Male',
                doj: '15/01/2026',
                memberType: 'Regular',
                panNo: 'ABCDE1234F',
                phoneNo: '9876543211',
                nominee: 'RAMESH VERMA',
                branch: 'HEAD OFFICE - 001',
                status: 'Active',
                selected: false
            },
            {
                slNo: 3,
                memberCode: 'MA000098',
                memberName: 'PRIYA SHARMA',
                gender: 'Female',
                doj: '20/02/2026',
                memberType: 'Premium',
                panNo: 'XYZAB5678G',
                phoneNo: '9876543212',
                nominee: 'RAJESH SHARMA',
                branch: 'BRANCH - 002',
                status: 'Active',
                selected: false
            },
            {
                slNo: 4,
                memberCode: 'MA000099',
                memberName: 'AMIT PATEL',
                gender: 'Male',
                doj: '10/03/2026',
                memberType: 'Regular',
                panNo: 'PATEL1234H',
                phoneNo: '9876543213',
                nominee: 'SURESH PATEL',
                branch: 'BRANCH - 003',
                status: 'Inactive',
                selected: false
            },
            {
                slNo: 5,
                memberCode: 'MA000100',
                memberName: 'SUNITA SINGH',
                gender: 'Female',
                doj: '05/04/2026',
                memberType: 'Premium',
                panNo: 'SINGH5678I',
                phoneNo: '9876543214',
                nominee: 'MANOJ SINGH',
                branch: 'HEAD OFFICE - 001',
                status: 'Active',
                selected: false
            },
            {
                slNo: 6,
                memberCode: 'MA000101',
                memberName: 'VIKAS GUPTA',
                gender: 'Male',
                doj: '12/05/2026',
                memberType: 'Regular',
                panNo: 'GUPTA9012J',
                phoneNo: '9876543215',
                nominee: 'RAJ GUPTA',
                branch: 'BRANCH - 002',
                status: 'Active',
                selected: false
            }
        ];

        let currentSearchResults = [];

        // Load member search table
        function loadMemberSearchTable(data) {
            const tbody = document.getElementById('memberSearchTableBody');
            if (!tbody) return;
            
            if (!data || data.length === 0) {
                tbody.innerHTML = '<tr><td colspan="12" style="text-align:center">No records found</td></tr>';
                return;
            }
            
            tbody.innerHTML = '';
            
            data.forEach((record, index) => {
                const row = tbody.insertRow();
                row.dataset.index = index;
                row.dataset.memberCode = record.memberCode;
                row.onclick = function(e) {
                    if (e.target.type !== 'checkbox') {
                        selectSearchRow(index);
                    }
                };
                
                // Checkbox cell
                const cellCheckbox = row.insertCell(0);
                const checkbox = document.createElement('input');
                checkbox.type = 'checkbox';
                checkbox.className = 'row-search-checkbox';
                checkbox.dataset.index = index;
                checkbox.checked = record.selected || false;
                checkbox.onclick = function(e) {
                    e.stopPropagation();
                    toggleSearchRowSelection(index, this.checked);
                };
                cellCheckbox.appendChild(checkbox);
                
                // Data cells
                row.insertCell(1).innerHTML = record.slNo;
                row.insertCell(2).innerHTML = record.memberCode;
                row.insertCell(3).innerHTML = record.memberName;
                row.insertCell(4).innerHTML = record.gender;
                row.insertCell(5).innerHTML = record.doj;
                row.insertCell(6).innerHTML = record.memberType;
                row.insertCell(7).innerHTML = record.panNo;
                row.insertCell(8).innerHTML = record.phoneNo;
                row.insertCell(9).innerHTML = record.nominee;
                row.insertCell(10).innerHTML = record.branch;
                row.insertCell(11).innerHTML = `<span class="status-${record.status.toLowerCase()}">${record.status}</span>`;
                
                // Highlight if selected
                if (record.selected) {
                    row.classList.add('selected');
                }
            });
            
            updateSelectAllSearchCheckbox();
        }

        // Perform search
        function performSearch() {
            const searchBy = document.getElementById('searchBy').value;
            const searchValue = document.getElementById('searchValue').value.trim().toLowerCase();
            
            if (!searchValue) {
                alert('Please enter search value');
                return;
            }
            
            let results = [];
            
            switch(searchBy) {
                case 'memberCode':
                    results = memberSearchData.filter(m => m.memberCode.toLowerCase().includes(searchValue));
                    break;
                case 'memberName':
                    results = memberSearchData.filter(m => m.memberName.toLowerCase().includes(searchValue));
                    break;
                case 'panNo':
                    results = memberSearchData.filter(m => m.panNo.toLowerCase().includes(searchValue));
                    break;
                case 'phoneNo':
                    results = memberSearchData.filter(m => m.phoneNo.includes(searchValue));
                    break;
            }
            
            // Reset SL NO for results
            results.forEach((record, index) => {
                record.slNo = index + 1;
                record.selected = false;
            });
            
            currentSearchResults = results;
            loadMemberSearchTable(results);
            
            alert(`Search completed. Found ${results.length} record(s).`);
        }

        // Toggle row selection
        function toggleSearchRowSelection(index, isChecked) {
            if (currentSearchResults[index]) {
                currentSearchResults[index].selected = isChecked;
            }
            
            const row = document.querySelector(`#memberSearchTableBody tr[data-index="${index}"]`);
            if (row) {
                if (isChecked) {
                    row.classList.add('selected');
                } else {
                    row.classList.remove('selected');
                }
            }
            
            updateSelectAllSearchCheckbox();
        }

        // Select single row
        function selectSearchRow(index) {
            const currentChecked = currentSearchResults[index]?.selected || false;
            toggleSearchRowSelection(index, !currentChecked);
            
            const checkbox = document.querySelector(`.row-search-checkbox[data-index="${index}"]`);
            if (checkbox) {
                checkbox.checked = !currentChecked;
            }
        }

        // Toggle Select All
        function toggleSelectAllSearch() {
            const selectAllCheckbox = document.getElementById('selectAllSearch');
            const isChecked = selectAllCheckbox.checked;
            
            currentSearchResults.forEach((record, index) => {
                record.selected = isChecked;
            });
            
            // Update all row checkboxes and row classes
            const rowCheckboxes = document.querySelectorAll('.row-search-checkbox');
            rowCheckboxes.forEach((checkbox, idx) => {
                checkbox.checked = isChecked;
                const row = checkbox.closest('tr');
                if (row) {
                    if (isChecked) {
                        row.classList.add('selected');
                    } else {
                        row.classList.remove('selected');
                    }
                }
            });
        }

        // Update Select All checkbox state
        function updateSelectAllSearchCheckbox() {
            const selectAllCheckbox = document.getElementById('selectAllSearch');
            if (!selectAllCheckbox) return;
            
            const allSelected = currentSearchResults.length > 0 && currentSearchResults.every(record => record.selected === true);
            const anySelected = currentSearchResults.some(record => record.selected === true);
            
            selectAllCheckbox.checked = allSelected;
            selectAllCheckbox.indeterminate = anySelected && !allSelected;
        }

        // Edit selected member
        function editSelectedMember() {
            const selectedMembers = currentSearchResults.filter(record => record.selected);
            
            if (selectedMembers.length === 0) {
                alert('Please select at least one member to edit');
                return;
            }
            
            if (selectedMembers.length > 1) {
                alert('Please select only one member to edit');
                return;
            }
            
            const member = selectedMembers[0];
            
            // Populate edit form (you can show a modal or redirect)
            const editInfo = `Edit Member Details:\n\n` +
                `Member Code: ${member.memberCode}\n` +
                `Member Name: ${member.memberName}\n` +
                `Gender: ${member.gender}\n` +
                `PAN No: ${member.panNo}\n` +
                `Phone No: ${member.phoneNo}\n` +
                `Nominee: ${member.nominee}\n` +
                `Branch: ${member.branch}\n\n` +
                `(In production, this would open an edit form)`;
            
            alert(editInfo);
        }

        // Generate report from selected members
        function generateMemberReport() {
            const selectedMembers = currentSearchResults.filter(record => record.selected);
            
            if (selectedMembers.length === 0) {
                alert('Please select at least one member to generate report');
                return;
            }
            
            let reportContent = '=== MEMBER REPORT ===\n\n';
            reportContent += `Generated on: ${new Date().toLocaleString()}\n`;
            reportContent += `Total Members: ${selectedMembers.length}\n`;
            reportContent += '='.repeat(50) + '\n\n';
            
            selectedMembers.forEach((member, idx) => {
                reportContent += `${idx + 1}. Member Code: ${member.memberCode}\n`;
                reportContent += `   Name: ${member.memberName}\n`;
                reportContent += `   Gender: ${member.gender}\n`;
                reportContent += `   DOJ: ${member.doj}\n`;
                reportContent += `   PAN: ${member.panNo}\n`;
                reportContent += `   Phone: ${member.phoneNo}\n`;
                reportContent += `   Branch: ${member.branch}\n`;
                reportContent += `   Status: ${member.status}\n`;
                reportContent += '-'.repeat(30) + '\n';
            });
            
            // Open in new window for printing
            const printWindow = window.open('', '_blank');
            printWindow.document.write(`
                <html>
                <head><title>Member Report</title>
                <style>
                    body { font-family: monospace; padding: 20px; white-space: pre-wrap; }
                </style>
                </head>
                <body>${reportContent.replace(/\n/g, '<br>')}</body>
                </html>
            `);
            printWindow.print();
        }

        // Close member search (reset)
        function closeMemberSearch() {
            document.getElementById('searchBy').value = 'memberCode';
            document.getElementById('searchValue').value = '';
            
            // Reset all selections
            memberSearchData.forEach(record => {
                record.selected = false;
            });
            
            // Reload all data
            currentSearchResults = [...memberSearchData];
            currentSearchResults.forEach((record, index) => {
                record.slNo = index + 1;
            });
            loadMemberSearchTable(currentSearchResults);
            
            alert('Search closed. Results reset.');
        }

        // Show Member Search module
        function showMemberSearch() {
            if (document.querySelectorAll('.content-section')) {
                document.querySelectorAll('.content-section').forEach(section => {
                    section.style.display = 'none';
                });
            }
            
            const searchContainer = document.getElementById('memberSearchContainer');
            if (searchContainer) {
                searchContainer.style.display = 'block';
            }
            
            // Initialize with all data
            currentSearchResults = [...memberSearchData];
            currentSearchResults.forEach((record, index) => {
                record.slNo = index + 1;
                record.selected = false;
            });
            loadMemberSearchTable(currentSearchResults);
        }
    
        // Collector Entry Module Functions

        let collectorsDatabase = [];
        let currentEditCode = null;

        // Calculate age
        function calculateCollectorAge() {
            const dobInput = document.getElementById('dob');
            const ageInput = document.getElementById('age');
            if (dobInput && dobInput.value && ageInput) {
                const birthDate = new Date(dobInput.value);
                const today = new Date();
                let age = today.getFullYear() - birthDate.getFullYear();
                const monthDiff = today.getMonth() - birthDate.getMonth();
                if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) age--;
                ageInput.value = age;
            }
        }

        // Search by code from top left
        function searchByCode() {
            const searchCode = document.getElementById('searchAssociateCode').value.trim();
            if (!searchCode) {
                alert('Please enter Associate Code to search');
                return;
            }
            const collector = collectorsDatabase.find(c => c.associateCode === searchCode);
            if (collector) {
                populateForm(collector);
                alert(`Collector found: ${collector.agentName}`);
            } else {
                alert('Collector not found');
            }
        }

        // Populate form with collector data
        function populateForm(collector) {
            document.getElementById('associateCode').value = collector.associateCode || '';
            document.getElementById('membershipNo').value = collector.membershipNo || '';
            document.getElementById('dateOfJoining').value = collector.dateOfJoining || '';
            document.getElementById('applicationNo').value = collector.applicationNo || '';
            document.getElementById('agentName').value = collector.agentName || '';
            document.getElementById('fatherHusbandName').value = collector.fatherHusbandName || '';
            document.getElementById('agentRank').value = collector.agentRank || '';
            document.getElementById('position').value = collector.position || '';
            document.getElementById('address').value = collector.address || '';
            document.getElementById('pinCode').value = collector.pinCode || '';
            document.getElementById('dob').value = collector.dob || '';
            document.getElementById('age').value = collector.age || '';
            document.getElementById('nomineeName').value = collector.nomineeName || '';
            document.getElementById('nomineeRelation').value = collector.nomineeRelation || '';
            document.getElementById('nomineeAge').value = collector.nomineeAge || '';
            document.getElementById('bloodGroup').value = collector.bloodGroup || '';
            document.getElementById('sex').value = collector.sex || '';
            document.getElementById('phoneNo').value = collector.phoneNo || '';
            document.getElementById('introducerCode').value = collector.introducerCode || '';
            document.getElementById('introducerName').value = collector.introducerName || '';
            document.getElementById('introducerRank').value = collector.introducerRank || '';
            document.getElementById('branchNameCode').value = collector.branchNameCode || '';
            document.getElementById('regAmt').value = collector.regAmt || '';
            document.getElementById('status').value = collector.status || '';
            document.getElementById('remarks').value = collector.remarks || '';
            document.getElementById('panCardNo').value = collector.panCardNo || '';
            document.getElementById('passportNo').value = collector.passportNo || '';
            document.getElementById('voterIdNo').value = collector.voterIdNo || '';
            document.getElementById('drivingLicenseNo').value = collector.drivingLicenseNo || '';
            document.getElementById('aadharNo').value = collector.aadharNo || '';
            document.getElementById('rationCardNo').value = collector.rationCardNo || '';
            document.getElementById('accountNo').value = collector.accountNo || '';
            document.getElementById('bankName').value = collector.bankName || '';
            document.getElementById('ifscCode').value = collector.ifscCode || '';
            document.getElementById('bankBranch').value = collector.bankBranch || '';
            currentEditCode = collector.associateCode;
        }

        // Save collector
        function saveCollector() {
            const associateCode = document.getElementById('associateCode').value.trim();
            if (!associateCode) {
                alert('Please enter Associate Code');
                return;
            }
            if (collectorsDatabase.some(c => c.associateCode === associateCode)) {
                alert('Associate Code already exists. Use Update button.');
                return;
            }
            const collectorData = getFormData();
            collectorsDatabase.push(collectorData);
            renderCollectorTable();
            clearCollectorForm();
            alert(`Collector ${collectorData.agentName} saved successfully`);
        }

        // Update collector
        function updateCollector() {
            const associateCode = document.getElementById('associateCode').value.trim();
            if (!associateCode) {
                alert('Please enter Associate Code');
                return;
            }
            const index = collectorsDatabase.findIndex(c => c.associateCode === associateCode);
            if (index === -1) {
                alert('Collector not found. Please save as new.');
                return;
            }
            collectorsDatabase[index] = getFormData();
            renderCollectorTable();
            alert(`Collector ${associateCode} updated successfully`);
        }

        // Delete collector
        function deleteCollector() {
            const associateCode = document.getElementById('associateCode').value.trim();
            if (!associateCode) {
                alert('Please enter Associate Code to delete');
                return;
            }
            if (confirm(`Delete collector ${associateCode}?`)) {
                collectorsDatabase = collectorsDatabase.filter(c => c.associateCode !== associateCode);
                renderCollectorTable();
                clearCollectorForm();
                alert('Collector deleted successfully');
            }
        }

        // Get form data
        function getFormData() {
            return {
                associateCode: document.getElementById('associateCode').value.trim(),
                membershipNo: document.getElementById('membershipNo').value.trim(),
                dateOfJoining: document.getElementById('dateOfJoining').value,
                applicationNo: document.getElementById('applicationNo').value.trim(),
                agentName: document.getElementById('agentName').value.trim(),
                fatherHusbandName: document.getElementById('fatherHusbandName').value.trim(),
                agentRank: document.getElementById('agentRank').value,
                position: document.getElementById('position').value,
                address: document.getElementById('address').value.trim(),
                pinCode: document.getElementById('pinCode').value.trim(),
                dob: document.getElementById('dob').value,
                age: document.getElementById('age').value,
                nomineeName: document.getElementById('nomineeName').value.trim(),
                nomineeRelation: document.getElementById('nomineeRelation').value.trim(),
                nomineeAge: document.getElementById('nomineeAge').value.trim(),
                bloodGroup: document.getElementById('bloodGroup').value,
                sex: document.getElementById('sex').value,
                phoneNo: document.getElementById('phoneNo').value.trim(),
                introducerCode: document.getElementById('introducerCode').value.trim(),
                introducerName: document.getElementById('introducerName').value.trim(),
                introducerRank: document.getElementById('introducerRank').value,
                branchNameCode: document.getElementById('branchNameCode').value,
                regAmt: document.getElementById('regAmt').value,
                status: document.getElementById('status').value,
                remarks: document.getElementById('remarks').value.trim(),
                panCardNo: document.getElementById('panCardNo').value.trim(),
                passportNo: document.getElementById('passportNo').value.trim(),
                voterIdNo: document.getElementById('voterIdNo').value.trim(),
                drivingLicenseNo: document.getElementById('drivingLicenseNo').value.trim(),
                aadharNo: document.getElementById('aadharNo').value.trim(),
                rationCardNo: document.getElementById('rationCardNo').value.trim(),
                accountNo: document.getElementById('accountNo').value.trim(),
                bankName: document.getElementById('bankName').value.trim(),
                ifscCode: document.getElementById('ifscCode').value.trim(),
                bankBranch: document.getElementById('bankBranch').value.trim()
            };
        }

        // Render collector table
        function renderCollectorTable() {
            const tbody = document.getElementById('collectorTableBody');
            if (!tbody) return;
            
            if (collectorsDatabase.length === 0) {
                tbody.innerHTML = '<tr><td colspan="3" style="text-align:center">No records found</td></tr>';
                return;
            }
            
            tbody.innerHTML = '';
            collectorsDatabase.forEach((c) => {
                const row = tbody.insertRow();
                row.insertCell(0).innerHTML = c.agentRank || '-';
                row.insertCell(1).innerHTML = c.associateCode || '-';
                row.insertCell(2).innerHTML = c.agentName || '-';
            });
        }

        function editFromTable(code) {
            const collector = collectorsDatabase.find(c => c.associateCode === code);
            if (collector) populateForm(collector);
        }

        function deleteFromTable(code) {
            if (confirm(`Delete ${code}?`)) {
                collectorsDatabase = collectorsDatabase.filter(c => c.associateCode !== code);
                renderCollectorTable();
                if (currentEditCode === code) clearCollectorForm();
            }
        }

        // Clear form
        function clearCollectorForm() {
            document.querySelectorAll('#collectorEntryContainer input, #collectorEntryContainer select, #collectorEntryContainer textarea').forEach(field => {
                if (field.type !== 'file') field.value = '';
            });
            document.getElementById('dateOfJoining').value = '2026-04-04';
            document.getElementById('dob').value = '2026-04-04';
            document.getElementById('regAmt').value = '0';
            document.getElementById('status').value = 'Active';
            document.getElementById('bloodGroup').value = 'A+';
            document.getElementById('sex').value = 'MALE';
            currentEditCode = null;
        }

        // Print functions
        function printMoneyReceipt() {
            const agentName = document.getElementById('agentName').value || 'N/A';
            const associateCode = document.getElementById('associateCode').value || 'N/A';
            const regAmt = document.getElementById('regAmt').value || '0';
            const win = window.open('', '_blank');
            win.document.write(`<html><head><title>Money Receipt</title><style>body{font-family:Arial;padding:40px}</style></head><body><h2>MONEY RECEIPT</h2><hr><p>Collector: ${agentName}</p><p>Associate Code: ${associateCode}</p><p>Amount: ₹${regAmt}</p><p>Date: ${new Date().toLocaleDateString()}</p><hr><p>Thank you</p></body></html>`);
            win.print();
        }

        function printCollectorCard() {
            const agentName = document.getElementById('agentName').value || 'N/A';
            const associateCode = document.getElementById('associateCode').value || 'N/A';
            const win = window.open('', '_blank');
            win.document.write(`<html><head><title>Collector Card</title><style>body{font-family:Arial;padding:40px}</style></head><body><h2>COLLECTOR CARD</h2><hr><p>Name: ${agentName}</p><p>Code: ${associateCode}</p><p>Rank: ${document.getElementById('agentRank').value}</p><p>Branch: ${document.getElementById('branchNameCode').value}</p><hr><p>Authorized Signature</p></body></html>`);
            win.print();
        }

        function printIdCard() {
            const agentName = document.getElementById('agentName').value || 'N/A';
            const associateCode = document.getElementById('associateCode').value || 'N/A';
            const win = window.open('', '_blank');
            win.document.write(`<html><head><title>ID Card</title><style>body{font-family:Arial;padding:40px}</style></head><body><div style="border:2px solid #000;padding:20px;text-align:center"><h2>IDENTITY CARD</h2><hr><p><strong>${agentName}</strong></p><p>Associate Code: ${associateCode}</p><p>Valid Until: 31/03/2027</p><hr><p>Authorized</p></div></body></html>`);
            win.print();
        }

        // Preview photo before upload
        function previewPhoto(input) {
            const preview = document.getElementById('photoPreview');
            const placeholder = document.getElementById('photoPlaceholder');
            
            if (input.files && input.files[0]) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    preview.src = e.target.result;
                    preview.style.display = 'block';
                    placeholder.style.display = 'none';
                }
                reader.readAsDataURL(input.files[0]);
            }
        }

        // Show module
        function showCollectorEntry() {
            document.querySelectorAll('.content-section').forEach(s => s.style.display = 'none');
            document.getElementById('collectorEntryContainer').style.display = 'block';
            renderCollectorTable();
        }

        // Agent Promotion Module Functions

        // Mock agent database
        let agentsDatabase = [
            { agentCode: 'AGT001', agentName: 'RAHUL KUMAR', rank: 'Junior Collector', sponsorCode: 'SP001', sponsorName: 'SURESH SINGH', sponsorRank: 'Senior Collector' },
            { agentCode: 'AGT002', agentName: 'PRIYA SHARMA', rank: 'Senior Collector', sponsorCode: 'SP002', sponsorName: 'AMIT PATEL', sponsorRank: 'Master Collector' },
            { agentCode: 'AGT003', agentName: 'VIKAS GUPTA', rank: 'Master Collector', sponsorCode: 'SP003', sponsorName: 'NEHA VERMA', sponsorRank: 'Regional Collector' }
        ];

        let newUplineData = [];
        let oldUplineData = [];

        // Search agent by code
        document.getElementById('agentCode').addEventListener('blur', function() {
            const agentCode = this.value.trim();
            if (agentCode) {
                const agent = agentsDatabase.find(a => a.agentCode === agentCode);
                if (agent) {
                    document.getElementById('agentName').value = agent.agentName;
                    document.getElementById('agentRank').value = agent.rank;
                    document.getElementById('sponsorCode').value = agent.sponsorCode || '';
                    document.getElementById('sponsorName').value = agent.sponsorName || '';
                    document.getElementById('sponsorRank').value = agent.sponsorRank || '';
                } else {
                    document.getElementById('agentName').value = 'Not Found';
                    document.getElementById('agentRank').value = '';
                    document.getElementById('sponsorCode').value = '';
                    document.getElementById('sponsorName').value = '';
                    document.getElementById('sponsorRank').value = '';
                }
            }
        });

        // Search new sponsor by code
        document.getElementById('newSponsorCode').addEventListener('blur', function() {
            const sponsorCode = this.value.trim();
            if (sponsorCode) {
                const sponsor = agentsDatabase.find(a => a.agentCode === sponsorCode);
                if (sponsor) {
                    document.getElementById('newSponsorName').value = sponsor.agentName;
                    document.getElementById('newSponsorRank').value = sponsor.rank;
                } else {
                    document.getElementById('newSponsorName').value = 'Not Found';
                    document.getElementById('newSponsorRank').value = '';
                }
            }
        });

        // Rank promotion change - update new upline
        document.getElementById('rankPromotion').addEventListener('change', function() {
            const newRank = this.value;
            const agentCode = document.getElementById('agentCode').value.trim();
            const agentName = document.getElementById('agentName').value.trim();
            const oldRank = document.getElementById('agentRank').value.trim();
            
            if (newRank && agentCode && agentName) {
                // Add to new upline
                const existingIndex = newUplineData.findIndex(u => u.agentCode === agentCode);
                if (existingIndex !== -1) {
                    newUplineData[existingIndex].rank = newRank;
                } else {
                    newUplineData.push({ rank: newRank, agentCode: agentCode, agentName: agentName });
                }
                renderNewUplineTable();
                
                // Add to old upline if not already
                if (oldRank) {
                    const oldExists = oldUplineData.some(u => u.agentCode === agentCode);
                    if (!oldExists) {
                        oldUplineData.push({ rank: oldRank, agentCode: agentCode, agentName: agentName });
                        renderOldUplineTable();
                    }
                }
            }
        });

        // Render New Upline Table
        function renderNewUplineTable() {
            const tbody = document.getElementById('newUplineTableBody');
            if (!tbody) return;
            if (newUplineData.length === 0) {
                tbody.innerHTML = '<tr><td colspan="3" style="text-align:center">No records found</td></tr>';
                return;
            }
            tbody.innerHTML = '';
            newUplineData.forEach((item) => {
                const row = tbody.insertRow();
                row.insertCell(0).innerHTML = item.rank;
                row.insertCell(1).innerHTML = item.agentCode;
                row.insertCell(2).innerHTML = item.agentName;
            });
        }

        // Render Old Upline Table
        function renderOldUplineTable() {
            const tbody = document.getElementById('oldUplineTableBody');
            if (!tbody) return;
            if (oldUplineData.length === 0) {
                tbody.innerHTML = '<tr><td colspan="3" style="text-align:center">No records found</td></tr>';
                return;
            }
            tbody.innerHTML = '';
            oldUplineData.forEach((item) => {
                const row = tbody.insertRow();
                row.insertCell(0).innerHTML = item.rank;
                row.insertCell(1).innerHTML = item.agentCode;
                row.insertCell(2).innerHTML = item.agentName;
            });
        }

        // Update Promotion
        function updatePromotion() {
            const agentCode = document.getElementById('agentCode').value.trim();
            const newRank = document.getElementById('rankPromotion').value;
            const newSponsorCode = document.getElementById('newSponsorCode').value.trim();
            const remarks = document.getElementById('remarks').value.trim();
            
            if (!agentCode) {
                alert('Please enter Agent Code');
                return;
            }
            if (!newRank) {
                alert('Please select Rank Promotion');
                return;
            }
            
            const agentIndex = agentsDatabase.findIndex(a => a.agentCode === agentCode);
            if (agentIndex !== -1) {
                agentsDatabase[agentIndex].rank = newRank;
                if (newSponsorCode) {
                    agentsDatabase[agentIndex].sponsorCode = newSponsorCode;
                    const newSponsor = agentsDatabase.find(a => a.agentCode === newSponsorCode);
                    if (newSponsor) {
                        agentsDatabase[agentIndex].sponsorName = newSponsor.agentName;
                        agentsDatabase[agentIndex].sponsorRank = newSponsor.rank;
                    }
                }
            }
            
            alert(`Promotion Updated!\nAgent: ${agentCode}\nNew Rank: ${newRank}\nRemarks: ${remarks || 'N/A'}`);
        }

        // Clear form
        function clearPromotionForm() {
            if (confirm('Clear all form data?')) {
                document.getElementById('agentCode').value = '';
                document.getElementById('agentName').value = '';
                document.getElementById('agentRank').value = '';
                document.getElementById('sponsorCode').value = '';
                document.getElementById('sponsorName').value = '';
                document.getElementById('sponsorRank').value = '';
                document.getElementById('serviceBranch').value = 'HEAD OFFICE - 001';
                document.getElementById('rankPromotion').value = '';
                document.getElementById('newSponsorCode').value = '';
                document.getElementById('newSponsorName').value = '';
                document.getElementById('newSponsorRank').value = '';
                document.getElementById('remarks').value = '';
                document.getElementById('downMaxResult').value = '';
                document.getElementById('rightAgentCode').value = '';
                document.getElementById('rightAgentName').value = '';
                document.getElementById('uplineMinRank').value = '';
                document.getElementById('rightAgentCode2').value = '';
                document.getElementById('rightAgentName2').value = '';

                alert('Form cleared');
            }
        }

        // Commit and Close
        function commitAndClose() {
            if (newUplineData.length === 0) {
                alert('No changes to commit');
                return;
            }
            
            if (confirm('Commit these changes? This will update the chain.')) {
                setTimeout(() => {
                    alert('Changes committed successfully! Chain updated.');
                    clearPromotionForm();
                    newUplineData = [];
                    oldUplineData = [];
                    renderNewUplineTable();
                    renderOldUplineTable();
                }, 1000);
            }
        }

        // Show module
        function showAgentPromotion() {
            document.querySelectorAll('.content-section').forEach(s => s.style.display = 'none');
            document.getElementById('agentPromotionContainer').style.display = 'block';
        }

        // Associate Block / UnBlock Functions

        let associatesData = [
            { agentCode: 'AGT001', agentName: 'RAHUL KUMAR', rank: 'Junior Collector', doj: '2024-01-15', phoneNo: '9876543210', branch: 'HEAD OFFICE - 001', status: 'Active', selected: false },
            { agentCode: 'AGT002', agentName: 'PRIYA SHARMA', rank: 'Senior Collector', doj: '2024-02-20', phoneNo: '9876543211', branch: 'BRANCH - 002', status: 'Active', selected: false },
            { agentCode: 'AGT003', agentName: 'VIKAS GUPTA', rank: 'Master Collector', doj: '2024-03-10', phoneNo: '9876543212', branch: 'HEAD OFFICE - 001', status: 'Blocked', selected: false },
            { agentCode: 'AGT004', agentName: 'NEHA VERMA', rank: 'Regional Collector', doj: '2024-04-05', phoneNo: '9876543213', branch: 'BRANCH - 003', status: 'Active', selected: false },
            { agentCode: 'AGT005', agentName: 'AMIT PATEL', rank: 'Senior Collector', doj: '2024-05-12', phoneNo: '9876543214', branch: 'HEAD OFFICE - 001', status: 'Active', selected: false }
        ];

        function renderAssociateTable() {
            const tbody = document.getElementById('associateTableBody');
            if (!tbody) return;
            
            if (associatesData.length === 0) {
                tbody.innerHTML = '<tr><td colspan="9" style="text-align:center">No records found</td></tr>';
                return;
            }
            
            tbody.innerHTML = '';
            associatesData.forEach((item, idx) => {
                const row = tbody.insertRow();
                row.insertCell(0).innerHTML = `<input type="checkbox" class="row-select" data-index="${idx}" ${item.selected ? 'checked' : ''} onchange="toggleRowSelection(${idx}, this.checked)">`;
                row.insertCell(1).innerHTML = idx + 1;
                row.insertCell(2).innerHTML = item.agentCode;
                row.insertCell(3).innerHTML = item.agentName;
                row.insertCell(4).innerHTML = item.rank;
                row.insertCell(5).innerHTML = item.doj;
                row.insertCell(6).innerHTML = item.phoneNo;
                row.insertCell(7).innerHTML = item.branch;
                row.insertCell(8).innerHTML = `<span class="status-${item.status.toLowerCase()}">${item.status}</span>`;
            });
        }

        function toggleRowSelection(index, isChecked) {
            associatesData[index].selected = isChecked;
            updateSelectAllCheckboxes();
        }

        function toggleSelectAllAssociates() {
            const selectAll = document.getElementById('selectAllAssociates');
            const isChecked = selectAll.checked;
            associatesData.forEach(item => item.selected = isChecked);
            document.querySelectorAll('.row-select').forEach(cb => cb.checked = isChecked);
            updateSelectAllCheckboxes();
        }

        function toggleSelectAllFromHeader() {
            const headerCheckbox = document.getElementById('headerSelectAllAssociates');
            const isChecked = headerCheckbox.checked;
            associatesData.forEach(item => item.selected = isChecked);
            document.querySelectorAll('.row-select').forEach(cb => cb.checked = isChecked);
            const selectAllLabel = document.getElementById('selectAllAssociates');
            if (selectAllLabel) selectAllLabel.checked = isChecked;
            updateSelectAllCheckboxes();
        }

        function updateSelectAllCheckboxes() {
            const allSelected = associatesData.length > 0 && associatesData.every(item => item.selected === true);
            const anySelected = associatesData.some(item => item.selected === true);
            
            const selectAll = document.getElementById('selectAllAssociates');
            const headerSelectAll = document.getElementById('headerSelectAllAssociates');
            
            if (selectAll) selectAll.checked = allSelected;
            if (headerSelectAll) headerSelectAll.checked = allSelected;
            if (headerSelectAll) headerSelectAll.indeterminate = anySelected && !allSelected;
        }

        function viewAssociates() {
            const selected = associatesData.filter(item => item.selected);
            if (selected.length === 0) {
                alert('Please select at least one associate to view');
                return;
            }
            alert(`Viewing ${selected.length} associate(s)\n\n` + selected.map(s => `${s.agentCode} - ${s.agentName} (${s.status})`).join('\n'));
        }

        function blockAssociates() {
            const selected = associatesData.filter(item => item.selected && item.status !== 'Blocked');
            if (selected.length === 0) {
                alert('Please select active associates to block');
                return;
            }
            if (confirm(`Block ${selected.length} associate(s)?`)) {
                selected.forEach(item => item.status = 'Blocked');
                renderAssociateTable();
                alert(`${selected.length} associate(s) blocked successfully`);
            }
        }

        function unblockAssociates() {
            const selected = associatesData.filter(item => item.selected && item.status === 'Blocked');
            if (selected.length === 0) {
                alert('Please select blocked associates to unblock');
                return;
            }
            if (confirm(`Unblock ${selected.length} associate(s)?`)) {
                selected.forEach(item => item.status = 'Active');
                renderAssociateTable();
                alert(`${selected.length} associate(s) unblocked successfully`);
            }
        }

        function showAssociateBlock() {
            document.querySelectorAll('.content-section').forEach(s => s.style.display = 'none');
            document.getElementById('associateBlockContainer').style.display = 'block';
            renderAssociateTable();
        }

        // Collector Search Functions

        let collectorSearchData = [
            { slNo: 1, mCode: 'AGT001', mName: 'RAHUL KUMAR', rank: 'Junior', doj: '2024-01-15', intCode: 'INT001', intName: 'SURESH', panNo: 'ABCDE1234F', phoneNo: '9876543210', branch: 'HEAD OFFICE - 001', status: 'Active', selected: false },
            { slNo: 2, mCode: 'AGT002', mName: 'PRIYA SHARMA', rank: 'Senior', doj: '2024-02-20', intCode: 'INT002', intName: 'AMIT', panNo: 'XYZAB5678G', phoneNo: '9876543211', branch: 'BRANCH - 002', status: 'Active', selected: false },
            { slNo: 3, mCode: 'AGT003', mName: 'VIKAS GUPTA', rank: 'Master', doj: '2024-03-10', intCode: 'INT003', intName: 'NEHA', panNo: 'GUPTA9012J', phoneNo: '9876543212', branch: 'HEAD OFFICE - 001', status: 'Blocked', selected: false },
            { slNo: 4, mCode: 'AGT004', mName: 'NEHA VERMA', rank: 'Regional', doj: '2024-04-05', intCode: 'INT004', intName: 'RAJ', panNo: 'VERMA3456K', phoneNo: '9876543213', branch: 'BRANCH - 003', status: 'Active', selected: false },
            { slNo: 5, mCode: 'AGT005', mName: 'AMIT PATEL', rank: 'Senior', doj: '2024-05-12', intCode: 'INT005', intName: 'PRIYA', panNo: 'PATEL7890L', phoneNo: '9876543214', branch: 'HEAD OFFICE - 001', status: 'Active', selected: false }
        ];

        let AgenttSearchResults = [];

        function renderCollectorSearchTable(data) {
            const tbody = document.getElementById('collectorSearchTableBody');
            if (!tbody) return;
            
            if (!data || data.length === 0) {
                tbody.innerHTML = '<tr><td colspan="12" style="text-align:center">No records found</td></tr>';
                return;
            }
            
            tbody.innerHTML = '';
            data.forEach((item, idx) => {
                const row = tbody.insertRow();
                row.insertCell(0).innerHTML = `<input type="checkbox" class="row-select-search" data-index="${idx}" ${item.selected ? 'checked' : ''} onchange="toggleSearchRowSelection(${idx}, this.checked)">`;
                row.insertCell(1).innerHTML = item.slNo;
                row.insertCell(2).innerHTML = item.mCode;
                row.insertCell(3).innerHTML = item.mName;
                row.insertCell(4).innerHTML = item.rank;
                row.insertCell(5).innerHTML = item.doj;
                row.insertCell(6).innerHTML = item.intCode;
                row.insertCell(7).innerHTML = item.intName;
                row.insertCell(8).innerHTML = item.panNo;
                row.insertCell(9).innerHTML = item.phoneNo;
                row.insertCell(10).innerHTML = item.branch;
                row.insertCell(11).innerHTML = `<span class="status-${item.status.toLowerCase()}">${item.status}</span>`;
            });
        }

        function performCollectorSearch() {
            const searchBy = document.getElementById('searchBy').value;
            const searchValue = document.getElementById('searchValue').value.trim().toLowerCase();
            
            if (!searchValue) {
                alert('Please enter search value');
                return;
            }
            
            let results = [];
            switch(searchBy) {
                case 'agentCode': results = collectorSearchData.filter(c => c.mCode.toLowerCase().includes(searchValue)); break;
                case 'agentName': results = collectorSearchData.filter(c => c.mName.toLowerCase().includes(searchValue)); break;
                case 'panNo': results = collectorSearchData.filter(c => c.panNo.toLowerCase().includes(searchValue)); break;
                case 'phoneNo': results = collectorSearchData.filter(c => c.phoneNo.includes(searchValue)); break;
            }
            
            results.forEach((r, idx) => { r.slNo = idx + 1; r.selected = false; });
            AgentSearchResults = results;
            renderCollectorSearchTable(results);
            alert(`Found ${results.length} record(s)`);
        }

        function toggleSearchRowSelection(index, isChecked) {
            if (AgentSearchResults[index]) AgentSearchResults[index].selected = isChecked;
            updateSelectAllCollectorSearch();
        }

        function toggleSelectAllCollectorSearch() {
            const selectAll = document.getElementById('selectAllCollectorSearch');
            const isChecked = selectAll.checked;
            AgentSearchResults.forEach(item => item.selected = isChecked);
            document.querySelectorAll('.row-select-search').forEach(cb => cb.checked = isChecked);
        }

        function updateSelectAllCollectorSearch() {
            const selectAll = document.getElementById('selectAllCollectorSearch');
            if (!selectAll || AgentSearchResults.length === 0) return;
            const allSelected = AgentSearchResults.every(item => item.selected);
            selectAll.checked = allSelected;
        }

        function editSelectedRecord() {
            const selected = AgentSearchResults.filter(item => item.selected);
            if (selected.length === 0) {
                alert('Please select a record to edit');
                return;
            }
            if (selected.length > 1) {
                alert('Please select only one record to edit');
                return;
            }
            alert(`Edit Record:\n\nM. CODE: ${selected[0].mCode}\nM. NAME: ${selected[0].mName}\nPAN NO: ${selected[0].panNo}\nPHONE: ${selected[0].phoneNo}\n\n(Edit form would open here)`);
        }

        function closeCollectorSearch() {
            document.getElementById('searchBy').value = 'agentCode';
            document.getElementById('searchValue').value = '';
            AgentSearchResults= [...collectorSearchData];
            AgentSearchResults.forEach((r, idx) => { r.slNo = idx + 1; r.selected = false; });
            renderCollectorSearchTable(AgentSearchResults);
            alert('Search closed. Results reset.');
        }

        function showCollectorSearch() {
            document.querySelectorAll('.content-section').forEach(s => s.style.display = 'none');
            document.getElementById('collectorSearchContainer').style.display = 'block';
            AgentSearchResults = [...collectorSearchData];
            AgentSearchResults.forEach((r, idx) => { r.slNo = idx + 1; r.selected = false; });
            renderCollectorSearchTable(AgentSearchResults);
        }

        // Associate Downline Functions

        // Mock database
        let associatesDownlineDB = [
            { code: 'AGT001', name: 'RAHUL KUMAR', rank: 'Junior Collector', doj: '2024-01-15', sponsor: 'SP001', sponsorName: 'SURESH SINGH', branch: 'HEAD OFFICE - 001' },
            { code: 'AGT002', name: 'PRIYA SHARMA', rank: 'Senior Collector', doj: '2024-02-20', sponsor: 'AGT001', sponsorName: 'RAHUL KUMAR', branch: 'BRANCH - 002' },
            { code: 'AGT003', name: 'VIKAS GUPTA', rank: 'Master Collector', doj: '2024-03-10', sponsor: 'AGT001', sponsorName: 'RAHUL KUMAR', branch: 'HEAD OFFICE - 001' },
            { code: 'AGT004', name: 'NEHA VERMA', rank: 'Regional Collector', doj: '2024-04-05', sponsor: 'AGT002', sponsorName: 'PRIYA SHARMA', branch: 'BRANCH - 003' },
            { code: 'AGT005', name: 'AMIT PATEL', rank: 'Senior Collector', doj: '2024-05-12', sponsor: 'AGT003', sponsorName: 'VIKAS GUPTA', branch: 'HEAD OFFICE - 001' },
            { code: 'AGT006', name: 'SUNITA SINGH', rank: 'Junior Collector', doj: '2024-06-18', sponsor: 'AGT002', sponsorName: 'PRIYA SHARMA', branch: 'BRANCH - 002' },
            { code: 'AGT007', name: 'RAJESH KUMAR', rank: 'Master Collector', doj: '2024-07-22', sponsor: 'AGT001', sponsorName: 'RAHUL KUMAR', branch: 'HEAD OFFICE - 001' }
        ];

        // Search associate by code
        document.getElementById('associateCode').addEventListener('blur', function() {
            const code = this.value.trim();
            if (code) {
                const associate = associatesDownlineDB.find(a => a.code === code);
                if (associate) {
                    document.getElementById('associateName').value = associate.name;
                    document.getElementById('associateRank').value = associate.rank;
                    document.getElementById('associateBranch').value = associate.branch;
                } else {
                    document.getElementById('associateName').value = 'Not Found';
                    document.getElementById('associateRank').value = '';
                    document.getElementById('associateBranch').value = '';
                }
            }
        });

        // View Downline
        function viewDownline() {
            const associateCode = document.getElementById('associateCode').value.trim();
            
            if (!associateCode) {
                alert('Please enter Associate Code');
                return;
            }
            
            // Find all downline (where sponsor = associateCode)
            const downline = associatesDownlineDB.filter(a => a.sponsor === associateCode);
            
            if (downline.length === 0) {
                document.getElementById('downlineTableBody').innerHTML = '<tr><td colspan="7" style="text-align:center">No downline found for this associate</td></tr>';
                alert('No downline found for this associate');
                return;
            }
            
            renderDownlineTable(downline);
            alert(`Found ${downline.length} downline member(s)`);
        }

        // Render Downline Table
        function renderDownlineTable(data) {
            const tbody = document.getElementById('downlineTableBody');
            if (!tbody) return;
            
            tbody.innerHTML = '';
            data.forEach((item) => {
                const row = tbody.insertRow();
                row.insertCell(0).innerHTML = item.code;
                row.insertCell(1).innerHTML = item.name;
                row.insertCell(2).innerHTML = item.rank;
                row.insertCell(3).innerHTML = item.doj;
                row.insertCell(4).innerHTML = item.sponsor;
                row.insertCell(5).innerHTML = item.sponsorName;
                row.insertCell(6).innerHTML = item.branch;
            });
        }

        // Download Report
        function downloadDownlineReport() {
            const associateCode = document.getElementById('associateCode').value.trim();
            const associateName = document.getElementById('associateName').value.trim();
            
            if (!associateCode) {
                alert('Please enter Associate Code first');
                return;
            }
            
            const downline = associatesDownlineDB.filter(a => a.sponsor === associateCode);
            
            if (downline.length === 0) {
                alert('No downline data to download');
                return;
            }
            
            let reportContent = '========================================\n';
            reportContent += 'ASSOCIATE DOWNLINE REPORT\n';
            reportContent += '========================================\n\n';
            reportContent += `Associate Code: ${associateCode}\n`;
            reportContent += `Associate Name: ${associateName || 'N/A'}\n`;
            reportContent += `Total Downline: ${downline.length}\n`;
            reportContent += '\n----------------------------------------\n';
            reportContent += 'CODE | NAME | RANK | DOJ | SPONSOR | SPONSOR NAME | BRANCH\n';
            reportContent += '----------------------------------------\n';
            
            downline.forEach(d => {
                reportContent += `${d.code} | ${d.name} | ${d.rank} | ${d.doj} | ${d.sponsor} | ${d.sponsorName} | ${d.branch}\n`;
            });
            
            reportContent += '----------------------------------------\n';
            reportContent += `Generated on: ${new Date().toLocaleString()}\n`;
            
            // Download as text file
            const blob = new Blob([reportContent], { type: 'text/plain' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `Downline_Report_${associateCode}.txt`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
            
            alert('Report downloaded successfully');
        }

        // Show module
        function showAssociateDownline() {
            document.querySelectorAll('.content-section').forEach(s => s.style.display = 'none');
            document.getElementById('associateDownlineContainer').style.display = 'block';
            
            // Clear fields
            document.getElementById('associateCode').value = '';
            document.getElementById('associateName').value = '';
            document.getElementById('associateRank').value = '';
            document.getElementById('associateBranch').value = '';
            document.getElementById('downlineTableBody').innerHTML = '<tr><td colspan="7" style="text-align:center">Enter Associate Code and click Downline View</td></tr>';
        }

        // Appointment Letter Functions

        // Employee data for table click
        let employeesList = [
            { code: 'C00001', name: 'ARITRA DAS', date: '09/06/2025', address: 'Kolkata', designation: 'Manager', basicSalary: '25000', hra: '8000', conveyance: '2000', pda: '1500', specialAllowance: '3000', medicalRemb: '2000' },
            { code: 'C00018', name: 'SUDESHA GHOSH', date: '11/11/2025', address: 'Howrah', designation: 'Executive', basicSalary: '20000', hra: '6000', conveyance: '1500', pda: '1000', specialAllowance: '2000', medicalRemb: '1500' },
            { code: 'C00019', name: 'SAYANTANI GHOSH', date: '11/11/2025', address: 'Salt Lake', designation: 'Senior Executive', basicSalary: '22000', hra: '7000', conveyance: '1800', pda: '1200', specialAllowance: '2500', medicalRemb: '1800' },
            { code: 'C00020', name: 'SHOVANIKA DEY', date: '11/11/2025', address: 'Barrackpore', designation: 'Associate', basicSalary: '18000', hra: '5000', conveyance: '1200', pda: '800', specialAllowance: '1500', medicalRemb: '1200' },
            { code: 'C00021', name: 'SAYANTAN HALDER', date: '17/11/2025', address: 'Dum Dum', designation: 'Trainee', basicSalary: '15000', hra: '4000', conveyance: '1000', pda: '500', specialAllowance: '1000', medicalRemb: '1000' }
        ];

        // Calculate Earning (readonly field - auto calculated)
        function calculateEarning() {
            const basic = parseFloat(document.getElementById('basicSalary').value) || 0;
            const hra = parseFloat(document.getElementById('hra').value) || 0;
            const conveyance = parseFloat(document.getElementById('conveyance').value) || 0;
            const pda = parseFloat(document.getElementById('pda').value) || 0;
            const specialAllowance = parseFloat(document.getElementById('specialAllowance').value) || 0;
            const medicalRemb = parseFloat(document.getElementById('medicalRemb').value) || 0;
            
            const total = basic + hra + conveyance + pda + specialAllowance + medicalRemb;
            document.getElementById('earning').value = total.toFixed(2);
        }

        // Preview signature image
        function previewSignature(input) {
            const preview = document.getElementById('signaturePreview');
            const uploadArea = document.querySelector('.image-upload-area');
            
            if (input.files && input.files[0]) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    preview.src = e.target.result;
                    preview.style.display = 'block';
                    if (uploadArea) uploadArea.style.display = 'none';
                }
                reader.readAsDataURL(input.files[0]);
            }
        }

        // Populate form from table
        function populateFormFromTable(code) {
            const employee = employeesList.find(e => e.code === code);
            if (employee) {
                document.getElementById('employeeCode').value = employee.code;
                document.getElementById('employeeName').value = employee.name;
                const dateParts = employee.date.split('/');
                document.getElementById('appointmentDate').value = `${dateParts[2]}-${dateParts[1]}-${dateParts[0]}`;
                document.getElementById('employeeAddress').value = employee.address || '';
                document.getElementById('designation').value = employee.designation || '';
                document.getElementById('basicSalary').value = employee.basicSalary || '';
                document.getElementById('hra').value = employee.hra || '';
                document.getElementById('conveyance').value = employee.conveyance || '';
                document.getElementById('pda').value = employee.pda || '';
                document.getElementById('specialAllowance').value = employee.specialAllowance || '';
                document.getElementById('medicalRemb').value = employee.medicalRemb || '';
                
                calculateEarning();
            }
        }

        // Add click event to table rows
        document.addEventListener('DOMContentLoaded', function() {
            const tableRows = document.querySelectorAll('#employeeListTableBody tr');
            tableRows.forEach(row => {
                row.addEventListener('click', function() {
                    const code = this.cells[0].innerText;
                    populateFormFromTable(code);
                });
            });
        });

        // Save Appointment
        function saveAppointment(){
            const employeeCode = document.getElementById('employeeCode').value.trim();
            const employeeName = document.getElementById('employeeName').value.trim();
            const appointmentDate = document.getElementById('appointmentDate').value;
            const designation = document.getElementById('designation').value.trim();
            const printSlip = document.getElementById('printSlip').checked;
            
            if (!employeeCode) {
                alert('Please enter Employee Code');
                return;
            }
            
            if (!employeeName) {
                alert('Please enter Employee Name');
                return;
            }
            
            const formattedDate = new Date(appointmentDate).toLocaleDateString('en-GB');
            
            alert(`Appointment saved for ${employeeName} (${employeeCode})`);
            
            if (printSlip) {
                const printWindow = window.open('', '_blank');
                printWindow.document.write(`
                    <html>
                    <head><title>Appointment Letter - ${employeeName}</title>
                    <style>
                        body { font-family: Arial, sans-serif; padding: 40px; line-height: 1.6; }
                        .container { max-width: 800px; margin: auto; border: 1px solid #ccc; padding: 30px; }
                        h2 { text-align: center; color: #1e4663; }
                        hr { margin: 20px 0; }
                        table { width: 100%; border-collapse: collapse; margin: 15px 0; }
                        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
                        th { background: #f5f5f5; }
                        .footer { margin-top: 50px; text-align: center; }
                        .signature { margin-top: 30px; text-align: right; }
                    </style>
                    </head>
                    <body>
                    <div class="container">
                        <h2>APPOINTMENT LETTER</h2>
                        <hr>
                        <p><strong>Date:</strong> ${formattedDate}</p>
                        <p><strong>To,</strong><br>${employeeName}<br>${document.getElementById('employeeAddress').value}</p>
                        <p>Dear ${employeeName},</p>
                        <p>We are pleased to appoint you as <strong>${designation}</strong> in our organization.</p>
                        <h3>Employee Details:</h3>
                        <p><strong>Employee Code:</strong> ${employeeCode}<br>
                        <strong>Date of Joining:</strong> ${formattedDate}</p>
                        <h3>Salary Details:</h3>
                        <table>
                            <tr><th>Particulars</th><th>Amount (₹)</th></tr>
                            <tr><td>Basic Salary</td><td>${document.getElementById('basicSalary').value || 0}</td></tr>
                            <tr><td>H.R.A.</td><td>${document.getElementById('hra').value || 0}</td></tr>
                            <tr><td>Conveyance</td><td>${document.getElementById('conveyance').value || 0}</td></tr>
                            <tr><td>P.D.A.</td><td>${document.getElementById('pda').value || 0}</td></tr>
                            <tr><td>Special Allowance</td><td>${document.getElementById('specialAllowance').value || 0}</td></tr>
                            <tr><td>Medical Remb.</td><td>${document.getElementById('medicalRemb').value || 0}</td></tr>
                            <tr style="background:#f0f0f0"><td><strong>Total Earning</strong></td><td><strong>${document.getElementById('earning').value || 0}</strong></td></tr>
                        </table>
                        <p>This appointment is subject to the terms and conditions of the company.</p>
                        <div class="signature">
                            <p>Authorized Signatory</p>
                        </div>
                    </div>
                    </body>
                    </html>
                `);
                printWindow.print();
                printWindow.close();
            }
        }

        // Show module
        function showAppointmentLetter() {
            document.querySelectorAll('.content-section').forEach(s => s.style.display = 'none');
            document.getElementById('appointmentLetterContainer').style.display = 'block';
        }

        // Loan Tables Module - Complete

        var loanData = [
            { code:'001', name:'TEST LOAN', minAmt:'10000', maxAmt:'10000', type:'PERSONAL LOAN', minTerm:'12', maxTerm:'200', mode:'WLY', roi:'8', fees:'2', stax:'0' },
            { code:'10K', name:'10K', minAmt:'10000', maxAmt:'10000', type:'PERSONAL LOAN', minTerm:'1', maxTerm:'52', mode:'WLY', roi:'8', fees:'2', stax:'0' },
            { code:'20K', name:'20K', minAmt:'20000', maxAmt:'20000', type:'PERSONAL LOAN', minTerm:'1', maxTerm:'52', mode:'WLY', roi:'8', fees:'2.5', stax:'0' },
            { code:'25K', name:'25K', minAmt:'25000', maxAmt:'25000', type:'PERSONAL LOAN', minTerm:'1', maxTerm:'104', mode:'WLY', roi:'8', fees:'2', stax:'0' },
            { code:'30K', name:'30K', minAmt:'30000', maxAmt:'30000', type:'PERSONAL LOAN', minTerm:'1', maxTerm:'104', mode:'WLY', roi:'8', fees:'2', stax:'0' },
            { code:'35K', name:'35K', minAmt:'35000', maxAmt:'35000', type:'PERSONAL LOAN', minTerm:'1', maxTerm:'104', mode:'WLY', roi:'8', fees:'2', stax:'0' },
            { code:'40K', name:'40K', minAmt:'40000', maxAmt:'40000', type:'PERSONAL LOAN', minTerm:'1', maxTerm:'104', mode:'WLY', roi:'8', fees:'2', stax:'0' },
            { code:'50K', name:'50K', minAmt:'50000', maxAmt:'50000', type:'PERSONAL LOAN', minTerm:'1', maxTerm:'156', mode:'WLY', roi:'8', fees:'2', stax:'0' },
            { code:'60K', name:'60K', minAmt:'60000', maxAmt:'60000', type:'PERSONAL LOAN', minTerm:'1', maxTerm:'156', mode:'WLY', roi:'8', fees:'2', stax:'0' },
            { code:'70K', name:'70K', minAmt:'70000', maxAmt:'70000', type:'PERSONAL LOAN', minTerm:'1', maxTerm:'156', mode:'WLY', roi:'8', fees:'2', stax:'0' },
            { code:'80K', name:'80K', minAmt:'80000', maxAmt:'80000', type:'PERSONAL LOAN', minTerm:'1', maxTerm:'104', mode:'WLY', roi:'8', fees:'2', stax:'0' },
            { code:'P001', name:'PRODUCT LOAN', minAmt:'50000', maxAmt:'100000', type:'PRODUCT LOAN', minTerm:'1', maxTerm:'104', mode:'WLY', roi:'8', fees:'2', stax:'0' }
        ];

        function renderLoanTable() {
            var tbody = document.getElementById('loanTableBody');
            if(!tbody) return;
            tbody.innerHTML = '';
            for(var i=0; i<loanData.length; i++) {
                var row = tbody.insertRow();
                row.insertCell(0).innerHTML = loanData[i].code;
                row.insertCell(1).innerHTML = loanData[i].name;
                row.insertCell(2).innerHTML = loanData[i].minAmt;
                row.insertCell(3).innerHTML = loanData[i].maxAmt;
                row.insertCell(4).innerHTML = loanData[i].type;
                row.insertCell(5).innerHTML = loanData[i].minTerm;
                row.insertCell(6).innerHTML = loanData[i].maxTerm;
                row.insertCell(7).innerHTML = loanData[i].mode;
                row.insertCell(8).innerHTML = loanData[i].roi;
                row.insertCell(9).innerHTML = loanData[i].fees;
                row.insertCell(10).innerHTML = loanData[i].stax;
                row.onclick = (function(item) { return function() { fillForm(item); }; })(loanData[i]);
            }
        }

        function fillForm(item) {
            document.getElementById('loanCode').value = item.code;
            document.getElementById('loanName').value = item.name;
            document.getElementById('loanMode').value = item.mode;
            document.getElementById('minAmount').value = item.minAmt;
            document.getElementById('maxAmount').value = item.maxAmt;
            document.getElementById('minTerm').value = item.minTerm;
            document.getElementById('maxTerm').value = item.maxTerm;
            document.getElementById('minRoi').value = item.roi;
            document.getElementById('maxRoi').value = item.roi;
            document.getElementById('loanType').value = item.type;
            document.getElementById('processingFees').value = item.fees;
        }

        function updatePreview() {
            var prefix = document.getElementById('prefix').value;
            var start = document.getElementById('startFrom').value;
            var digits = parseInt(document.getElementById('digitCount').value);
            document.getElementById('lastNo').value = start;
            var padded = String(start).padStart(digits, '0');
            document.getElementById('previewCode').value = prefix + padded;
        }

        function newLoan() {
            document.getElementById('loanCode').value = '';
            document.getElementById('loanName').value = '';
            document.getElementById('loanMode').value = 'WLY';
            document.getElementById('minAmount').value = '';
            document.getElementById('maxAmount').value = '';
            document.getElementById('minTerm').value = '';
            document.getElementById('maxTerm').value = '';
            document.getElementById('minRoi').value = '';
            document.getElementById('maxRoi').value = '';
            document.getElementById('serviceCharge').value = '';
            document.getElementById('loanType').value = 'PERSONAL LOAN';
            document.getElementById('minAge').value = '';
            document.getElementById('maxAge').value = '';
            document.getElementById('gst').value = '';
            document.getElementById('processingFees').value = '';
            document.getElementById('legalAmt').value = '';
            document.getElementById('insuranceAmt').value = '';
            document.getElementById('lateFine').value = '';
            document.getElementById('gracePeriod').value = '';
            document.getElementById('fineInterest').value = '';
            document.getElementById('emiType').value = 'Fixed EMI';
            document.getElementById('selectLoanType').value = 'GROUP LOAN';
            document.getElementById('securityType').value = '';
            alert('Form cleared for new loan scheme');
        }

        function deleteLoan() {
            var code = document.getElementById('loanCode').value;
            var name = document.getElementById('loanName').value;
            if(!code && !name) { alert('Select a loan scheme first'); return; }
            var searchTerm = code || name;
            if(confirm('Delete loan scheme "' + searchTerm + '"?')) {
                for(var i=0; i<loanData.length; i++) {
                    if(loanData[i].code === code || loanData[i].name === name) {
                        loanData.splice(i,1);
                        break;
                    }
                }
                renderLoanTable();
                newLoan();
                alert('Deleted successfully');
            }
        }

        function saveLoan() {
            var code = document.getElementById('loanCode').value.trim();
            var name = document.getElementById('loanName').value.trim();
            if(!code) { alert('Enter Loan Code'); return; }
            if(!name) { alert('Enter Loan Name'); return; }
            
            var mode = document.getElementById('loanMode').value;
            var minAmt = document.getElementById('minAmount').value || '0';
            var maxAmt = document.getElementById('maxAmount').value || '0';
            var minTerm = document.getElementById('minTerm').value || '1';
            var maxTerm = document.getElementById('maxTerm').value || '12';
            var minRoi = document.getElementById('minRoi').value || '8';
            var maxRoi = document.getElementById('maxRoi').value || '8';
            var loanType = document.getElementById('loanType').value;
            var fees = document.getElementById('processingFees').value || '2';
            var gst = document.getElementById('gst').value || '0';
            var securityType = document.getElementById('securityType').value;
            
            var existing = false;
            for(var i=0; i<loanData.length; i++) {
                if(loanData[i].code === code) {
                    loanData[i].name = name;
                    loanData[i].minAmt = minAmt;
                    loanData[i].maxAmt = maxAmt;
                    loanData[i].type = loanType;
                    loanData[i].minTerm = minTerm;
                    loanData[i].maxTerm = maxTerm;
                    loanData[i].mode = mode;
                    loanData[i].roi = minRoi;
                    loanData[i].fees = fees;
                    loanData[i].stax = gst;
                    existing = true;
                    break;
                }
            }
            if(!existing) {
                loanData.push({
                    code: code,
                    name: name,
                    minAmt: minAmt,
                    maxAmt: maxAmt,
                    type: loanType,
                    minTerm: minTerm,
                    maxTerm: maxTerm,
                    mode: mode,
                    roi: minRoi,
                    fees: fees,
                    stax: gst
                });
            }
            renderLoanTable();
            alert('Loan scheme saved successfully!\nSecurity Type: ' + (securityType || 'None'));
        }

        function showEligibility() {
            var loanName = document.getElementById('loanName').value;
            var minAmt = document.getElementById('minAmount').value;
            var maxTerm = document.getElementById('maxTerm').value;
            var minRoi = document.getElementById('minRoi').value;
            if(!loanName) { alert('Please select a loan scheme from the table'); return; }
            alert('ELIGIBILITY SLAB\n\nLoan Name: ' + loanName + '\nMin Amount: ₹' + minAmt + '\nMax Term: ' + maxTerm + ' months\nROI: ' + minRoi + '%\n\nEligibility Criteria:\n- Age between 21-60 years\n- Min 6 months employment\n- CIBIL Score > 650');
        }

        document.getElementById('prefix').addEventListener('input', updatePreview);
        document.getElementById('startFrom').addEventListener('input', updatePreview);
        document.getElementById('digitCount').addEventListener('change', updatePreview);

        function showLoanTables() {
            var sections = document.querySelectorAll('.content-section');
            for(var i=0; i<sections.length; i++) sections[i].style.display = 'none';
            document.getElementById('loanTablesContainer').style.display = 'block';
            renderLoanTable();
            updatePreview();
        }

        renderLoanTable();
        updatePreview();

        var vendorsData = [
            { code: '001', name: 'SAYONARA', address: '', mobile: '', email: '', gst: '', accountNo: '', bankName: '', ifsc: '' },
            { code: '002', name: 'FINSPERITY LIMITED', address: '109. SANTIGARH, JUBILEE PARK, KOLKATA, WEST BENGAL, INDIA. PIN-700040', mobile: '8444009161, 9830214555', email: 'HO@FINSPERITYLIMITED.COM', gst: '19AAECF5073B1ZT', accountNo: '040105585823', bankName: 'STATE BANK OF INDIA', ifsc: 'SBIN0000040' }
        ];

        function renderVendorTable() {
            var tbody = document.getElementById('vendorTableBody');
            if(!tbody) return;
            tbody.innerHTML = '';
            for(var i=0; i<vendorsData.length; i++) {
                var row = tbody.insertRow();
                row.insertCell(0).innerHTML = vendorsData[i].code;
                row.insertCell(1).innerHTML = vendorsData[i].name;
                row.onclick = (function(v) { return function() { fillVendorForm(v); }; })(vendorsData[i]);
            }
        }

        function fillVendorForm(v) {
            document.getElementById('vendorCode').value = v.code;
            document.getElementById('vendorName').value = v.name;
            document.getElementById('vendorAddress').value = v.address || '';
            document.getElementById('vendorMobile').value = v.mobile || '';
            document.getElementById('vendorEmail').value = v.email || '';
            document.getElementById('gstNumber').value = v.gst || '';
            document.getElementById('accountNo').value = v.accountNo || '';
            document.getElementById('bankName').value = v.bankName || '';
            document.getElementById('ifscCode').value = v.ifsc || '';
        }

        function newVendor() {
            document.getElementById('vendorCode').value = '';
            document.getElementById('vendorName').value = '';
            document.getElementById('vendorAddress').value = '';
            document.getElementById('vendorMobile').value = '';
            document.getElementById('vendorEmail').value = '';
            document.getElementById('gstNumber').value = '';
            document.getElementById('accountNo').value = '';
            document.getElementById('bankName').value = '';
            document.getElementById('ifscCode').value = '';
            alert('Form cleared for new vendor');
        }

        function saveVendor() {
            var code = document.getElementById('vendorCode').value.trim();
            var name = document.getElementById('vendorName').value.trim();
            if(!code) { alert('Enter Vendor Code'); return; }
            if(!name) { alert('Enter Vendor Name'); return; }
            
            var existing = vendorsData.some(function(v) { return v.code === code; });
            if(existing) { alert('Vendor code already exists. Use Update.'); return; }
            
            vendorsData.push({
                code: code,
                name: name,
                address: document.getElementById('vendorAddress').value,
                mobile: document.getElementById('vendorMobile').value,
                email: document.getElementById('vendorEmail').value,
                gst: document.getElementById('gstNumber').value,
                accountNo: document.getElementById('accountNo').value,
                bankName: document.getElementById('bankName').value,
                ifsc: document.getElementById('ifscCode').value
            });
            renderVendorTable();
            alert('Vendor saved successfully');
            newVendor();
        }

        function updateVendor() {
            var code = document.getElementById('vendorCode').value.trim();
            if(!code) { alert('Select a vendor to update'); return; }
            
            for(var i=0; i<vendorsData.length; i++) {
                if(vendorsData[i].code === code) {
                    vendorsData[i].name = document.getElementById('vendorName').value;
                    vendorsData[i].address = document.getElementById('vendorAddress').value;
                    vendorsData[i].mobile = document.getElementById('vendorMobile').value;
                    vendorsData[i].email = document.getElementById('vendorEmail').value;
                    vendorsData[i].gst = document.getElementById('gstNumber').value;
                    vendorsData[i].accountNo = document.getElementById('accountNo').value;
                    vendorsData[i].bankName = document.getElementById('bankName').value;
                    vendorsData[i].ifsc = document.getElementById('ifscCode').value;
                    break;
                }
            }
            renderVendorTable();
            alert('Vendor updated successfully');
        }

        function deleteVendor() {
            var code = document.getElementById('vendorCode').value.trim();
            if(!code) { alert('Select a vendor to delete'); return; }
            if(confirm('Delete vendor ' + code + '?')) {
                for(var i=0; i<vendorsData.length; i++) {
                    if(vendorsData[i].code === code) {
                        vendorsData.splice(i,1);
                        break;
                    }
                }
                renderVendorTable();
                newVendor();
                alert('Vendor deleted successfully');
            }
        }

        function showVendorMaster() {
            var sections = document.querySelectorAll('.content-section');
            for(var i=0; i<sections.length; i++) sections[i].style.display = 'none';
            document.getElementById('vendorMasterContainer').style.display = 'block';
            renderVendorTable();
        }

        renderVendorTable();

        function calculateAge() {
            var dob = document.getElementById('holderDob').value;
            if(dob) {
                var birthDate = new Date(dob);
                var today = new Date();
                var age = today.getFullYear() - birthDate.getFullYear();
                var m = today.getMonth() - birthDate.getMonth();
                if(m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) age--;
                document.getElementById('holderAge').value = age;
            }
        }

        document.getElementById('holderDob').addEventListener('change', calculateAge);
        document.getElementById('primarySecurity').addEventListener('change', function() {
            document.getElementById('primaryFileName').innerText = this.files[0]?.name || 'No file chosen';
        });
        document.getElementById('secondarySecurity').addEventListener('change', function() {
            document.getElementById('secondaryFileName').innerText = this.files[0]?.name || 'No file chosen';
        });

        function newLoanEntry() {
            document.getElementById('applicantName').value = '';
            document.getElementById('loanId').value = '';
            document.getElementById('formMember').value = '';
            document.getElementById('processingFee').value = '';
            document.getElementById('gstAmt').value = '';
            document.getElementById('legalAmt').value = '';
            document.getElementById('loanDate').value = new Date().toISOString().slice(0,10);
            document.getElementById('insuranceAmt').value = '';
            document.getElementById('previousLoan').value = '';
            document.getElementById('holderDob').value = new Date().toISOString().slice(0,10);
            document.getElementById('holderAge').value = '';
            document.getElementById('relation').value = '';
            document.getElementById('address').value = '';
            document.getElementById('pinCode').value = '';
            document.getElementById('loanAmount').value = '';
            document.getElementById('chequeNo').value = '';
            document.getElementById('bankBranch').value = '';
            document.getElementById('guaranteeChequeNo').value = '';
            document.getElementById('guaranteeBankBranch').value = '';
            document.getElementById('primarySecurity').value = '';
            document.getElementById('secondarySecurity').value = '';
            document.getElementById('primaryFileName').innerText = 'No file chosen';
            document.getElementById('secondaryFileName').innerText = 'No file chosen';
            alert('Form cleared for new loan entry');
        }

        function saveLoanEntry() {
            var applicantName = document.getElementById('applicantName').value.trim();
            var loanAmount = document.getElementById('loanAmount').value.trim();
            if(!applicantName) { alert('Enter Applicant Name'); return; }
            if(!loanAmount) { alert('Enter Loan Amount'); return; }
            
            var loanData = {
                applicantName: applicantName,
                loanId: document.getElementById('loanId').value,
                formMember: document.getElementById('formMember').value,
                processingFee: document.getElementById('processingFee').value,
                gstAmt: document.getElementById('gstAmt').value,
                legalAmt: document.getElementById('legalAmt').value,
                loanDate: document.getElementById('loanDate').value,
                insuranceAmt: document.getElementById('insuranceAmt').value,
                previousLoan: document.getElementById('previousLoan').value,
                holderDob: document.getElementById('holderDob').value,
                holderAge: document.getElementById('holderAge').value,
                relation: document.getElementById('relation').value,
                address: document.getElementById('address').value,
                pinCode: document.getElementById('pinCode').value,
                loanName: document.getElementById('loanName').value,
                loanTerm: document.getElementById('loanTerm').value,
                loanAmount: loanAmount,
                interestType: document.getElementById('interestType').value,
                chequeDate: document.getElementById('chequeDate').value,
                chequeNo: document.getElementById('chequeNo').value,
                bankBranch: document.getElementById('bankBranch').value,
                guaranteeDate: document.getElementById('guaranteeDate').value,
                guaranteeChequeDate: document.getElementById('guaranteeChequeDate').value,
                guaranteeChequeNo: document.getElementById('guaranteeChequeNo').value,
                guaranteeBankBranch: document.getElementById('guaranteeBankBranch').value
            };
            console.log('Loan Entry Saved:', loanData);
            alert('Loan entry saved successfully for ' + applicantName);
        }

        function showLoanEntryMember() {
            var sections = document.querySelectorAll('.content-section');
            for(var i=0; i<sections.length; i++) sections[i].style.display = 'none';
            document.getElementById('loanEntryMemberContainer').style.display = 'block';
        }

        // Group data
        var groupsData = {
            GRP001: { name: 'Women Empowerment Group', head: 'RADHIKA DEVI', foCode: 'FO001', address: '123, Women Colony, Kolkata', phone: '9876543210', state: 'West Bengal', pin: '700001', members: [
                { code: 'M001', name: 'RADHIKA DEVI', loanAmount: '25000', emi: '2500', processingFees: '500', gst: '90', legalAmt: '200', amount: '25790', loanId: 'LN001', isOk: false },
                { code: 'M002', name: 'SARITA SINGH', loanAmount: '20000', emi: '2000', processingFees: '400', gst: '72', legalAmt: '160', amount: '20632', loanId: 'LN002', isOk: false },
                { code: 'M003', name: 'MEENA KUMARI', loanAmount: '15000', emi: '1500', processingFees: '300', gst: '54', legalAmt: '120', amount: '15474', loanId: 'LN003', isOk: false }
            ]},
            GRP002: { name: 'Farmer Producer Group', head: 'RAMESH SINGH', foCode: 'FO002', address: '456, Village Road, Bardhaman', phone: '9876543211', state: 'West Bengal', pin: '713101', members: [
                { code: 'M101', name: 'RAMESH SINGH', loanAmount: '50000', emi: '5000', processingFees: '1000', gst: '180', legalAmt: '400', amount: '51580', loanId: 'LN101', isOk: false },
                { code: 'M102', name: 'SURESH YADAV', loanAmount: '30000', emi: '3000', processingFees: '600', gst: '108', legalAmt: '240', amount: '30948', loanId: 'LN102', isOk: false }
            ]},
            GRP003: { name: 'Self Help Group', head: 'LAKSHMI NARAYAN', foCode: 'FO003', address: '789, SHG Colony, Howrah', phone: '9876543212', state: 'West Bengal', pin: '711101', members: [
                { code: 'M201', name: 'LAKSHMI NARAYAN', loanAmount: '35000', emi: '3500', processingFees: '700', gst: '126', legalAmt: '280', amount: '36106', loanId: 'LN201', isOk: false },
                { code: 'M202', name: 'GEETA DEVI', loanAmount: '22000', emi: '2200', processingFees: '440', gst: '79', legalAmt: '176', amount: '22695', loanId: 'LN202', isOk: false },
                { code: 'M203', name: 'ANITA SINGH', loanAmount: '18000', emi: '1800', processingFees: '360', gst: '65', legalAmt: '144', amount: '18569', loanId: 'LN203', isOk: false }
            ]}
        };

        function loadGroupDetails() {
            var groupId = document.getElementById('groupId').value;
            if(!groupId || groupId === '') {
                document.getElementById('groupHead').value = '';
                document.getElementById('groupName').value = '';
                document.getElementById('address').value = '';
                document.getElementById('phoneNo').value = '';
                document.getElementById('state').value = '';
                document.getElementById('pin').value = '';
                document.getElementById('memberLoanTableBody').innerHTML = '<tr><td colspan="10" style="text-align:center">Select a group to view members</td></tr>';
                return;
            }
            
            var group = groupsData[groupId];
            if(group) {
                document.getElementById('groupHead').value = group.head;
                document.getElementById('groupName').value = group.name;
                document.getElementById('address').value = group.address;
                document.getElementById('phoneNo').value = group.phone;
                document.getElementById('state').value = group.state;
                document.getElementById('pin').value = group.pin;
                document.getElementById('foCode').value = group.foCode;
                renderMemberTable(group.members);
            }
        }

        function renderMemberTable(members) {
            var tbody = document.getElementById('memberLoanTableBody');
            if(!tbody) return;
            tbody.innerHTML = '';
            for(var i=0; i<members.length; i++) {
                var m = members[i];
                var row = tbody.insertRow();
                row.insertCell(0).innerHTML = m.code;
                row.insertCell(1).innerHTML = m.name;
                row.insertCell(2).innerHTML = '<input type="text" value="' + m.loanAmount + '" class="loan-amount" data-idx="' + i + '" onchange="updateMemberValue(' + i + ', \'loanAmount\', this.value)">';
                row.insertCell(3).innerHTML = '<input type="text" value="' + m.emi + '" class="emi-amount" data-idx="' + i + '" onchange="updateMemberValue(' + i + ', \'emi\', this.value)">';
                row.insertCell(4).innerHTML = '<input type="text" value="' + m.processingFees + '" class="proc-fees" data-idx="' + i + '" onchange="updateMemberValue(' + i + ', \'processingFees\', this.value)">';
                row.insertCell(5).innerHTML = '<input type="text" value="' + m.gst + '" class="gst-amt" data-idx="' + i + '" onchange="updateMemberValue(' + i + ', \'gst\', this.value)">';
                row.insertCell(6).innerHTML = '<input type="text" value="' + m.legalAmt + '" class="legal-amt" data-idx="' + i + '" onchange="updateMemberValue(' + i + ', \'legalAmt\', this.value)">';
                row.insertCell(7).innerHTML = '<input type="text" value="' + m.amount + '" class="total-amount" data-idx="' + i + '" readonly style="background:#e9ecef">';
                row.insertCell(8).innerHTML = '<input type="text" value="' + m.loanId + '" class="loan-id" data-idx="' + i + '" onchange="updateMemberValue(' + i + ', \'loanId\', this.value)">';
                row.insertCell(9).innerHTML = '<input type="checkbox" class="ok-checkbox" data-idx="' + i + '" ' + (m.isOk ? 'checked' : '') + ' onchange="updateMemberValue(' + i + ', \'isOk\', this.checked)">';
            }
        }

        function updateMemberValue(idx, field, value) {
            var groupId = document.getElementById('groupId').value;
            if(!groupId || !groupsData[groupId]) return;
            if(field === 'isOk') {
                groupsData[groupId].members[idx].isOk = value;
            } else if(field === 'loanAmount') {
                groupsData[groupId].members[idx].loanAmount = value;
                recalcMemberAmount(idx);
            } else if(field === 'emi') {
                groupsData[groupId].members[idx].emi = value;
            } else if(field === 'processingFees') {
                groupsData[groupId].members[idx].processingFees = value;
                recalcMemberAmount(idx);
            } else if(field === 'gst') {
                groupsData[groupId].members[idx].gst = value;
                recalcMemberAmount(idx);
            } else if(field === 'legalAmt') {
                groupsData[groupId].members[idx].legalAmt = value;
                recalcMemberAmount(idx);
            } else if(field === 'loanId') {
                groupsData[groupId].members[idx].loanId = value;
            }
        }

        function recalcMemberAmount(idx) {
            var groupId = document.getElementById('groupId').value;
            if(!groupId || !groupsData[groupId]) return;
            var m = groupsData[groupId].members[idx];
            var loan = parseFloat(m.loanAmount) || 0;
            var proc = parseFloat(m.processingFees) || 0;
            var gstVal = parseFloat(m.gst) || 0;
            var legal = parseFloat(m.legalAmt) || 0;
            var total = loan + proc + gstVal + legal;
            m.amount = total.toFixed(2);
            var row = document.querySelector('#memberLoanTableBody tr:nth-child(' + (idx+1) + ')');
            if(row) {
                var amountCell = row.cells[7];
                if(amountCell) amountCell.innerHTML = '<input type="text" value="' + m.amount + '" class="total-amount" readonly style="background:#e9ecef">';
            }
        }

        function newGroupLoan() {
            document.getElementById('groupId').value = '';
            document.getElementById('groupHead').value = '';
            document.getElementById('groupName').value = '';
            document.getElementById('foCode').value = '';
            document.getElementById('loanDate').value = new Date().toISOString().slice(0,10);
            document.getElementById('grtCloseDate').value = new Date().toISOString().slice(0,10);
            document.getElementById('address').value = '';
            document.getElementById('phoneNo').value = '';
            document.getElementById('state').value = '';
            document.getElementById('pin').value = '';
            document.getElementById('branch').value = 'HEAD OFFICE - 001';
            document.getElementById('productName').value = 'TEST LOAN';
            document.getElementById('interestType').value = 'FLAT';
            document.getElementById('loanTerm').value = '12';
            document.getElementById('loanAmount').value = '0';
            document.getElementById('roi').value = '8';
            document.getElementById('mode').value = 'WLY';
            document.getElementById('processingFees').value = '0';
            document.getElementById('legalAmount').value = '0';
            document.getElementById('gst').value = '0';
            document.getElementById('insuranceAmount').value = '0';
            document.getElementById('memberLoanTableBody').innerHTML = '<tr><td colspan="10" style="text-align:center">Select a group to view members</td></tr>';
            alert('Form cleared for new group loan');
        }

        function deleteLoan() {
            var groupId = document.getElementById('groupId').value;
            if(!groupId) { alert('Select a group first'); return; }
            if(confirm('Delete loan entry for group ' + groupId + '?')) {
                alert('Loan entry deleted successfully');
                newGroupLoan();
            }
        }

        function submitGroupLoan() {
            var groupId = document.getElementById('groupId').value;
            if(!groupId) { alert('Select a group'); return; }
            var group = groupsData[groupId];
            if(!group) { alert('Group not found'); return; }
            
            var loanData = {
                groupId: groupId,
                groupName: group.name,
                groupHead: group.head,
                loanDate: document.getElementById('loanDate').value,
                grtCloseDate: document.getElementById('grtCloseDate').value,
                branch: document.getElementById('branch').value,
                productName: document.getElementById('productName').value,
                interestType: document.getElementById('interestType').value,
                loanTerm: document.getElementById('loanTerm').value,
                loanAmount: document.getElementById('loanAmount').value,
                roi: document.getElementById('roi').value,
                mode: document.getElementById('mode').value,
                processingFees: document.getElementById('processingFees').value,
                legalAmount: document.getElementById('legalAmount').value,
                gst: document.getElementById('gst').value,
                insuranceAmount: document.getElementById('insuranceAmount').value,
                members: group.members
            };
            console.log('Group Loan Submitted:', loanData);
            alert('Group loan submitted successfully for ' + group.name);
        }

        document.getElementById('groupId').addEventListener('change', loadGroupDetails);

        function showGroupCashLoan() {
            var sections = document.querySelectorAll('.content-section');
            for(var i=0; i<sections.length; i++) sections[i].style.display = 'none';
            document.getElementById('groupCashLoanContainer').style.display = 'block';
        }

        //Loan Search
        var loanRecords = [
            { sno: 1, loanId: 'LN001', reqDate: '2026-04-01', memberId: 'M001', memberName: 'RADHIKA DEVI', scheme: 'TEST LOAN', amount: '25000', emi: '2500', approvalDate: '2026-04-05', status: 'UnPaid', branch: 'HEAD OFFICE - 001' },
            { sno: 2, loanId: 'LN002', reqDate: '2026-04-02', memberId: 'M002', memberName: 'SARITA SINGH', scheme: 'TEST LOAN', amount: '20000', emi: '2000', approvalDate: '2026-04-06', status: 'UnPaid', branch: 'HEAD OFFICE - 001' },
            { sno: 3, loanId: 'LN003', reqDate: '2026-04-03', memberId: 'M003', memberName: 'MEENA KUMARI', scheme: 'GOLD LOAN', amount: '15000', emi: '1500', approvalDate: '2026-04-07', status: 'Paid', branch: 'BRANCH - 002' },
            { sno: 4, loanId: 'LN101', reqDate: '2026-04-04', memberId: 'M101', memberName: 'RAMESH SINGH', scheme: 'TEST LOAN', amount: '50000', emi: '5000', approvalDate: '2026-04-08', status: 'UnPaid', branch: 'HEAD OFFICE - 001' },
            { sno: 5, loanId: 'LN102', reqDate: '2026-04-05', memberId: 'M102', memberName: 'SURESH YADAV', scheme: 'PERSONAL LOAN', amount: '30000', emi: '3000', approvalDate: '2026-04-09', status: 'Partial', branch: 'BRANCH - 003' }
        ];

        function renderLoanSearchTable(data) {
            var tbody = document.getElementById('loanSearchTableBody');
            if(!tbody) return;
            if(!data || data.length === 0) {
                tbody.innerHTML = '<tr><td colspan="11" style="text-align:center">No records found</td></tr>';
                return;
            }
            tbody.innerHTML = '';
            for(var i=0; i<data.length; i++) {
                var row = tbody.insertRow();
                row.insertCell(0).innerHTML = data[i].sno;
                row.insertCell(1).innerHTML = data[i].loanId;
                row.insertCell(2).innerHTML = data[i].reqDate;
                row.insertCell(3).innerHTML = data[i].memberId;
                row.insertCell(4).innerHTML = data[i].memberName;
                row.insertCell(5).innerHTML = data[i].scheme;
                row.insertCell(6).innerHTML = data[i].amount;
                row.insertCell(7).innerHTML = data[i].emi;
                row.insertCell(8).innerHTML = data[i].approvalDate;
                row.insertCell(9).innerHTML = '<span class="status-' + data[i].status.toLowerCase() + '">' + data[i].status + '</span>';
                row.insertCell(10).innerHTML = '<button class="pay-btn" onclick="payLoan(\'' + data[i].loanId + '\')">Pay</button>';
            }
        }

        function searchLoans() {
            var searchText = document.getElementById('searchText').value.toLowerCase();
            var searchDate = document.getElementById('searchDate').value;
            var statusFilter = document.getElementById('statusFilter').value;
            var branchFilter = document.getElementById('branchFilter').value;
            
            var filtered = loanRecords.filter(function(loan) {
                var matchText = true;
                var matchDate = true;
                var matchStatus = true;
                var matchBranch = true;
                
                if(searchText) {
                    matchText = loan.loanId.toLowerCase().includes(searchText) || loan.memberName.toLowerCase().includes(searchText);
                }
                if(searchDate) {
                    matchDate = loan.reqDate === searchDate;
                }
                if(statusFilter && statusFilter !== 'All') {
                    matchStatus = loan.status === statusFilter;
                }
                if(branchFilter && branchFilter !== 'All Branch') {
                    matchBranch = loan.branch === branchFilter;
                }
                return matchText && matchDate && matchStatus && matchBranch;
            });
            
            filtered.forEach(function(loan, idx) { loan.sno = idx + 1; });
            renderLoanSearchTable(filtered);
            alert('Found ' + filtered.length + ' record(s)');
        }

        function payLoan(loanId) {
            alert('Proceed to payment for Loan ID: ' + loanId);
        }

        function closeLoanSearch() {
            document.getElementById('searchText').value = '';
            document.getElementById('searchDate').value = '';
            document.getElementById('statusFilter').value = 'UnPaid';
            document.getElementById('branchFilter').value = 'All Branch';
            renderLoanSearchTable(loanRecords);
            alert('Search closed. All records displayed.');
        }

        function showLoanSearch() {
            var sections = document.querySelectorAll('.content-section');
            for(var i=0; i<sections.length; i++) sections[i].style.display = 'none';
            document.getElementById('loanSearchContainer').style.display = 'block';
            renderLoanSearchTable(loanRecords);
        }

        renderLoanSearchTable(loanRecords);

        var groupPaymentData = {
            GRP001: { name: 'Women Empowerment Group', foName: 'RADHIKA DEVI', state: 'West Bengal', pin: '700001', address: '123, Women Colony, Kolkata', phone: '9876543210', loanAmount: '60000', emi: '6000', members: [
                { code: 'M001', name: 'RADHIKA DEVI', loanAmount: '25000', emi: '2500', procFees: '500', gst: '90', legalAmt: '200', amount: '25790', loanId: 'LN001', iok: false },
                { code: 'M002', name: 'SARITA SINGH', loanAmount: '20000', emi: '2000', procFees: '400', gst: '72', legalAmt: '160', amount: '20632', loanId: 'LN002', iok: false },
                { code: 'M003', name: 'MEENA KUMARI', loanAmount: '15000', emi: '1500', procFees: '300', gst: '54', legalAmt: '120', amount: '15474', loanId: 'LN003', iok: false }
            ]},
            GRP002: { name: 'Farmer Producer Group', foName: 'RAMESH SINGH', state: 'West Bengal', pin: '713101', address: '456, Village Road, Bardhaman', phone: '9876543211', loanAmount: '80000', emi: '8000', members: [
                { code: 'M101', name: 'RAMESH SINGH', loanAmount: '50000', emi: '5000', procFees: '1000', gst: '180', legalAmt: '400', amount: '51580', loanId: 'LN101', iok: false },
                { code: 'M102', name: 'SURESH YADAV', loanAmount: '30000', emi: '3000', procFees: '600', gst: '108', legalAmt: '240', amount: '30948', loanId: 'LN102', iok: false }
            ]}
        };

        function loadGroupForPayment() {
            var groupId = document.getElementById('memberId').value;
            if(!groupId) return;
            var group = groupPaymentData[groupId];
            if(group) {
                document.getElementById('groupName').value = group.name;
                document.getElementById('foName').value = group.foName;
                document.getElementById('state').value = group.state;
                document.getElementById('pin').value = group.pin;
                document.getElementById('address').value = group.address;
                document.getElementById('phoneNo').value = group.phone;
                document.getElementById('loanAmount').value = group.loanAmount;
                document.getElementById('emi').value = group.emi;
                renderPaymentMemberTable(group.members);
            }
        }

        function renderPaymentMemberTable(members) {
            var tbody = document.getElementById('paymentMemberTableBody');
            if(!tbody) return;
            tbody.innerHTML = '';
            for(var i=0; i<members.length; i++) {
                var m = members[i];
                var row = tbody.insertRow();
                row.insertCell(0).innerHTML = m.code;
                row.insertCell(1).innerHTML = m.name;
                row.insertCell(2).innerHTML = '<input type="text" value="' + m.loanAmount + '">';
                row.insertCell(3).innerHTML = '<input type="text" value="' + m.emi + '">';
                row.insertCell(4).innerHTML = '<input type="text" value="' + m.procFees + '">';
                row.insertCell(5).innerHTML = '<input type="text" value="' + m.gst + '">';
                row.insertCell(6).innerHTML = '<input type="text" value="' + m.legalAmt + '">';
                row.insertCell(7).innerHTML = '<input type="text" value="' + m.amount + '">';
                row.insertCell(8).innerHTML = '<input type="text" value="' + m.loanId + '">';
                row.insertCell(9).innerHTML = '<input type="checkbox" ' + (m.iok ? 'checked' : '') + '>';
            }
        }

        function setPaymentStatus(status) {
            alert('Payment status set to: ' + status);
        }

        function processPayment() {
            var groupId = document.getElementById('memberId').value;
            if(!groupId) { alert('Select a group first'); return; }
            alert('Payment processed successfully for group: ' + groupId);
        }

        function revertPayment() {
            var groupId = document.getElementById('memberId').value;
            if(!groupId) { alert('Select a group first'); return; }
            if(confirm('Revert payment for this group?')) {
                alert('Payment reverted successfully');
            }
        }

        function showLoanPaymentGroup() {
            var sections = document.querySelectorAll('.content-section');
            for(var i=0; i<sections.length; i++) sections[i].style.display = 'none';
            document.getElementById('loanPaymentGroupContainer').style.display = 'block';
        }

        //Collection Scheduler
        var schedulerGroupData = {
            GRP001: {
                groupName: 'Women Empowerment Group',
                branchCode: 'BR001',
                branchName: 'HEAD OFFICE - 001',
                centerCode: 'CTR001',
                centerName: 'CENTER A',
                loanTerm: '12 months',
                members: [
                    { code: 'M001', name: 'RADHIKA DEVI', loanId: 'LN001', loanAmount: '25000', emi: '2500' },
                    { code: 'M002', name: 'SARITA SINGH', loanId: 'LN002', loanAmount: '20000', emi: '2000' },
                    { code: 'M003', name: 'MEENA KUMARI', loanId: 'LN003', loanAmount: '15000', emi: '1500' }
                ]
            },
            GRP002: {
                groupName: 'Farmer Producer Group',
                branchCode: 'BR002',
                branchName: 'BRANCH - 002',
                centerCode: 'CTR002',
                centerName: 'CENTER B',
                loanTerm: '24 months',
                members: [
                    { code: 'M101', name: 'RAMESH SINGH', loanId: 'LN101', loanAmount: '50000', emi: '5000' },
                    { code: 'M102', name: 'SURESH YADAV', loanId: 'LN102', loanAmount: '30000', emi: '3000' }
                ]
            },
            GRP003: {
                groupName: 'Self Help Group',
                branchCode: 'BR003',
                branchName: 'BRANCH - 003',
                centerCode: 'CTR003',
                centerName: 'CENTER C',
                loanTerm: '18 months',
                members: [
                    { code: 'M201', name: 'LAKSHMI NARAYAN', loanId: 'LN201', loanAmount: '35000', emi: '3500' },
                    { code: 'M202', name: 'GEETA DEVI', loanId: 'LN202', loanAmount: '22000', emi: '2200' },
                    { code: 'M203', name: 'ANITA SINGH', loanId: 'LN203', loanAmount: '18000', emi: '1800' }
                ]
            }
        };

        function loadGroupSchedulerData() {
            var groupCode = document.getElementById('groupCode').value;
            if (!groupCode) {
                clearSchedulerForm();
                return;
            }
            
            var group = schedulerGroupData[groupCode];
            if (group) {
                document.getElementById('groupName').value = group.groupName;
                document.getElementById('branchCode').value = group.branchCode;
                document.getElementById('branchName').value = group.branchName;
                document.getElementById('centerCode').value = group.centerCode;
                document.getElementById('centerName').value = group.centerName;
                document.getElementById('loanTerm').value = group.loanTerm;
                renderSchedulerMemberTable(group.members);
            }
        }

        function renderSchedulerMemberTable(members) {
            var tbody = document.getElementById('schedulerMemberTableBody');
            if (!tbody) return;
            
            if (!members || members.length === 0) {
                tbody.innerHTML = '<tr><td colspan="7" style="text-align:center">No members found</td></tr>';
                return;
            }
            
            var payDate = document.getElementById('collectionStartDate').value;
            var term = document.getElementById('loanTerm').value;
            
            tbody.innerHTML = '';
            for (var i = 0; i < members.length; i++) {
                var m = members[i];
                var row = tbody.insertRow();
                row.insertCell(0).innerHTML = m.code;
                row.insertCell(1).innerHTML = m.name;
                row.insertCell(2).innerHTML = m.loanId;
                row.insertCell(3).innerHTML = m.loanAmount;
                row.insertCell(4).innerHTML = '<input type="date" value="' + payDate + '" class="pay-date-input" data-idx="' + i + '">';
                row.insertCell(5).innerHTML = '<input type="text" value="' + term + '" class="term-input" data-idx="' + i + '">';
                row.insertCell(6).innerHTML = '<input type="text" value="' + m.emi + '" class="emi-input" data-idx="' + i + '">';
            }
        }

        function clearSchedulerForm() {
            document.getElementById('groupName').value = '';
            document.getElementById('branchCode').value = '';
            document.getElementById('branchName').value = '';
            document.getElementById('centerCode').value = '';
            document.getElementById('centerName').value = '';
            document.getElementById('loanTerm').value = '';
            document.getElementById('schedulerMemberTableBody').innerHTML = '<tr><td colspan="7" style="text-align:center">Select a group to view members</td></tr>';
        }

        function confirmAndGenerate() {
            var groupCode = document.getElementById('groupCode').value;
            if (!groupCode) {
                alert('Please select a Group Code');
                return;
            }
            
            var groupName = document.getElementById('groupName').value;
            var branchCode = document.getElementById('branchCode').value;
            var branchName = document.getElementById('branchName').value;
            var centerCode = document.getElementById('centerCode').value;
            var centerName = document.getElementById('centerName').value;
            var collector = document.getElementById('collector').value;
            var loanMode = document.getElementById('loanMode').value;
            var collectionStartDate = document.getElementById('collectionStartDate').value;
            var dayOfWeek = document.getElementById('dayOfWeek').value;
            var loanTerm = document.getElementById('loanTerm').value;
            var loanPaidDate = document.getElementById('loanPaidDate').value;
            
            if (!collector) {
                alert('Please enter Collector name');
                return;
            }
            
            // Get member data from table
            var members = [];
            var tableRows = document.getElementById('schedulerMemberTableBody').rows;
            for (var i = 0; i < tableRows.length; i++) {
                var cells = tableRows[i].cells;
                members.push({
                    memberCode: cells[0].innerHTML,
                    memberName: cells[1].innerHTML,
                    loanId: cells[2].innerHTML,
                    loanAmount: cells[3].innerHTML,
                    payDate: cells[4].querySelector('input')?.value || collectionStartDate,
                    term: cells[5].querySelector('input')?.value || loanTerm,
                    emi: cells[6].querySelector('input')?.value || '0'
                });
            }
            
            var scheduleData = {
                groupCode: groupCode,
                groupName: groupName,
                branchCode: branchCode,
                branchName: branchName,
                centerCode: centerCode,
                centerName: centerName,
                collector: collector,
                loanMode: loanMode,
                collectionStartDate: collectionStartDate,
                dayOfWeek: dayOfWeek,
                loanTerm: loanTerm,
                loanPaidDate: loanPaidDate,
                members: members,
                generatedOn: new Date().toLocaleString()
            };
            
            console.log('Payment Schedule Generated:', scheduleData);
            
            // Show confirmation message
            var message = '✅ PAYMENT SCHEDULE GENERATED SUCCESSFULLY!\n\n';
            message += '━━━━━━━━━━━━━━━━━━━━━\n';
            message += 'Group: ' + groupName + ' (' + groupCode + ')\n';
            message += 'Branch: ' + branchName + '\n';
            message += 'Center: ' + centerName + '\n';
            message += 'Collector: ' + collector + '\n';
            message += 'Loan Mode: ' + loanMode + '\n';
            message += 'Start Date: ' + collectionStartDate + '\n';
            message += 'Day of Week: ' + dayOfWeek + '\n';
            message += '━━━━━━━━━━━━━━━━━━━━━\n';
            message += 'Total Members: ' + members.length + '\n';
            message += 'Total Loan Amount: ' + members.reduce(function(sum, m) { return sum + parseFloat(m.loanAmount || 0); }, 0) + '\n';
            message += '━━━━━━━━━━━━━━━━━━━━━\n';
            message += 'Schedule has been generated successfully!';
            
            alert(message);
        }

        // Update pay dates when collection start date changes
        document.getElementById('collectionStartDate').addEventListener('change', function() {
            var payDateInputs = document.querySelectorAll('.pay-date-input');
            for (var i = 0; i < payDateInputs.length; i++) {
                payDateInputs[i].value = this.value;
            }
        });

        // Update term when loan term changes
        document.getElementById('loanTerm').addEventListener('change', function() {
            var termInputs = document.querySelectorAll('.term-input');
            for (var i = 0; i < termInputs.length; i++) {
                termInputs[i].value = this.value;
            }
        });

        function showPaymentScheduler() {
            var sections = document.querySelectorAll('.content-section');
            for (var i = 0; i < sections.length; i++) {
                sections[i].style.display = 'none';
            }
            document.getElementById('paymentSchedulerContainer').style.display = 'block';
        }

        // Product Loan Entry Module - Complete

        function calculateProductLoanAge() {
            var dob = document.getElementById('pleHolderDob').value;
            var ageField = document.getElementById('pleHolderAge');
            if (dob && ageField) {
                var birthDate = new Date(dob);
                var today = new Date();
                var age = today.getFullYear() - birthDate.getFullYear();
                var monthDiff = today.getMonth() - birthDate.getMonth();
                if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
                    age--;
                }
                ageField.value = age;
            }
        }

        function triggerPrimarySecurity() {
            document.getElementById('plePrimarySecurity').click();
        }

        document.getElementById('plePrimarySecurity').addEventListener('change', function() {
            var fileName = this.files[0] ? this.files[0].name : 'No file chosen';
            document.getElementById('plePrimaryFileName').innerText = fileName;
        });

        function fillProductData() {
            var productName = document.getElementById('pleProductName').value;
            var itemName = document.getElementById('pleItemName').value;
            var vendorName = document.getElementById('pleVendorName').value;
            alert('Product Data Filled!\n\nProduct Name: ' + productName + '\nItem Name: ' + itemName + '\nVendor: ' + vendorName);
        }

        function resetProductLoanForm() {
            // Search Details
            document.getElementById('pleApplicantName').value = '';
            document.getElementById('pleLoanId').value = '';
            document.getElementById('pleMemberId').value = '';
            document.getElementById('pleFormNo').value = '';
            document.getElementById('pleLoanDate').value = new Date().toISOString().slice(0,10);
            document.getElementById('pleLoanAmount').value = '';
            
            // Deductions
            document.getElementById('pleProcessingFee').value = '';
            document.getElementById('pleGstAmt').value = '';
            document.getElementById('pleLegalAmt').value = '';
            document.getElementById('pleInsuranceAmt').value = '';
            
            // 1st Guarantor
            document.getElementById('pleGuarantor1MemberNo').value = '';
            document.getElementById('pleGuarantor1Name').value = '';
            document.getElementById('pleGuarantor1Guardian').value = '';
            document.getElementById('pleGuarantor1Address').value = '';
            document.getElementById('pleGuarantor1Phone').value = '';
            document.getElementById('pleGuarantor1Pan').value = '';
            document.getElementById('pleGuarantor1Aadhar').value = '';
            document.getElementById('pleGuarantor1Relation').value = '';
            
            // 2nd Guarantor
            document.getElementById('pleGuarantor2MemberNo').value = '';
            document.getElementById('pleGuarantor2Name').value = '';
            document.getElementById('pleGuarantor2Guardian').value = '';
            document.getElementById('pleGuarantor2Address').value = '';
            document.getElementById('pleGuarantor2Phone').value = '';
            document.getElementById('pleGuarantor2Pan').value = '';
            document.getElementById('pleGuarantor2Aadhar').value = '';
            document.getElementById('pleGuarantor2Relation').value = '';
            
            // 3rd Guarantor
            document.getElementById('pleGuarantor3MemberNo').value = '';
            document.getElementById('pleGuarantor3Name').value = '';
            document.getElementById('pleGuarantor3Guardian').value = '';
            document.getElementById('pleGuarantor3Address').value = '';
            document.getElementById('pleGuarantor3Phone').value = '';
            document.getElementById('pleGuarantor3Pan').value = '';
            document.getElementById('pleGuarantor3Aadhar').value = '';
            document.getElementById('pleGuarantor3Relation').value = '';
            
            // Previous Loan
            document.getElementById('plePreviousLoan').value = '';
            
            // Personal Info
            document.getElementById('pleHolderDob').value = new Date().toISOString().slice(0,10);
            document.getElementById('pleHolderAge').value = '';
            document.getElementById('pleGuardianName').value = '';
            document.getElementById('plePhoneNo').value = '';
            document.getElementById('pleAddress').value = '';
            document.getElementById('plePinCode').value = '';
            document.getElementById('pleRelation').value = '';
            
            // Member Cheque Details
            document.getElementById('pleMemberChequeDate').value = new Date().toISOString().slice(0,10);
            document.getElementById('pleMemberChequeNo').value = '';
            document.getElementById('pleMemberBankBranch').value = '';
            
            // Guarantor Cheque Details
            document.getElementById('pleGuarantorChequeDate').value = new Date().toISOString().slice(0,10);
            document.getElementById('pleGuarantorChequeNo').value = '';
            document.getElementById('pleGuarantorBankBranch').value = '';
            
            // Scheme Details
            document.getElementById('pleDownPayment').value = '';
            document.getElementById('pleAvailableStock').value = '';
            document.getElementById('pleLoanTerm').value = '';
            document.getElementById('pleRoiEmi').value = '';
            document.getElementById('pleStax').value = '';
            document.getElementById('pleCollectorCode').value = '';
            document.getElementById('plePurpose').value = '';
            
            // Primary Security
            document.getElementById('plePrimarySecurity').value = '';
            document.getElementById('plePrimaryFileName').innerText = 'No file chosen';
            
            alert('Form cleared for new loan entry');
        }

        function saveProductLoanEntry() {
            var applicantName = document.getElementById('pleApplicantName').value.trim();
            var loanAmount = document.getElementById('pleLoanAmount').value.trim();
            
            if (!applicantName) {
                alert('Please enter Applicant Name');
                return;
            }
            if (!loanAmount) {
                alert('Please enter Loan Amount');
                return;
            }
            
            var loanData = {
                // Search Details
                applicantName: applicantName,
                loanId: document.getElementById('pleLoanId').value,
                memberId: document.getElementById('pleMemberId').value,
                formNo: document.getElementById('pleFormNo').value,
                loanDate: document.getElementById('pleLoanDate').value,
                loanAmount: loanAmount,
                
                // Deductions
                processingFee: document.getElementById('pleProcessingFee').value,
                gstAmt: document.getElementById('pleGstAmt').value,
                legalAmt: document.getElementById('pleLegalAmt').value,
                insuranceAmt: document.getElementById('pleInsuranceAmt').value,
                
                // 1st Guarantor
                guarantor1: {
                    memberNo: document.getElementById('pleGuarantor1MemberNo').value,
                    name: document.getElementById('pleGuarantor1Name').value,
                    guardian: document.getElementById('pleGuarantor1Guardian').value,
                    address: document.getElementById('pleGuarantor1Address').value,
                    phone: document.getElementById('pleGuarantor1Phone').value,
                    pan: document.getElementById('pleGuarantor1Pan').value,
                    aadhar: document.getElementById('pleGuarantor1Aadhar').value,
                    relation: document.getElementById('pleGuarantor1Relation').value
                },
                
                // 2nd Guarantor
                guarantor2: {
                    memberNo: document.getElementById('pleGuarantor2MemberNo').value,
                    name: document.getElementById('pleGuarantor2Name').value,
                    guardian: document.getElementById('pleGuarantor2Guardian').value,
                    address: document.getElementById('pleGuarantor2Address').value,
                    phone: document.getElementById('pleGuarantor2Phone').value,
                    pan: document.getElementById('pleGuarantor2Pan').value,
                    aadhar: document.getElementById('pleGuarantor2Aadhar').value,
                    relation: document.getElementById('pleGuarantor2Relation').value
                },
                
                // 3rd Guarantor
                guarantor3: {
                    memberNo: document.getElementById('pleGuarantor3MemberNo').value,
                    name: document.getElementById('pleGuarantor3Name').value,
                    guardian: document.getElementById('pleGuarantor3Guardian').value,
                    address: document.getElementById('pleGuarantor3Address').value,
                    phone: document.getElementById('pleGuarantor3Phone').value,
                    pan: document.getElementById('pleGuarantor3Pan').value,
                    aadhar: document.getElementById('pleGuarantor3Aadhar').value,
                    relation: document.getElementById('pleGuarantor3Relation').value
                },
                
                // Previous Loan
                previousLoan: document.getElementById('plePreviousLoan').value,
                
                // Personal Info
                holderDob: document.getElementById('pleHolderDob').value,
                holderAge: document.getElementById('pleHolderAge').value,
                guardianName: document.getElementById('pleGuardianName').value,
                phoneNo: document.getElementById('plePhoneNo').value,
                address: document.getElementById('pleAddress').value,
                pinCode: document.getElementById('plePinCode').value,
                relation: document.getElementById('pleRelation').value,
                
                // Cheque Details
                memberChequeDate: document.getElementById('pleMemberChequeDate').value,
                memberChequeNo: document.getElementById('pleMemberChequeNo').value,
                memberBankBranch: document.getElementById('pleMemberBankBranch').value,
                guarantorChequeDate: document.getElementById('pleGuarantorChequeDate').value,
                guarantorChequeNo: document.getElementById('pleGuarantorChequeNo').value,
                guarantorBankBranch: document.getElementById('pleGuarantorBankBranch').value,
                
                // Scheme Details
                productName: document.getElementById('pleProductName').value,
                itemName: document.getElementById('pleItemName').value,
                downPayment: document.getElementById('pleDownPayment').value,
                availableStock: document.getElementById('pleAvailableStock').value,
                loanTerm: document.getElementById('pleLoanTerm').value,
                mode: document.getElementById('pleMode').value,
                roiEmi: document.getElementById('pleRoiEmi').value,
                interestType: document.getElementById('pleInterestType').value,
                stax: document.getElementById('pleStax').value,
                vendorName: document.getElementById('pleVendorName').value,
                collectorCode: document.getElementById('pleCollectorCode').value,
                purpose: document.getElementById('plePurpose').value
            };
            
            console.log('Product Loan Entry Saved:', loanData);
            alert('Loan entry saved successfully for ' + applicantName + '\nLoan Amount: ₹' + loanAmount);
        }

        function showProductLoanEntry() {
            var sections = document.querySelectorAll('.content-section');
            for (var i = 0; i < sections.length; i++) {
                sections[i].style.display = 'none';
            }
            document.getElementById('ProductLoanEntry').style.display = 'block';
        }

        // Collection Sheet Print Functions

        function switchCollectionTab(tab) {
            var collectorPanel = document.getElementById('collectorWisePanel');
            var groupPanel = document.getElementById('groupWisePanel');
            var tabs = document.querySelectorAll('.sheet-tab');
            
            // Remove active class from all tabs and panels
            tabs.forEach(function(t) {
                t.classList.remove('active');
            });
            
            if (tab === 'collector') {
                collectorPanel.classList.add('active');
                groupPanel.classList.remove('active');
                tabs[0].classList.add('active');
            } else {
                groupPanel.classList.add('active');
                collectorPanel.classList.remove('active');
                tabs[1].classList.add('active');
            }
        }

        function searchCollectionSheet() {
            var activePanel = document.querySelector('.sheet-panel.active');
            var isCollectorWise = activePanel.id === 'collectorWisePanel';
            
            if (isCollectorWise) {
                var collectorCode = document.getElementById('collectorCode').value;
                var fromDate = document.getElementById('collectorFromDate').value;
                var toDate = document.getElementById('collectorToDate').value;
                
                if (!collectorCode) {
                    alert('Please select Collector Code');
                    return;
                }
                
                alert('🔍 COLLECTOR WISE COLLECTION SHEET\n\n' +
                    'Collector: ' + collectorCode + '\n' +
                    'From Date: ' + fromDate + '\n' +
                    'To Date: ' + toDate + '\n\n' +
                    '📄 Generating collection sheet...');
                    
                // Open print preview
                openCollectionPrintPreview('collector', collectorCode, fromDate, toDate);
                
            } else {
                var groupId = document.getElementById('groupId').value;
                var fromDate = document.getElementById('groupFromDate').value;
                var toDate = document.getElementById('groupToDate').value;
                
                if (!groupId) {
                    alert('Please select Group ID');
                    return;
                }
                
                alert('🔍 GROUP WISE COLLECTION SHEET\n\n' +
                    'Group: ' + groupId + '\n' +
                    'From Date: ' + fromDate + '\n' +
                    'To Date: ' + toDate + '\n\n' +
                    '📄 Generating collection sheet...');
                    
                openCollectionPrintPreview('group', groupId, fromDate, toDate);
            }
        }

        function openCollectionPrintPreview(type, code, fromDate, toDate) {
            var printWindow = window.open('', '_blank');
            var title = type === 'collector' ? 'COLLECTOR WISE COLLECTION SHEET' : 'GROUP WISE COLLECTION SHEET';
            var header = type === 'collector' ? 'Collector Code: ' + code : 'Group ID: ' + code;
            
            printWindow.document.write(`
                <html>
                <head>
                    <title>Collection Sheet - ${code}</title>
                    <style>
                        body {
                            font-family: Arial, sans-serif;
                            padding: 40px;
                            margin: 0;
                        }
                        .container {
                            max-width: 1200px;
                            margin: 0 auto;
                        }
                        .header {
                            text-align: center;
                            margin-bottom: 30px;
                            border-bottom: 2px solid #1e4663;
                            padding-bottom: 15px;
                        }
                        .header h1 {
                            color: #1e4663;
                            margin: 0 0 10px 0;
                            font-size: 1.5rem;
                        }
                        .header p {
                            margin: 5px 0;
                            color: #555;
                        }
                        .info-section {
                            margin-bottom: 20px;
                            padding: 10px;
                            background: #f8f9fa;
                            border: 1px solid #ddd;
                        }
                        table {
                            width: 100%;
                            border-collapse: collapse;
                            margin-top: 20px;
                        }
                        th {
                            background: #1e4663;
                            color: white;
                            padding: 10px;
                            text-align: left;
                            border: 1px solid #2c5a82;
                        }
                        td {
                            padding: 8px;
                            border: 1px solid #ddd;
                            text-align: left;
                        }
                        .footer {
                            margin-top: 30px;
                            text-align: center;
                            font-size: 0.8rem;
                            color: #666;
                            border-top: 1px solid #ddd;
                            padding-top: 15px;
                        }
                        @media print {
                            body {
                                padding: 20px;
                            }
                            .no-print {
                                display: none;
                            }
                        }
                    </style>
                </head>
                <body>
                    <div class="container">
                        <div class="header">
                            <h1>ANU MICRO SELFHELP ASSOCIATION</h1>
                            <h2>${title}</h2>
                            <p>${header}</p>
                            <p>Period: ${fromDate} to ${toDate}</p>
                            <p>Generated on: ${new Date().toLocaleString()}</p>
                        </div>
                        
                        <div class="info-section">
                            <strong>Collection Summary</strong><br>
                            Total Members: 5<br>
                            Total Expected Collection: ₹25,000<br>
                            Total Collected: ₹0<br>
                            Pending: ₹25,000
                        </div>
                        
                        <table>
                            <thead>
                                <tr>
                                    <th>Sl No</th>
                                    <th>Member Code</th>
                                    <th>Member Name</th>
                                    <th>Loan ID</th>
                                    <th>EMI Amount</th>
                                    <th>Due Date</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr><td>1</td><td>M001</td><td>RADHIKA DEVI</td><td>LN001</td><td>2,500</td><td>${fromDate}</td><td>Pending</td></tr>
                                <tr><td>2</td><td>M002</td><td>SARITA SINGH</td><td>LN002</td><td>2,000</td><td>${fromDate}</td><td>Pending</td></tr>
                                <tr><td>3</td><td>M003</td><td>MEENA KUMARI</td><td>LN003</td><td>1,500</td><td>${fromDate}</td><td>Pending</td></tr>
                                <tr><td>4</td><td>M004</td><td>RAMESH SINGH</td><td>LN004</td><td>5,000</td><td>${fromDate}</td><td>Pending</td></tr>
                                <tr><td>5</td><td>M005</td><td>SURESH YADAV</td><td>LN005</td><td>3,000</td><td>${fromDate}</td><td>Pending</td></tr>
                            </tbody>
                        </table>
                        
                        <div class="footer">
                            <p>This is a system generated collection sheet. Authorized Signature</p>
                            <p>** Thank you **</p>
                        </div>
                        
                        <div class="no-print" style="text-align:center; margin-top:20px;">
                            <button onclick="window.print()" style="padding:8px 20px; background:#007bff; color:white; border:none; border-radius:5px; cursor:pointer;">Print</button>
                            <button onclick="window.close()" style="padding:8px 20px; background:#dc3545; color:white; border:none; border-radius:5px; cursor:pointer; margin-left:10px;">Close</button>
                        </div>
                    </div>
                </body>
                </html>
            `);
            printWindow.document.close();
        }

        function exitCollectionSheet() {
            if (confirm('Are you sure you want to exit?')) {
                document.getElementById('collectorCode').value = '';
                document.getElementById('collectorFromDate').value = '2026-04-07';
                document.getElementById('collectorToDate').value = '2026-04-09';
                document.getElementById('groupId').value = '';
                document.getElementById('groupFromDate').value = '2026-04-07';
                document.getElementById('groupToDate').value = '2026-04-09';
                alert('Exited Collection Sheet Print');
            }
        }

        function showCollectionSheetPrint() {
            var sections = document.querySelectorAll('.content-section');
            for (var i = 0; i < sections.length; i++) {
                sections[i].style.display = 'none';
            }
            document.getElementById('collectionSheetPrintContainer').style.display = 'block';
        }

        // Loan Payment Module Functions

        var lpmLoanData = {
            loanId: 'LN001',
            formNo: 'F001',
            memberId: 'M001',
            holderName: 'RADHIKA DEVI',
            phoneNo: '9876543210',
            holderAge: '35',
            term: '12 months',
            loanName: 'TEST LOAN',
            loanAmount: '25000',
            mode: 'WLY',
            roi: '8',
            processingFee: '500',
            gst: '90',
            insuranceAmt: '200',
            emiAmount: '2500',
            accountNo: '1234567890',
            totalPayable: '30000',
            totalPaid: '5000',
            dueAmount: '25000',
            advanceAmt: '0',
            paidEmis: [
                { emiNo: 1, dueDate: '2026-03-01', payDate: '2026-03-05', amount: '2500', lateFine: '0' },
                { emiNo: 2, dueDate: '2026-04-01', payDate: '2026-04-05', amount: '2500', lateFine: '0' }
            ]
        };

        var lpmNewEmis = [];

        function searchLoanPayment() {
            var loanId = document.getElementById('lpmLoanId').value.trim();
            if (!loanId) {
                alert('Please enter Loan ID');
                return;
            }
            
            document.getElementById('lpmLoanIdDisplay').value = lpmLoanData.loanId;
            document.getElementById('lpmFormNo').value = lpmLoanData.formNo;
            document.getElementById('lpmMemberId').value = lpmLoanData.memberId;
            document.getElementById('lpmDate').value = '2026-04-09';
            document.getElementById('lpmHolderName').value = lpmLoanData.holderName;
            document.getElementById('lpmPhoneNo').value = lpmLoanData.phoneNo;
            document.getElementById('lpmHolderAge').value = lpmLoanData.holderAge;
            document.getElementById('lpmTerm').value = lpmLoanData.term;
            document.getElementById('lpmLoanName').value = lpmLoanData.loanName;
            document.getElementById('lpmLoanAmount').value = lpmLoanData.loanAmount;
            document.getElementById('lpmMode').value = lpmLoanData.mode;
            document.getElementById('lpmRoi').value = lpmLoanData.roi;
            document.getElementById('lpmProcessingFee').value = lpmLoanData.processingFee;
            document.getElementById('lpmGst').value = lpmLoanData.gst;
            document.getElementById('lpmInsuranceAmt').value = lpmLoanData.insuranceAmt;
            document.getElementById('lpmEmiAmount').value = lpmLoanData.emiAmount;
            document.getElementById('lpmAccountNo').value = lpmLoanData.accountNo;
            document.getElementById('lpmTotalPayable').value = lpmLoanData.totalPayable;
            document.getElementById('lpmTotalPaid').value = lpmLoanData.totalPaid;
            document.getElementById('lpmDueAmount').value = lpmLoanData.dueAmount;
            document.getElementById('lpmAdvanceAmt').value = lpmLoanData.advanceAmt;
            
            renderPaidEmisTable();
            renderNewEmisTable();
            alert('Loan details loaded for ID: ' + loanId);
        }

        function renderPaidEmisTable() {
            var tbody = document.getElementById('lpmPaidEmisTable');
            if (!tbody) return;
            
            if (lpmLoanData.paidEmis.length === 0) {
                tbody.innerHTML = '<tr><td colspan="5" style="text-align:center">No paid EMIs found</td></tr>';
                return;
            }
            
            tbody.innerHTML = '';
            for (var i = 0; i < lpmLoanData.paidEmis.length; i++) {
                var emi = lpmLoanData.paidEmis[i];
                var row = tbody.insertRow();
                row.insertCell(0).innerHTML = emi.emiNo;
                row.insertCell(1).innerHTML = emi.dueDate;
                row.insertCell(2).innerHTML = emi.payDate;
                row.insertCell(3).innerHTML = emi.amount;
                row.insertCell(4).innerHTML = emi.lateFine;
            }
        }

        function renderNewEmisTable() {
            var tbody = document.getElementById('lpmNewEmisTable');
            if (!tbody) return;
            
            if (lpmNewEmis.length === 0) {
                tbody.innerHTML = '<tr><td colspan="6" style="text-align:center">No new EMI entries</td></tr>';
                return;
            }
            
            tbody.innerHTML = '';
            for (var i = 0; i < lpmNewEmis.length; i++) {
                var emi = lpmNewEmis[i];
                var row = tbody.insertRow();
                row.insertCell(0).innerHTML = '<input type="text" value="' + emi.emiNo + '" class="new-emi-no" data-idx="' + i + '" onchange="updateNewEmi(' + i + ', \'emiNo\', this.value)">';
                row.insertCell(1).innerHTML = '<input type="date" value="' + emi.dueDate + '" class="new-due-date" data-idx="' + i + '" onchange="updateNewEmi(' + i + ', \'dueDate\', this.value)">';
                row.insertCell(2).innerHTML = '<input type="date" value="' + emi.payDate + '" class="new-pay-date" data-idx="' + i + '" onchange="updateNewEmi(' + i + ', \'payDate\', this.value)">';
                row.insertCell(3).innerHTML = '<input type="text" value="' + emi.amount + '" class="new-amount" data-idx="' + i + '" onchange="updateNewEmi(' + i + ', \'amount\', this.value)">';
                row.insertCell(4).innerHTML = '<input type="text" value="' + emi.lateFine + '" class="new-latefine" data-idx="' + i + '" onchange="updateNewEmi(' + i + ', \'lateFine\', this.value)">';
                row.insertCell(5).innerHTML = '<button class="delete-emi-row-btn" onclick="deleteNewEmi(' + i + ')">Delete</button>';
            }
        }

        function updateNewEmi(index, field, value) {
            if (lpmNewEmis[index]) {
                lpmNewEmis[index][field] = value;
            }
        }

        function addNewEmiRow() {
            lpmNewEmis.push({
                emiNo: '',
                dueDate: '',
                payDate: '',
                amount: '',
                lateFine: '0'
            });
            renderNewEmisTable();
        }

        function deleteNewEmi(index) {
            lpmNewEmis.splice(index, 1);
            renderNewEmisTable();
        }

        function saveLoanPayment() {
            var paymentAmount = document.getElementById('lpmPaymentAmount').value;
            var paymentMode = document.getElementById('lpmPaymentMode').value;
            var cashChecked = document.getElementById('lpmCashCheckbox').checked;
            
            if (!paymentAmount || parseFloat(paymentAmount) <= 0) {
                alert('Please enter Payment Amount');
                return;
            }
            
            // Save new EMIs to paid EMIs
            for (var i = 0; i < lpmNewEmis.length; i++) {
                var emi = lpmNewEmis[i];
                if (emi.emiNo && emi.amount) {
                    lpmLoanData.paidEmis.push({
                        emiNo: emi.emiNo,
                        dueDate: emi.dueDate,
                        payDate: emi.payDate,
                        amount: emi.amount,
                        lateFine: emi.lateFine || '0'
                    });
                }
            }
            
            var newTotalPaid = parseFloat(lpmLoanData.totalPaid) + parseFloat(paymentAmount);
            lpmLoanData.totalPaid = newTotalPaid;
            lpmLoanData.dueAmount = parseFloat(lpmLoanData.totalPayable) - newTotalPaid;
            
            document.getElementById('lpmTotalPaid').value = lpmLoanData.totalPaid;
            document.getElementById('lpmDueAmount').value = lpmLoanData.dueAmount;
            
            renderPaidEmisTable();
            lpmNewEmis = [];
            renderNewEmisTable();
            
            alert('Loan Payment Saved!\nAmount: ₹' + paymentAmount + '\nMode: ' + paymentMode + '\nCash: ' + (cashChecked ? 'Yes' : 'No'));
        }

        function deleteLastEmi() {
            if (lpmLoanData.paidEmis.length === 0) {
                alert('No EMI to delete');
                return;
            }
            
            var lastEmi = lpmLoanData.paidEmis[lpmLoanData.paidEmis.length - 1];
            if (confirm('Delete last EMI payment of ₹' + lastEmi.amount + '?')) {
                lpmLoanData.paidEmis.pop();
                var newTotalPaid = parseFloat(lpmLoanData.totalPaid) - parseFloat(lastEmi.amount);
                lpmLoanData.totalPaid = newTotalPaid;
                lpmLoanData.dueAmount = parseFloat(lpmLoanData.totalPayable) - newTotalPaid;
                
                document.getElementById('lpmTotalPaid').value = lpmLoanData.totalPaid;
                document.getElementById('lpmDueAmount').value = lpmLoanData.dueAmount;
                renderPaidEmisTable();
                alert('Last EMI deleted successfully');
            }
        }

        function printMoneyReceipt() {
            var paymentAmount = document.getElementById('lpmPaymentAmount').value || '0';
            var loanId = document.getElementById('lpmLoanIdDisplay').value || 'N/A';
            var holderName = document.getElementById('lpmHolderName').value || 'N/A';
            
            var printWindow = window.open('', '_blank');
            printWindow.document.write(`
                <html><head><title>Money Receipt</title>
                <style>body{font-family:Arial;padding:40px;} .receipt{border:1px solid #000;padding:20px;max-width:400px;margin:auto;} h2{text-align:center;}</style>
                </head><body>
                <div class="receipt"><h2>MONEY RECEIPT</h2><hr>
                <p><strong>Loan ID:</strong> ${loanId}</p>
                <p><strong>Member Name:</strong> ${holderName}</p>
                <p><strong>Amount Received:</strong> ₹${paymentAmount}</p>
                <p><strong>Date:</strong> ${new Date().toLocaleDateString()}</p>
                <hr><p style="text-align:center">Thank you</p></div>
                </body></html>
            `);
            printWindow.print();
            printWindow.close();
        }

        function printPaymentDetails() {
            var printWindow = window.open('', '_blank');
            printWindow.document.write(`
                <html><head><title>Payment Details</title>
                <style>body{font-family:Arial;padding:40px;} table{border-collapse:collapse;width:100%;} th,td{border:1px solid #ddd;padding:8px;text-align:left;}</style>
                </head><body>
                <h2>LOAN PAYMENT DETAILS</h2>
                <p><strong>Loan ID:</strong> ${document.getElementById('lpmLoanIdDisplay').value}</p>
                <p><strong>Member:</strong> ${document.getElementById('lpmHolderName').value}</p>
                <p><strong>Total Paid:</strong> ₹${document.getElementById('lpmTotalPaid').value}</p>
                <p><strong>Due Amount:</strong> ₹${document.getElementById('lpmDueAmount').value}</p>
                <h3>PAID EMIs</h3>
                <tr><th>EMI No</th><th>Due Date</th><th>Pay Date</th><th>Amount</th><th>Late Fine</th></tr>
                ${lpmLoanData.paidEmis.map(e => `<tr><td>${e.emiNo}</td><td>${e.dueDate}</td><td>${e.payDate}</td><td>${e.amount}</td><td>${e.lateFine}</td></tr>`).join('')}
                </table>
                </body></html>
            `);
            printWindow.print();
            printWindow.close();
        }

        function resetLoanPayment() {
            document.getElementById('lpmLoanId').value = '';
            document.getElementById('lpmLoanIdDisplay').value = '';
            document.getElementById('lpmFormNo').value = '';
            document.getElementById('lpmMemberId').value = '';
            document.getElementById('lpmHolderName').value = '';
            document.getElementById('lpmPhoneNo').value = '';
            document.getElementById('lpmHolderAge').value = '';
            document.getElementById('lpmTerm').value = '';
            document.getElementById('lpmLoanName').value = '';
            document.getElementById('lpmLoanAmount').value = '';
            document.getElementById('lpmMode').value = '';
            document.getElementById('lpmRoi').value = '';
            document.getElementById('lpmProcessingFee').value = '';
            document.getElementById('lpmGst').value = '';
            document.getElementById('lpmInsuranceAmt').value = '';
            document.getElementById('lpmEmiAmount').value = '';
            document.getElementById('lpmAccountNo').value = '';
            document.getElementById('lpmChequeDate').value = '';
            document.getElementById('lpmBankName').value = '';
            document.getElementById('lpmChequeNo').value = '';
            document.getElementById('lpmTotalPayable').value = '';
            document.getElementById('lpmTotalPaid').value = '';
            document.getElementById('lpmDueAmount').value = '';
            document.getElementById('lpmAdvanceAmt').value = '';
            document.getElementById('lpmPaymentAmount').value = '';
            document.getElementById('lpmPaymentNumber').value = '';
            document.getElementById('lpmPaymentRemarks').value = '';
            document.getElementById('lpmSavingsAc').value = '';
            document.getElementById('lpmReceiptedAc').value = '';
            document.getElementById('lpmPenaltyDeduct').value = '';
            document.getElementById('lpmPenaltyCharges').value = '';
            document.getElementById('lpmDueLateFine').value = '';
            document.getElementById('lpmPayDueLateFine').checked = false;
            document.getElementById('lpmCashCheckbox').checked = false;
            document.getElementById('lpmPaymentChequeDate').value = '';
            document.getElementById('lpmPaymentBankName').value = '';
            document.getElementById('lpmPaymentChequeNo').value = '';
            lpmNewEmis = [];
            renderNewEmisTable();
            document.getElementById('lpmPaidEmisTable').innerHTML = '<tr><td colspan="5" style="text-align:center">No paid EMIs found</td></tr>';
            alert('Form reset for new loan payment');
        }

        function showLoanPaymentModule() {
            var sections = document.querySelectorAll('.content-section');
            for (var i = 0; i < sections.length; i++) {
                sections[i].style.display = 'none';
            }
            document.getElementById('LoanPaymentModule').style.display = 'block';
        }

        // Repayment Group Settings Functions

        var groupLoanData = {
            GRP001: {
                loanIds: ['GL001', 'GL002'],
                members: {
                    'GL001': [
                        { loanId: 'GL001', memberId: 'M001', applicantName: 'RADHIKA DEVI', payNo: '1', emNo: '1', emi: '2500', totalPaid: '5000', prevAdvance: '0', collectionAmount: '2500', totalAmount: '2500', noOfEmi: '12', newAdvance: '0' },
                        { loanId: 'GL001', memberId: 'M002', applicantName: 'SARITA SINGH', payNo: '1', emNo: '1', emi: '2000', totalPaid: '4000', prevAdvance: '0', collectionAmount: '2000', totalAmount: '2000', noOfEmi: '12', newAdvance: '0' },
                        { loanId: 'GL001', memberId: 'M003', applicantName: 'MEENA KUMARI', payNo: '1', emNo: '1', emi: '1500', totalPaid: '3000', prevAdvance: '0', collectionAmount: '1500', totalAmount: '1500', noOfEmi: '12', newAdvance: '0' }
                    ],
                    'GL002': [
                        { loanId: 'GL002', memberId: 'M004', applicantName: 'RAMESH SINGH', payNo: '2', emNo: '3', emi: '5000', totalPaid: '15000', prevAdvance: '0', collectionAmount: '5000', totalAmount: '5000', noOfEmi: '24', newAdvance: '0' },
                        { loanId: 'GL002', memberId: 'M005', applicantName: 'SURESH YADAV', payNo: '2', emNo: '3', emi: '3000', totalPaid: '9000', prevAdvance: '0', collectionAmount: '3000', totalAmount: '3000', noOfEmi: '24', newAdvance: '0' }
                    ]
                }
            },
            GRP002: {
                loanIds: ['GL003', 'GL004'],
                members: {
                    'GL003': [
                        { loanId: 'GL003', memberId: 'M006', applicantName: 'LAKSHMI NARAYAN', payNo: '1', emNo: '2', emi: '3500', totalPaid: '7000', prevAdvance: '500', collectionAmount: '3500', totalAmount: '3000', noOfEmi: '18', newAdvance: '0' },
                        { loanId: 'GL003', memberId: 'M007', applicantName: 'GEETA DEVI', payNo: '1', emNo: '2', emi: '2200', totalPaid: '4400', prevAdvance: '0', collectionAmount: '2200', totalAmount: '2200', noOfEmi: '18', newAdvance: '0' }
                    ],
                    'GL004': [
                        { loanId: 'GL004', memberId: 'M008', applicantName: 'ANITA SINGH', payNo: '1', emNo: '1', emi: '1800', totalPaid: '1800', prevAdvance: '0', collectionAmount: '1800', totalAmount: '1800', noOfEmi: '12', newAdvance: '0' }
                    ]
                }
            },
            GRP003: {
                loanIds: ['GL005'],
                members: {
                    'GL005': [
                        { loanId: 'GL005', memberId: 'M009', applicantName: 'VIKAS GUPTA', payNo: '3', emNo: '5', emi: '4000', totalPaid: '20000', prevAdvance: '1000', collectionAmount: '4000', totalAmount: '3000', noOfEmi: '36', newAdvance: '0' },
                        { loanId: 'GL005', memberId: 'M010', applicantName: 'NEHA VERMA', payNo: '3', emNo: '5', emi: '3500', totalPaid: '17500', prevAdvance: '0', collectionAmount: '3500', totalAmount: '3500', noOfEmi: '36', newAdvance: '0' }
                    ]
                }
            }
        };

        function loadGroupLoanIds() {
            var groupId = document.getElementById('rsSelectGroup').value;
            var loanIdSelect = document.getElementById('rsGroupLoanId');
            
            loanIdSelect.innerHTML = '<option value="">Select Group Loan ID</option>';
            
            if (groupId && groupLoanData[groupId]) {
                var loanIds = groupLoanData[groupId].loanIds;
                for (var i = 0; i < loanIds.length; i++) {
                    var option = document.createElement('option');
                    option.value = loanIds[i];
                    option.text = loanIds[i];
                    loanIdSelect.appendChild(option);
                }
            }
        }

        function loadRepaymentData() {
            var groupId = document.getElementById('rsSelectGroup').value;
            var loanId = document.getElementById('rsGroupLoanId').value;
            
            if (!groupId || !loanId) {
                alert('Please select both Group and Group Loan ID');
                return;
            }
            
            if (groupLoanData[groupId] && groupLoanData[groupId].members[loanId]) {
                var members = groupLoanData[groupId].members[loanId];
                renderRepaymentTable(members);
                calculateTotals(members);
            } else {
                document.getElementById('rsRepaymentTableBody').innerHTML = '<tr><td colspan="12" style="text-align:center">No data found</td></tr>';
                document.getElementById('rsTotalProjectionAmount').value = '0.00';
                document.getElementById('rsTotalCollectionAmount').value = '0.00';
            }
        }

        function renderRepaymentTable(members) {
            var tbody = document.getElementById('rsRepaymentTableBody');
            if (!tbody) return;
            
            tbody.innerHTML = '';
            
            for (var i = 0; i < members.length; i++) {
                var m = members[i];
                var row = tbody.insertRow();
                
                row.insertCell(0).innerHTML = m.loanId;
                row.insertCell(1).innerHTML = m.memberId;
                row.insertCell(2).innerHTML = m.applicantName;
                row.insertCell(3).innerHTML = '<input type="text" value="' + m.payNo + '" class="pay-no" data-idx="' + i + '" onchange="updateRepaymentField(' + i + ', \'payNo\', this.value)">';
                row.insertCell(4).innerHTML = '<input type="text" value="' + m.emNo + '" class="em-no" data-idx="' + i + '" onchange="updateRepaymentField(' + i + ', \'emNo\', this.value)">';
                row.insertCell(5).innerHTML = '<input type="text" value="' + m.emi + '" class="emi" data-idx="' + i + '" readonly style="background:#e9ecef">';
                row.insertCell(6).innerHTML = '<input type="text" value="' + m.totalPaid + '" class="total-paid" data-idx="' + i + '" readonly style="background:#e9ecef">';
                row.insertCell(7).innerHTML = '<input type="text" value="' + m.prevAdvance + '" class="prev-advance" data-idx="' + i + '" onchange="updateRepaymentField(' + i + ', \'prevAdvance\', this.value); calculateRowTotal(' + i + ')">';
                row.insertCell(8).innerHTML = '<input type="text" value="' + m.collectionAmount + '" class="collection-amount" data-idx="' + i + '" onchange="updateRepaymentField(' + i + ', \'collectionAmount\', this.value); calculateRowTotal(' + i + '); updateTotalCollection()">';
                row.insertCell(9).innerHTML = '<input type="text" value="' + m.totalAmount + '" class="total-amount" data-idx="' + i + '" readonly style="background:#e9ecef">';
                row.insertCell(10).innerHTML = '<input type="text" value="' + m.noOfEmi + '" class="no-of-emi" data-idx="' + i + '" readonly style="background:#e9ecef">';
                row.insertCell(11).innerHTML = '<input type="text" value="' + m.newAdvance + '" class="new-advance" data-idx="' + i + '" onchange="updateRepaymentField(' + i + ', \'newAdvance\', this.value)">';
            }
        }

        function updateRepaymentField(index, field, value) {
            var groupId = document.getElementById('rsSelectGroup').value;
            var loanId = document.getElementById('rsGroupLoanId').value;
            
            if (groupLoanData[groupId] && groupLoanData[groupId].members[loanId]) {
                groupLoanData[groupId].members[loanId][index][field] = value;
            }
        }

        function calculateRowTotal(index) {
            var groupId = document.getElementById('rsSelectGroup').value;
            var loanId = document.getElementById('rsGroupLoanId').value;
            
            if (groupLoanData[groupId] && groupLoanData[groupId].members[loanId]) {
                var member = groupLoanData[groupId].members[loanId][index];
                var emi = parseFloat(member.emi) || 0;
                var prevAdvance = parseFloat(member.prevAdvance) || 0;
                var collectionAmount = parseFloat(member.collectionAmount) || 0;
                
                var totalAmount = emi - prevAdvance;
                if (totalAmount < 0) totalAmount = 0;
                
                member.totalAmount = totalAmount;
                
                var row = document.getElementById('rsRepaymentTableBody').rows[index];
                if (row) {
                    var totalAmountCell = row.cells[9].querySelector('input');
                    if (totalAmountCell) totalAmountCell.value = totalAmount;
                }
            }
        }

        function updateTotalCollection() {
            var groupId = document.getElementById('rsSelectGroup').value;
            var loanId = document.getElementById('rsGroupLoanId').value;
            
            if (!groupId || !loanId) return;
            
            var members = groupLoanData[groupId].members[loanId];
            var totalProjection = 0;
            var totalCollection = 0;
            
            for (var i = 0; i < members.length; i++) {
                totalProjection += parseFloat(members[i].emi) || 0;
                totalCollection += parseFloat(members[i].collectionAmount) || 0;
            }
            
            document.getElementById('rsTotalProjectionAmount').value = totalProjection.toFixed(2);
            document.getElementById('rsTotalCollectionAmount').value = totalCollection.toFixed(2);
        }

        function calculateTotals(members) {
            var totalProjection = 0;
            var totalCollection = 0;
            
            for (var i = 0; i < members.length; i++) {
                totalProjection += parseFloat(members[i].emi) || 0;
                totalCollection += parseFloat(members[i].collectionAmount) || 0;
            }
            
            document.getElementById('rsTotalProjectionAmount').value = totalProjection.toFixed(2);
            document.getElementById('rsTotalCollectionAmount').value = totalCollection.toFixed(2);
        }

        function showRepaymentSettings() {
            var sections = document.querySelectorAll('.content-section');
            for (var i = 0; i < sections.length; i++) {
                sections[i].style.display = 'none';
            }
            document.getElementById('RepaymentSettingsContainer').style.display = 'block';
        }

        // Loan Pre Closer Functions

        var lpcLoanData = {
            loanId: 'LN001',
            formNo: 'F001',
            memberId: 'M001',
            holderName: 'RADHIKA DEVI',
            phoneNo: '9876543210',
            holderAge: '35',
            product: 'TEST LOAN',
            term: '12 months',
            loanAmount: '25000',
            mode: 'WLY',
            roi: '8',
            membership: '500',
            processingFees: '500',
            serviceTax: '90',
            insuranceAmount: '200',
            emiAmount: '2500',
            loanPrincipal: '25000',
            paidPrincipal: '5000',
            duePrincipal: '20000',
            payablePrincipal: '20000',
            payableInterest: '1500',
            loanInterest: '2500',
            paidInterest: '1000',
            dueInterest: '1500',
            emiSchedule: [
                { loanId: 'LN001', payNo: '1', payDate: '2026-03-05', principal: '2000', interest: '500', amount: '2500', branch: 'HEAD OFFICE - 001', payBy: 'CASH' },
                { loanId: 'LN001', payNo: '2', payDate: '2026-04-05', principal: '2000', interest: '500', amount: '2500', branch: 'HEAD OFFICE - 001', payBy: 'CHEQUE' },
                { loanId: 'LN001', payNo: '3', payDate: '', principal: '2000', interest: '500', amount: '2500', branch: '', payBy: '' },
                { loanId: 'LN001', payNo: '4', payDate: '', principal: '2000', interest: '500', amount: '2500', branch: '', payBy: '' },
                { loanId: 'LN001', payNo: '5', payDate: '', principal: '2000', interest: '500', amount: '2500', branch: '', payBy: '' },
                { loanId: 'LN001', payNo: '6', payDate: '', principal: '2000', interest: '500', amount: '2500', branch: '', payBy: '' }
            ]
        };

        function searchLoanForPreCloser() {
            var loanId = document.getElementById('lpcLoanId').value.trim();
            if (!loanId) {
                alert('Please enter Loan ID');
                return;
            }
            
            document.getElementById('lpcLoanIdDisplay').value = lpcLoanData.loanId;
            document.getElementById('lpcFormNo').value = lpcLoanData.formNo;
            document.getElementById('lpcMemberId').value = lpcLoanData.memberId;
            document.getElementById('lpcHolderName').value = lpcLoanData.holderName;
            document.getElementById('lpcPhoneNo').value = lpcLoanData.phoneNo;
            document.getElementById('lpcHolderAge').value = lpcLoanData.holderAge;
            
            document.getElementById('lpcProduct').value = lpcLoanData.product;
            document.getElementById('lpcTerm').value = lpcLoanData.term;
            document.getElementById('lpcLoanAmount').value = lpcLoanData.loanAmount;
            document.getElementById('lpcMode').value = lpcLoanData.mode;
            document.getElementById('lpcRoi').value = lpcLoanData.roi;
            document.getElementById('lpcMembership').value = lpcLoanData.membership;
            document.getElementById('lpcProcessingFees').value = lpcLoanData.processingFees;
            document.getElementById('lpcServiceTax').value = lpcLoanData.serviceTax;
            document.getElementById('lpcInsuranceAmount').value = lpcLoanData.insuranceAmount;
            document.getElementById('lpcEmiAmount').value = lpcLoanData.emiAmount;
            
            document.getElementById('lpcLoanPrincipal').value = lpcLoanData.loanPrincipal;
            document.getElementById('lpcPaidPrincipal').value = lpcLoanData.paidPrincipal;
            document.getElementById('lpcDuePrincipal').value = lpcLoanData.duePrincipal;
            document.getElementById('lpcPayablePrincipal').value = lpcLoanData.payablePrincipal;
            document.getElementById('lpcPayableInterest').value = lpcLoanData.payableInterest;
            document.getElementById('lpcPayablePrincipalBottom').value = lpcLoanData.payablePrincipal;
            
            document.getElementById('lpcLoanInterest').value = lpcLoanData.loanInterest;
            document.getElementById('lpcPaidInterest').value = lpcLoanData.paidInterest;
            document.getElementById('lpcDueInterest').value = lpcLoanData.dueInterest;
            
            renderEmiScheduleTable();
            calculateTotalAmount();
            
            alert('Loan details loaded for ID: ' + loanId);
        }

        function renderEmiScheduleTable() {
            var tbody = document.getElementById('lpcEmiTableBody');
            if (!tbody) return;
            
            var schedule = lpcLoanData.emiSchedule;
            tbody.innerHTML = '';
            
            for (var i = 0; i < schedule.length; i++) {
                var emi = schedule[i];
                var row = tbody.insertRow();
                row.insertCell(0).innerHTML = emi.loanId;
                row.insertCell(1).innerHTML = emi.payNo;
                row.insertCell(2).innerHTML = emi.payDate;
                row.insertCell(3).innerHTML = emi.principal;
                row.insertCell(4).innerHTML = emi.interest;
                row.insertCell(5).innerHTML = emi.amount;
                row.insertCell(6).innerHTML = emi.branch;
                row.insertCell(7).innerHTML = emi.payBy;
            }
        }

        function calculateTotalAmount() {
            var duePrincipal = parseFloat(document.getElementById('lpcDuePrincipal').value) || 0;
            var dueInterest = parseFloat(document.getElementById('lpcDueInterest').value) || 0;
            var waiverInterest = parseFloat(document.getElementById('lpcWaiverInterest').value) || 0;
            var settlementCharge = parseFloat(document.getElementById('lpcSettlementCharge').value) || 0;
            
            var totalAmount = duePrincipal + dueInterest - waiverInterest + settlementCharge;
            document.getElementById('lpcTotalAmount').value = totalAmount.toFixed(2);
        }

        document.getElementById('lpcWaiverInterest').addEventListener('input', calculateTotalAmount);
        document.getElementById('lpcSettlementCharge').addEventListener('input', calculateTotalAmount);

        function updatePreCloser() {
            var loanId = document.getElementById('lpcLoanIdDisplay').value;
            if (!loanId) {
                alert('Please search for a loan first');
                return;
            }
            
            var totalAmount = document.getElementById('lpcTotalAmount').value;
            alert('Loan Pre Closure details updated successfully!\nTotal Amount: ₹' + totalAmount);
        }

        function closePreCloser() {
            if (confirm('Are you sure you want to close?')) {
                document.getElementById('lpcLoanId').value = '';
                document.getElementById('lpcEmiTableBody').innerHTML = '<tr><td colspan="6" style="text-align:center">Search loan to view EMI schedule</td></tr>';
                alert('Closed');
            }
        }

        function showLoanPreCloser() {
            var sections = document.querySelectorAll('.content-section');
            for (var i = 0; i < sections.length; i++) {
                sections[i].style.display = 'none';
            }
            document.getElementById('LoanPreCloserContainer').style.display = 'block';
        }

        // Loan Document Print Functions

        function printLoanDocuments() {
            var loanNo = document.getElementById('ldpLoanNo').innerText;
            var loanId = document.getElementById('ldpLoanId').value;
            var applicantName = document.getElementById('ldpApplicantName').value;
            var memberCode = document.getElementById('ldpMemberCode').value;
            var loanName = document.getElementById('ldpLoanName').value;
            var term = document.getElementById('ldpTerm').value;
            var loanAmount = document.getElementById('ldpLoanAmount').value;
            var roi = document.getElementById('ldpRoi').value;
            var emi = document.getElementById('ldpEmi').value;
            var interestType = document.getElementById('ldpInterestType').value;
            
            // Get selected documents
            var selectedDocs = [];
            if (document.getElementById('ldpLoanAgreement').checked) selectedDocs.push('Loan Agreement');
            if (document.getElementById('ldpApplicationForm').checked) selectedDocs.push('Application Form');
            if (document.getElementById('ldpTerm').checked) selectedDocs.push('Term');
            if (document.getElementById('ldpSchemeDetails').checked) selectedDocs.push('Scheme Details');
            if (document.getElementById('ldpLoanPaymentSchedule').checked) selectedDocs.push('Loan Payment Schedule');
            if (document.getElementById('ldpTermAndCondition').checked) selectedDocs.push('Term And Condition');
            if (document.getElementById('ldpPaymentDueNotice').checked) selectedDocs.push('Payment Due Notice');
            
            if (selectedDocs.length === 0) {
                alert('Please select at least one document to print');
                return;
            }
            
            // Create print window
            var printWindow = window.open('', '_blank');
            
            var documentContent = '';
            for (var i = 0; i < selectedDocs.length; i++) {
                documentContent += generateDocumentContent(selectedDocs[i], {
                    loanNo: loanNo,
                    loanId: loanId,
                    applicantName: applicantName,
                    memberCode: memberCode,
                    loanName: loanName,
                    term: term,
                    loanAmount: loanAmount,
                    roi: roi,
                    emi: emi,
                    interestType: interestType
                });
            }
            
            printWindow.document.write(`
                <html>
                <head>
                    <title>Loan Documents - ${loanId}</title>
                    <style>
                        body {
                            font-family: Arial, sans-serif;
                            padding: 40px;
                            margin: 0;
                        }
                        .container {
                            max-width: 900px;
                            margin: 0 auto;
                        }
                        .header {
                            text-align: center;
                            margin-bottom: 30px;
                            border-bottom: 2px solid #1e4663;
                            padding-bottom: 15px;
                        }
                        .header h1 {
                            color: #1e4663;
                            margin: 0;
                            font-size: 1.5rem;
                        }
                        .header p {
                            margin: 5px 0;
                            color: #555;
                        }
                        .document-section {
                            margin-bottom: 30px;
                            page-break-inside: avoid;
                        }
                        .document-title {
                            background: #f0f2f6;
                            padding: 8px 15px;
                            font-size: 1rem;
                            font-weight: bold;
                            color: #1e4663;
                            border-left: 4px solid #3498db;
                            margin-bottom: 15px;
                        }
                        .loan-details {
                            margin-bottom: 20px;
                        }
                        .loan-details table {
                            width: 100%;
                            border-collapse: collapse;
                        }
                        .loan-details td {
                            padding: 8px;
                            border-bottom: 1px solid #ddd;
                        }
                        .loan-details td:first-child {
                            font-weight: bold;
                            width: 30%;
                        }
                        .footer {
                            margin-top: 50px;
                            text-align: center;
                            font-size: 0.7rem;
                            color: #666;
                            border-top: 1px solid #ddd;
                            padding-top: 15px;
                        }
                        @media print {
                            body {
                                padding: 20px;
                            }
                            .no-print {
                                display: none;
                            }
                        }
                    </style>
                </head>
                <body>
                    <div class="container">
                        <div class="header">
                            <h1>ANU MICRO SELFHELP ASSOCIATION</h1>
                            <p>Loan Document Print</p>
                            <p>Generated on: ${new Date().toLocaleString()}</p>
                        </div>
                        ${documentContent}
                        <div class="footer">
                            <p>This is a system generated document. Authorized Signature</p>
                            <p>** Thank you **</p>
                        </div>
                        <div class="no-print" style="text-align:center; margin-top:20px;">
                            <button onclick="window.print()" style="padding:8px 20px; background:#007bff; color:white; border:none; border-radius:5px; cursor:pointer;">Print</button>
                            <button onclick="window.close()" style="padding:8px 20px; background:#dc3545; color:white; border:none; border-radius:5px; cursor:pointer; margin-left:10px;">Close</button>
                        </div>
                    </div>
                </body>
                </html>
            `);
            printWindow.document.close();
        }

        function generateDocumentContent(docType, data) {
            var commonDetails = `
                <div class="loan-details">
                    <table>
                        <tr><td>Loan No:</td><td>${data.loanNo}</td></tr>
                        <tr><td>Loan ID:</td><td>${data.loanId}</td></tr>
                        <tr><td>Applicant Name:</td><td>${data.applicantName}</td></tr>
                        <tr><td>Member Code:</td><td>${data.memberCode}</td></tr>
                        <tr><td>Loan Name:</td><td>${data.loanName}</td></tr>
                        <tr><td>Term:</td><td>${data.term}</td></tr>
                        <tr><td>Loan Amount:</td><td>₹${data.loanAmount}</td></tr>
                        <tr><td>ROI:</td><td>${data.roi}</td></tr>
                        <tr><td>EMI:</td><td>₹${data.emi}</td></tr>
                        <tr><td>Interest Type:</td><td>${data.interestType}</td></tr>
                    </table>
                </div>
            `;
            
            var specificContent = '';
            
            switch(docType) {
                case 'Loan Agreement':
                    specificContent = `
                        <p>This Loan Agreement is made between ANU MICRO SELFHELP ASSOCIATION and the borrower ${data.applicantName}.</p>
                        <p>The borrower agrees to repay the loan amount of ₹${data.loanAmount} with an interest rate of ${data.roi} over a period of ${data.term}.</p>
                        <p>The EMI amount is ₹${data.emi} which shall be paid on or before the due date each month.</p>
                    `;
                    break;
                case 'Application Form':
                    specificContent = `
                        <p>I, ${data.applicantName} (Member Code: ${data.memberCode}), hereby apply for a loan of ₹${data.loanAmount} under the ${data.loanName} scheme.</p>
                        <p>I declare that all information provided is true and correct to the best of my knowledge.</p>
                        <p>Date: ___________</p>
                        <p>Signature: ___________</p>
                    `;
                    break;
                case 'Term':
                    specificContent = `
                        <p><strong>Loan Terms:</strong></p>
                        <ul>
                            <li>Loan Amount: ₹${data.loanAmount}</li>
                            <li>Interest Rate: ${data.roi} per annum</li>
                            <li>Loan Tenure: ${data.term}</li>
                            <li>EMI Amount: ₹${data.emi}</li>
                            <li>Interest Type: ${data.interestType}</li>
                        </ul>
                    `;
                    break;
                case 'Scheme Details':
                    specificContent = `
                        <p><strong>Scheme Name:</strong> ${data.loanName}</p>
                        <p><strong>Scheme Features:</strong></p>
                        <ul>
                            <li>Quick Disbursal</li>
                            <li>Flexible Repayment Options</li>
                            <li>Low Interest Rate</li>
                            <li>No Hidden Charges</li>
                        </ul>
                    `;
                    break;
                case 'Loan Payment Schedule':
                    specificContent = `
                        <table border="1" cellpadding="8" style="width:100%; border-collapse:collapse;">
                            <tr style="background:#f0f0f0"><th>EMI No</th><th>Due Date</th><th>Principal</th><th>Interest</th><th>Total</th></tr>
                            ${generatePaymentSchedule()}
                        </table>
                    `;
                    break;
                case 'Term And Condition':
                    specificContent = `
                        <p><strong>Terms and Conditions:</strong></p>
                        <ul>
                            <li>EMI must be paid on or before the due date.</li>
                            <li>Late payment will attract additional charges.</li>
                            <li>The loan can be foreclosed after 6 months.</li>
                            <li>Documentation charges are non-refundable.</li>
                        </ul>
                    `;
                    break;
                case 'Payment Due Notice':
                    specificContent = `
                        <p>Dear ${data.applicantName},</p>
                        <p>This is to remind you that your EMI payment of ₹${data.emi} is due for the loan ${data.loanId}.</p>
                        <p>Please make the payment on or before the due date to avoid late payment charges.</p>
                        <p>Thank you for your cooperation.</p>
                    `;
                    break;
            }
            
            return `
                <div class="document-section">
                    <div class="document-title">${docType}</div>
                    ${commonDetails}
                    ${specificContent}
                </div>
            `;
        }

        function generatePaymentSchedule() {
            var rows = '';
            for (var i = 1; i <= 12; i++) {
                var dueDate = new Date();
                dueDate.setMonth(dueDate.getMonth() + i);
                var dateStr = dueDate.toISOString().slice(0, 10);
                rows += `<tr><td>${i}</td><td>${dateStr}</td><td>3,500</td><td>1,000</td><td>4,500</td></tr>`;
            }
            return rows;
        }

        function showLoanDocumentPrint() {
            var sections = document.querySelectorAll('.content-section');
            for (var i = 0; i < sections.length; i++) {
                sections[i].style.display = 'none';
            }
            document.getElementById('LoanDocumentPrintContainer').style.display = 'block';
        }

        // Loan Calculator Functions

        function calculateLoan() {
            // Get input values
            var loanAmount = parseFloat(document.getElementById('calcLoanAmount').value) || 0;
            var rateOfInterest = parseFloat(document.getElementById('calcRateOfInterest').value) || 0;
            var noOfInstallments = parseFloat(document.getElementById('calcNoOfInstallments').value) || 0;
            var loanMode = document.getElementById('calcLoanMode').value;
            var interestType = document.getElementById('calcInterestType').value;
            
            // Validation
            if (loanAmount <= 0) {
                alert('Please enter valid Loan Amount');
                return;
            }
            
            if (rateOfInterest <= 0) {
                alert('Please enter Rate of Interest');
                return;
            }
            
            if (noOfInstallments <= 0) {
                alert('Please enter Number of Installments');
                return;
            }
            
            if (!loanMode) {
                alert('Please select Loan Mode');
                return;
            }
            
            if (!interestType) {
                alert('Please select Loan Interest Type');
                return;
            }
            
            var interestAmount = 0;
            var totalRepayment = 0;
            var emi = 0;
            
            // Calculate based on interest type
            if (interestType === 'FLAT') {
                interestAmount = loanAmount * (rateOfInterest / 100) * (noOfInstallments / 12);
                totalRepayment = loanAmount + interestAmount;
                emi = totalRepayment / noOfInstallments;
            } else if (interestType === 'REDUCING') {
                var monthlyRate = (rateOfInterest / 100) / 12;
                emi = loanAmount * monthlyRate * Math.pow(1 + monthlyRate, noOfInstallments) / (Math.pow(1 + monthlyRate, noOfInstallments) - 1);
                totalRepayment = emi * noOfInstallments;
                interestAmount = totalRepayment - loanAmount;
            }
            
            document.getElementById('calcInterestAmount').value = interestAmount.toFixed(2);
            document.getElementById('calcTotalRepayment').value = totalRepayment.toFixed(2);
            document.getElementById('calcEmi').value = emi.toFixed(2);
        }

        function showLoanCard() {
            var loanAmount = document.getElementById('calcLoanAmount').value || '0';
            var rateOfInterest = document.getElementById('calcRateOfInterest').value || '0';
            var noOfInstallments = document.getElementById('calcNoOfInstallments').value || '0';
            var loanDate = document.getElementById('calcLoanDate').value;
            var loanModeSelect = document.getElementById('calcLoanMode');
            var loanMode = loanModeSelect.options[loanModeSelect.selectedIndex]?.text || 'Not Selected';
            var interestTypeSelect = document.getElementById('calcInterestType');
            var interestType = interestTypeSelect.options[interestTypeSelect.selectedIndex]?.text || 'Not Selected';
            var interestAmount = document.getElementById('calcInterestAmount').value || '0';
            var totalRepayment = document.getElementById('calcTotalRepayment').value || '0';
            var emi = document.getElementById('calcEmi').value || '0';
            
            if (parseFloat(loanAmount) <= 0) {
                alert('Please calculate the loan first');
                return;
            }
            
            var printWindow = window.open('', '_blank');
            printWindow.document.write(loanCardHTML(loanAmount, rateOfInterest, noOfInstallments, loanDate, loanMode, interestType, interestAmount, totalRepayment, emi));
            printWindow.document.close();
        }

        function loanCardHTML(loanAmount, rateOfInterest, noOfInstallments, loanDate, loanMode, interestType, interestAmount, totalRepayment, emi) {
            return `
                <!DOCTYPE html>
                <html>
                <head>
                    <title>Loan Card</title>
                    <style>
                        body { font-family: Arial, sans-serif; padding: 40px; margin: 0; }
                        .card { max-width: 400px; margin: 0 auto; border: 2px solid #1e4663; border-radius: 15px; padding: 20px; background: white; }
                        .header { text-align: center; border-bottom: 2px solid #1e4663; padding-bottom: 10px; margin-bottom: 20px; }
                        .header h1 { color: #1e4663; margin: 0; font-size: 1.2rem; }
                        .header p { margin: 5px 0 0 0; font-size: 0.7rem; color: #666; }
                        .detail-row { display: flex; justify-content: space-between; padding: 8px 0; border-bottom: 1px dashed #ddd; }
                        .detail-label { font-weight: bold; color: #495057; }
                        .detail-value { color: #2c3e50; }
                        .footer { text-align: center; margin-top: 20px; padding-top: 10px; border-top: 1px solid #ddd; font-size: 0.7rem; color: #666; }
                        @media print { body { padding: 20px; } }
                    </style>
                </head>
                <body>
                    <div class="card">
                        <div class="header">
                            <h1>LOAN CARD</h1>
                            <p>ANU MICRO SELFHELP ASSOCIATION</p>
                        </div>
                        <div class="detail-row"><span class="detail-label">Loan Amount:</span><span class="detail-value">₹ ${parseFloat(loanAmount).toFixed(2)}</span></div>
                        <div class="detail-row"><span class="detail-label">Rate of Interest:</span><span class="detail-value">${rateOfInterest}% p.a.</span></div>
                        <div class="detail-row"><span class="detail-label">No of Installments:</span><span class="detail-value">${noOfInstallments}</span></div>
                        <div class="detail-row"><span class="detail-label">Loan Date:</span><span class="detail-value">${loanDate}</span></div>
                        <div class="detail-row"><span class="detail-label">Loan Mode:</span><span class="detail-value">${loanMode}</span></div>
                        <div class="detail-row"><span class="detail-label">Interest Type:</span><span class="detail-value">${interestType}</span></div>
                        <div class="detail-row"><span class="detail-label">Interest Amount:</span><span class="detail-value">₹ ${parseFloat(interestAmount).toFixed(2)}</span></div>
                        <div class="detail-row"><span class="detail-label">Total Repayment:</span><span class="detail-value">₹ ${parseFloat(totalRepayment).toFixed(2)}</span></div>
                        <div class="detail-row"><span class="detail-label">EMI:</span><span class="detail-value">₹ ${parseFloat(emi).toFixed(2)}</span></div>
                        <div class="footer"><p>Generated on: ${new Date().toLocaleString()}</p><p>** Authorized Signature **</p></div>
                        <div style="text-align:center; margin-top:20px;">
                            <button onclick="window.print()" style="padding:8px 20px; background:#007bff; color:white; border:none; border-radius:5px; cursor:pointer;">Print</button>
                            <button onclick="window.close()" style="padding:8px 20px; background:#dc3545; color:white; border:none; border-radius:5px; cursor:pointer; margin-left:10px;">Close</button>
                        </div>
                    </div>
                </body>
                </html>
            `;
        }

        function showLoanCalculator() {
            var sections = document.querySelectorAll('.content-section');
            for (var i = 0; i < sections.length; i++) {
                sections[i].style.display = 'none';
            }
            document.getElementById('LoanCalculatorContainer').style.display = 'block';
        }

        // Loan NOC Document Functions

        function showLoanDocument() {
            var loanId = document.getElementById('ldocLoanId').value.trim();
            
            if (!loanId) {
                alert('Please enter Loan ID');
                return;
            }
            
            alert('Showing loan document for Loan ID: ' + loanId);
            // You can implement actual document display logic here
        }

        function closeLoanDocument() {
            if (confirm('Are you sure you want to close?')) {
                document.getElementById('ldocLoanId').value = '';
                alert('Closed');
            }
        }

        function downloadNOCCertificate() {
            var loanId = document.getElementById('ldocLoanId').value.trim();
            
            if (!loanId) {
                alert('Please enter Loan ID first');
                return;
            }
            
            // NOC Certificate Generation
            var printWindow = window.open('', '_blank');
            printWindow.document.write(nocCertificateHTML(loanId));
            printWindow.document.close();
        }

        function nocCertificateHTML(loanId) {
            var today = new Date();
            var formattedDate = today.toLocaleDateString('en-GB');
            
            return `
                <!DOCTYPE html>
                <html>
                <head>
                    <title>NOC Certificate - ${loanId}</title>
                    <style>
                        body {
                            font-family: Arial, sans-serif;
                            padding: 40px;
                            margin: 0;
                            background: #f0f2f6;
                        }
                        .certificate {
                            max-width: 800px;
                            margin: 0 auto;
                            background: white;
                            border: 2px solid #1e4663;
                            border-radius: 15px;
                            padding: 40px;
                            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
                        }
                        .header {
                            text-align: center;
                            border-bottom: 2px solid #1e4663;
                            padding-bottom: 15px;
                            margin-bottom: 25px;
                        }
                        .header h1 {
                            color: #1e4663;
                            margin: 0;
                            font-size: 1.8rem;
                        }
                        .header h2 {
                            color: #2c3e50;
                            margin: 10px 0 0 0;
                            font-size: 1.2rem;
                        }
                        .content {
                            margin-bottom: 30px;
                            line-height: 1.8;
                        }
                        .content p {
                            margin: 15px 0;
                            font-size: 1rem;
                        }
                        .loan-details {
                            background: #f8f9fa;
                            padding: 15px;
                            border-radius: 8px;
                            margin: 20px 0;
                        }
                        .footer {
                            text-align: center;
                            margin-top: 40px;
                            padding-top: 20px;
                            border-top: 1px solid #ddd;
                        }
                        .signature {
                            margin-top: 30px;
                            display: flex;
                            justify-content: space-between;
                        }
                        @media print {
                            body {
                                padding: 20px;
                                background: white;
                            }
                            .no-print {
                                display: none;
                            }
                        }
                    </style>
                </head>
                <body>
                    <div class="certificate">
                        <div class="header">
                            <h1>NO OBJECTION CERTIFICATE</h1>
                            <h2>ANU MICRO SELFHELP ASSOCIATION</h2>
                        </div>
                        
                        <div class="content">
                            <p>This is to certify that the loan against <strong>Loan ID: ${loanId}</strong> has been <strong>fully closed</strong> and there are no outstanding dues pending.</p>
                            
                            <div class="loan-details">
                                <p><strong>Loan ID:</strong> ${loanId}</p>
                                <p><strong>Closing Date:</strong> ${formattedDate}</p>
                                <p><strong>Status:</strong> <span style="color:green; font-weight:bold;">CLOSED</span></p>
                            </div>
                            
                            <p>This certificate is issued for the purpose of releasing all claims, liens, and charges on the loan account. The borrower is free from any further obligations towards the association.</p>
                            
                            <p>We wish the borrower all the best for their future endeavors.</p>
                        </div>
                        
                        <div class="signature">
                            <div>
                                <p>____________________</p>
                                <p><strong>Borrower Signature</strong></p>
                            </div>
                            <div>
                                <p>____________________</p>
                                <p><strong>Authorized Signatory</strong></p>
                            </div>
                        </div>
                        
                        <div class="footer">
                            <p>Generated on: ${formattedDate}</p>
                            <p>** This is a system generated certificate **</p>
                        </div>
                        
                        <div class="no-print" style="text-align:center; margin-top:20px;">
                            <button onclick="window.print()" style="padding:8px 20px; background:#007bff; color:white; border:none; border-radius:5px; cursor:pointer;">Print</button>
                            <button onclick="window.close()" style="padding:8px 20px; background:#dc3545; color:white; border:none; border-radius:5px; cursor:pointer; margin-left:10px;">Close</button>
                        </div>
                    </div>
                </body>
                </html>
            `;
        }

        function showLoanDocumentModule() {
            var sections = document.querySelectorAll('.content-section');
            for (var i = 0; i < sections.length; i++) {
                sections[i].style.display = 'none';
            }
            document.getElementById('LoanDocumentContainer').style.display = 'block';
        }

        // Loan EMI Daywise Report Functions

        // Sample report data
        var loanEmiReportData = [
            { slNo: 1, loanId: 'LN001', memberName: 'RADHIKA DEVI', memberCode: 'M001', emiAmount: '2500', dueDate: '2026-04-05', status: 'Paid', branch: 'HEAD OFFICE - 001' },
            { slNo: 2, loanId: 'LN002', memberName: 'SARITA SINGH', memberCode: 'M002', emiAmount: '2000', dueDate: '2026-04-05', status: 'Paid', branch: 'HEAD OFFICE - 001' },
            { slNo: 3, loanId: 'LN003', memberName: 'MEENA KUMARI', memberCode: 'M003', emiAmount: '1500', dueDate: '2026-04-10', status: 'Pending', branch: 'BRANCH - 002' },
            { slNo: 4, loanId: 'LN004', memberName: 'RAMESH SINGH', memberCode: 'M004', emiAmount: '5000', dueDate: '2026-04-10', status: 'Pending', branch: 'HEAD OFFICE - 001' },
            { slNo: 5, loanId: 'LN005', memberName: 'SURESH YADAV', memberCode: 'M005', emiAmount: '3000', dueDate: '2026-04-12', status: 'Partial', branch: 'BRANCH - 003' },
            { slNo: 6, loanId: 'LN006', memberName: 'LAKSHMI NARAYAN', memberCode: 'M006', emiAmount: '3500', dueDate: '2026-04-12', status: 'Pending', branch: 'HEAD OFFICE - 001' },
            { slNo: 7, loanId: 'LN007', memberName: 'GEETA DEVI', memberCode: 'M007', emiAmount: '2200', dueDate: '2026-04-15', status: 'Pending', branch: 'BRANCH - 002' },
            { slNo: 8, loanId: 'LN008', memberName: 'ANITA SINGH', memberCode: 'M008', emiAmount: '1800', dueDate: '2026-04-15', status: 'Paid', branch: 'HEAD OFFICE - 001' }
        ];

        function showLoanEmiReport() {
            var branch = document.getElementById('reportBranch').value;
            var weekDay = document.getElementById('reportWeekDay').value;
            var fromDate = document.getElementById('reportFromDate').value;
            var toDate = document.getElementById('reportToDate').value;
            
            var filteredData = loanEmiReportData.filter(function(item) {
                var matchBranch = true;
                var matchDate = true;
                
                if (branch !== 'All Branch') {
                    matchBranch = item.branch === branch;
                }
                
                if (fromDate && toDate) {
                    matchDate = item.dueDate >= fromDate && item.dueDate <= toDate;
                }
                
                return matchBranch && matchDate;
            });
            
            if (weekDay && weekDay !== '-- Select --') {
                // Filter by week day if needed
                filteredData = filteredData;
            }
            
            renderReportTable(filteredData);
            
            alert('Showing ' + filteredData.length + ' record(s)');
        }

        function renderReportTable(data) {
            var tbody = document.getElementById('loanEmiReportTableBody');
            if (!tbody) return;
            
            if (data.length === 0) {
                tbody.innerHTML = '<tr><td colspan="8" style="text-align:center">No records found</td></tr>';
                return;
            }
            
            tbody.innerHTML = '';
            for (var i = 0; i < data.length; i++) {
                var item = data[i];
                var row = tbody.insertRow();
                row.insertCell(0).innerHTML = i + 1;
                row.insertCell(1).innerHTML = item.loanId;
                row.insertCell(2).innerHTML = item.memberName;
                row.insertCell(3).innerHTML = item.memberCode;
                row.insertCell(4).innerHTML = item.emiAmount;
                row.insertCell(5).innerHTML = item.dueDate;
                row.insertCell(6).innerHTML = '<span class="status-' + item.status.toLowerCase() + '">' + item.status + '</span>';
                row.insertCell(7).innerHTML = item.branch;
            }
        }

        function closeLoanEmiReport() {
            if (confirm('Are you sure you want to close? Filters will be reset.')) {
                document.getElementById('reportBranch').value = 'All Branch';
                document.getElementById('reportWeekDay').value = '';
                document.getElementById('reportFromDate').value = '2026-04-09';
                document.getElementById('reportToDate').value = '2026-04-09';
                document.getElementById('loanEmiReportTableBody').innerHTML = '<tr><td colspan="8" style="text-align:center">Click Show to view report</td></tr>';
                alert('Closed');
            }
        }

        function showLoanEmiDaywiseReport() {
            var sections = document.querySelectorAll('.content-section');
            for (var i = 0; i < sections.length; i++) {
                sections[i].style.display = 'none';
            }
            document.getElementById('LoanEmiDaywiseReportContainer').style.display = 'block';
        }

        // Loan Part Payment Functions

        var lppLoanData = {
            memberId: 'M001',
            loanId: 'LN001',
            holderName: 'RADHIKA DEVI',
            phoneNo: '9876543210',
            product: 'TEST LOAN',
            loanAmount: '25000',
            membership: '500',
            serviceTax: '90',
            emiAmount: '2500',
            accountNo: '1234567890',
            totalPayable: '30000',
            totalPaid: '5000',
            dueAmount: '25000'
        };

        var lppPaymentRecords = [
            { payNo: '1', amount: '2500', date: '2026-03-05', branch: 'HEAD OFFICE - 001', payMode: 'CASH', chequeNo: '', accountNo: '1234567890', payUser: 'admin', remarks: 'EMI 1' },
            { payNo: '2', amount: '2500', date: '2026-04-05', branch: 'HEAD OFFICE - 001', payMode: 'CHEQUE', chequeNo: 'CHQ001', accountNo: '1234567890', payUser: 'admin', remarks: 'EMI 2' }
        ];

        function searchPartPaymentLoan() {
            var loanId = document.getElementById('lppLoanId').value.trim();
            if (!loanId) {
                alert('Please enter Loan ID');
                return;
            }
            
            document.getElementById('lppMemberId').value = lppLoanData.memberId;
            document.getElementById('lppLoanIdDisplay').value = lppLoanData.loanId;
            document.getElementById('lppHolderName').value = lppLoanData.holderName;
            document.getElementById('lppPhoneNo').value = lppLoanData.phoneNo;
            document.getElementById('lppProduct').value = lppLoanData.product;
            document.getElementById('lppLoanAmount').value = lppLoanData.loanAmount;
            document.getElementById('lppMembership').value = lppLoanData.membership;
            document.getElementById('lppServiceTax').value = lppLoanData.serviceTax;
            document.getElementById('lppEmiAmount').value = lppLoanData.emiAmount;
            document.getElementById('lppAccountNo').value = lppLoanData.accountNo;
            document.getElementById('lppTotalPayable').value = lppLoanData.totalPayable;
            document.getElementById('lppTotalPaid').value = lppLoanData.totalPaid;
            document.getElementById('lppDueAmount').value = lppLoanData.dueAmount;
            
            renderPaymentTable();
            alert('Loan details loaded for ID: ' + loanId);
        }

        function renderPaymentTable() {
            var tbody = document.getElementById('lppPaymentTableBody');
            if (!tbody) return;
            
            tbody.innerHTML = '';
            for (var i = 0; i < lppPaymentRecords.length; i++) {
                var p = lppPaymentRecords[i];
                var row = tbody.insertRow();
                row.insertCell(0).innerHTML = '<input type="text" value="' + p.payNo + '" class="pay-no" data-idx="' + i + '">';
                row.insertCell(1).innerHTML = '<input type="text" value="' + p.amount + '" class="amount" data-idx="' + i + '">';
                row.insertCell(2).innerHTML = '<input type="date" value="' + p.date + '" class="date" data-idx="' + i + '">';
                row.insertCell(3).innerHTML = '<input type="text" value="' + p.branch + '" class="branch" data-idx="' + i + '">';
                row.insertCell(4).innerHTML = '<input type="text" value="' + p.payMode + '" class="pay-mode" data-idx="' + i + '">';
                row.insertCell(5).innerHTML = '<input type="text" value="' + p.chequeNo + '" class="cheque-no" data-idx="' + i + '">';
                row.insertCell(6).innerHTML = '<input type="text" value="' + p.accountNo + '" class="account-no" data-idx="' + i + '">';
                row.insertCell(7).innerHTML = '<input type="text" value="' + p.payUser + '" class="pay-user" data-idx="' + i + '">';
                row.insertCell(8).innerHTML = '<input type="text" value="' + p.remarks + '" class="remarks" data-idx="' + i + '">';
            }
        }

        function newPartPayment() {
            document.getElementById('lppLoanId').value = '';
            document.getElementById('lppMemberId').value = '';
            document.getElementById('lppLoanIdDisplay').value = '';
            document.getElementById('lppHolderName').value = '';
            document.getElementById('lppPhoneNo').value = '';
            document.getElementById('lppProduct').value = '';
            document.getElementById('lppLoanAmount').value = '';
            document.getElementById('lppMembership').value = '';
            document.getElementById('lppServiceTax').value = '';
            document.getElementById('lppEmiAmount').value = '';
            document.getElementById('lppAccountNo').value = '';
            document.getElementById('lppLoanAgainstDeposit').value = '';
            document.getElementById('lppPaymentBy').value = '';
            document.getElementById('lppChequeDate').value = '2026-04-09';
            document.getElementById('lppBankName').value = '';
            document.getElementById('lppTotalPayable').value = '';
            document.getElementById('lppPaymentNumber').value = '';
            document.getElementById('lppPaymentAmount').value = '';
            document.getElementById('lppTransferToSb').value = '';
            document.getElementById('lppTotalPaid').value = '';
            document.getElementById('lppDueAmount').value = '';
            document.getElementById('lppCashCheckbox').checked = false;
            document.getElementById('lppCashChequeNo').value = '';
            document.getElementById('lppFromAc').value = '';
            document.getElementById('lppPaymentMode').value = 'CASH';
            document.getElementById('lppPaymentBankName').value = '';
            document.getElementById('lppPaymentRemarks').value = '';
            document.getElementById('lppCode1001').value = '';
            document.getElementById('lppPaymentTableBody').innerHTML = '<tr><td colspan="9" style="text-align:center">No payment records found</td></tr>';
            alert('Form cleared for new payment');
        }

        function savePartPayment() {
            var loanId = document.getElementById('lppLoanIdDisplay').value;
            if (!loanId) {
                alert('Please search for a loan first');
                return;
            }
            
            var paymentAmount = document.getElementById('lppPaymentAmount').value;
            if (!paymentAmount || parseFloat(paymentAmount) <= 0) {
                alert('Please enter Payment Amount');
                return;
            }
            
            alert('Part payment saved successfully!\nLoan ID: ' + loanId + '\nAmount: ₹' + paymentAmount);
        }

        function showLoanPartPayment() {
            var sections = document.querySelectorAll('.content-section');
            for (var i = 0; i < sections.length; i++) {
                sections[i].style.display = 'none';
            }
            document.getElementById('LoanPartPaymentContainer').style.display = 'block';
        }

    </script>

</body>
</html>