    </div> <!-- End of main-content -->

    <!-- Scripts -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>


// Mobile Menu Functionality
const initializeMobileMenu = () => {
    const sidebar = document.getElementById('sidebar');
    const sidebarToggle = document.getElementById('sidebarToggle');
    const mainContent = document.querySelector('.main-content');

    // Add overlay div if it doesn't exist
    let sidebarOverlay = document.getElementById('sidebarOverlay');
    if (!sidebarOverlay) {
        sidebarOverlay = document.createElement('div');
        sidebarOverlay.id = 'sidebarOverlay';
        sidebarOverlay.className = 'sidebar-overlay';
        document.body.appendChild(sidebarOverlay);
    }

    // Toggle menu function
    const toggleSidebar = () => {
        sidebar.classList.toggle('show');
        sidebarOverlay.classList.toggle('show');
        document.body.style.overflow = sidebar.classList.contains('show') ? 'hidden' : '';
    };

    // Toggle button click handler
    if (sidebarToggle) {
        sidebarToggle.addEventListener('click', (e) => {
            e.stopPropagation();
            toggleSidebar();
        });
    }

    // Overlay click handler
    sidebarOverlay.addEventListener('click', toggleSidebar);

    // Close on outside click
    document.addEventListener('click', (e) => {
        if (window.innerWidth <= 992) {
            if (sidebar.classList.contains('show') && 
                !sidebar.contains(e.target) && 
                !sidebarToggle.contains(e.target)) {
                toggleSidebar();
            }
        }
    });

    // Close on escape key
    document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape' && sidebar.classList.contains('show')) {
            toggleSidebar();
        }
    });

    // Handle window resize
    window.addEventListener('resize', () => {
        if (window.innerWidth > 992) {
            sidebar.classList.remove('show');
            sidebarOverlay.classList.remove('show');
            document.body.style.overflow = '';
        }
    });

    // Prevent sidebar clicks from closing
    sidebar.addEventListener('click', (e) => {
        e.stopPropagation();
    });

    // Initialize main content toggle button
    const mainSidebarToggle = document.getElementById('mainSidebarToggle');
    if (mainSidebarToggle) {
        mainSidebarToggle.addEventListener('click', toggleSidebar);
    }
};

// Initialize everything when DOM is loaded
document.addEventListener('DOMContentLoaded', function() {
    // Initialize mobile menu
    initializeMobileMenu();

    // Your other initializations...
    // (Keep your existing chart initializations and other code here)
});






document.addEventListener('DOMContentLoaded', function() {
    // Initialize Real-time Clock
    function updateClock() {
        const now = new Date();
        const options = { 
            weekday: 'long', 
            year: 'numeric', 
            month: 'long', 
            day: 'numeric',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        };
        document.getElementById('realTimeClock').textContent = now.toLocaleDateString('en-US', options);
    }
    setInterval(updateClock, 1000);
    updateClock();

    // Initialize Charts
    // Transaction Trend Chart
    const trendCtx = document.getElementById('transactionTrendChart');
    if (trendCtx) {
        new Chart(trendCtx, {
            type: 'line',
            data: {
                labels: <?php echo json_encode(array_map(function($item) {
                    return date('M j', strtotime($item['month']));
                }, $transactionHistory)); ?>,
                datasets: [{
                    label: 'Credits',
                    data: <?php echo json_encode(array_map(function($item) {
                        return $item['credits'] ?? 0;
                    }, $transactionHistory)); ?>,
                    borderColor: '#059669',
                    backgroundColor: 'rgba(5, 150, 105, 0.1)',
                    fill: true,
                    tension: 0.4,
                    borderWidth: 2,
                    pointRadius: 4,
                    pointHoverRadius: 6,
                    pointBackgroundColor: '#fff',
                    pointHoverBackgroundColor: '#059669',
                    pointBorderColor: '#059669',
                    pointHoverBorderColor: '#fff',
                    pointBorderWidth: 2,
                    pointHoverBorderWidth: 2
                }, {
                    label: 'Debits',
                    data: <?php echo json_encode(array_map(function($item) {
                        return $item['debits'] ?? 0;
                    }, $transactionHistory)); ?>,
                    borderColor: '#dc2626',
                    backgroundColor: 'rgba(220, 38, 38, 0.1)',
                    fill: true,
                    tension: 0.4,
                    borderWidth: 2,
                    pointRadius: 4,
                    pointHoverRadius: 6,
                    pointBackgroundColor: '#fff',
                    pointHoverBackgroundColor: '#dc2626',
                    pointBorderColor: '#dc2626',
                    pointHoverBorderColor: '#fff',
                    pointBorderWidth: 2,
                    pointHoverBorderWidth: 2
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                interaction: {
                    mode: 'index',
                    intersect: false
                },
                plugins: {
                    legend: {
                        position: 'top',
                        align: 'end',
                        labels: {
                            boxWidth: 8,
                            usePointStyle: true,
                            pointStyle: 'circle',
                            padding: 20,
                            font: {
                                size: 12,
                                family: "'Poppins', sans-serif"
                            }
                        }
                    },
                    tooltip: {
                        backgroundColor: 'white',
                        titleColor: '#1a1a1a',
                        titleFont: {
                            size: 13,
                            family: "'Poppins', sans-serif",
                            weight: '600'
                        },
                        bodyColor: '#64748b',
                        bodyFont: {
                            size: 12,
                            family: "'Poppins', sans-serif"
                        },
                        borderColor: '#e5e7eb',
                        borderWidth: 1,
                        padding: 12,
                        boxPadding: 4,
                        callbacks: {
                            label: function(context) {
                                let label = context.dataset.label || '';
                                if (label) {
                                    label += ': ';
                                }
                                label += '<?php echo $user['currency']; ?> ' + context.parsed.y.toLocaleString();
                                return label;
                            }
                        }
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        grid: {
                            drawBorder: false,
                            color: '#e5e7eb'
                        },
                        ticks: {
                            font: {
                                size: 12,
                                family: "'Poppins', sans-serif"
                            },
                            color: '#64748b',
                            callback: function(value) {
                                return '<?php echo $user['currency']; ?> ' + value.toLocaleString();
                            }
                        }
                    },
                    x: {
                        grid: {
                            display: false
                        },
                        ticks: {
                            font: {
                                size: 12,
                                family: "'Poppins', sans-serif"
                            },
                            color: '#64748b'
                        }
                    }
                }
            }
        });
    }

    // Distribution Chart
    const distributionCtx = document.getElementById('transactionDistributionChart');
    if (distributionCtx) {
        const credits = <?php echo $monthlySummary['total_credits'] ?? 0; ?>;
        const debits = <?php echo $monthlySummary['total_debits'] ?? 0; ?>;
        const total = credits + debits;

        new Chart(distributionCtx, {
            type: 'doughnut',
            data: {
                labels: ['Credits', 'Debits'],
                datasets: [{
                    data: [credits, debits],
                    backgroundColor: ['#059669', '#dc2626'],
                    borderWidth: 0,
                    hoverOffset: 4,
                    borderRadius: 4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                cutout: '75%',
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: {
                            padding: 20,
                            font: {
                                size: 12,
                                family: "'Poppins', sans-serif"
                            },
                            usePointStyle: true,
                            pointStyle: 'circle'
                        }
                    },
                    tooltip: {
                        backgroundColor: 'white',
                        titleColor: '#1a1a1a',
                        titleFont: {
                            size: 13,
                            family: "'Poppins', sans-serif",
                            weight: '600'
                        },
                        bodyColor: '#64748b',
                        bodyFont: {
                            size: 12,
                            family: "'Poppins', sans-serif"
                        },
                        borderColor: '#e5e7eb',
                        borderWidth: 1,
                        padding: 12,
                        boxPadding: 4,
                        callbacks: {
                            label: function(context) {
                                const value = context.raw;
                                const percentage = ((value / total) * 100).toFixed(1);
                                return `${context.label}: ${percentage}% (<?php echo $user['currency']; ?> ${value.toLocaleString()})`;
                            }
                        }
                    }
                }
            }
        });
    }

    // Transaction Search
    const searchInput = document.getElementById('transactionSearch');
    if (searchInput) {
        searchInput.addEventListener('input', function() {
            const searchTerm = this.value.toLowerCase();
            document.querySelectorAll('#transactionsTable tbody tr').forEach(row => {
                const text = row.textContent.toLowerCase();
                row.style.display = text.includes(searchTerm) ? '' : 'none';
            });
        });
    }

    // Table Sorting
    document.querySelectorAll('.sortable').forEach(header => {
        header.addEventListener('click', function() {
            const table = document.getElementById('transactionsTable');
            const rows = Array.from(table.querySelectorAll('tbody tr'));
            const column = this.dataset.sort;
            const ascending = !this.classList.contains('sort-asc');

            rows.sort((a, b) => {
                let aVal = a.querySelector(`td:nth-child(${getColumnIndex(column)})`).textContent;
                let bVal = b.querySelector(`td:nth-child(${getColumnIndex(column)})`).textContent;

                if (column === 'amount') {
                    aVal = parseFloat(aVal.replace(/[^0-9.-]+/g, ''));
                    bVal = parseFloat(bVal.replace(/[^0-9.-]+/g, ''));
                }

                if (ascending) {
                    return aVal > bVal ? 1 : -1;
                } else {
                    return aVal < bVal ? 1 : -1;
                }
            });

            document.querySelectorAll('.sortable').forEach(h => h.classList.remove('sort-asc', 'sort-desc'));
            this.classList.add(ascending ? 'sort-asc' : 'sort-desc');

            const tbody = table.querySelector('tbody');
            tbody.innerHTML = '';
            rows.forEach(row => tbody.appendChild(row));
        });
    });




    // Initialize tooltips
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
});

// Transaction Details Modal
function viewTransactionDetails(element) {
    const transaction = JSON.parse(element.closest('tr').dataset.transaction);
    const modal = new bootstrap.Modal(document.getElementById('transactionModal'));
    
    document.getElementById('transactionModalContent').innerHTML = `
        <div class="transaction-details">
            <div class="mb-4">
                <div class="transaction-icon bg-${transaction.type === 'credit' ? 'success' : 'danger'}-subtle 
                            text-${transaction.type === 'credit' ? 'success' : 'danger'} mx-auto mb-3">
                    <i class='bx bx-${transaction.type === 'credit' ? 'up-arrow-alt' : 'down-arrow-alt'}'></i>
                </div>
                <h4 class="text-${transaction.type === 'credit' ? 'success' : 'danger'}">
                    ${transaction.type === 'credit' ? '+' : '-'} <?php echo $user['currency']; ?> 
                    ${parseFloat(transaction.amount).toLocaleString()}
                </h4>
            </div>
            <div class="transaction-info">
                <div class="row mb-3">
                    <div class="col-6 text-start">
                        <small class="text-muted d-block">Transaction ID</small>
                        <span class="fw-medium">#${String(transaction.id).padStart(6, '0')}</span>
                    </div>
                    <div class="col-6 text-end">
                        <small class="text-muted d-block">Date & Time</small>
                        <span class="fw-medium">${new Date(transaction.created_at).toLocaleString()}</span>
                    </div>
                </div>
                <div class="row mb-3">
                    <div class="col-6 text-start">
                        <small class="text-muted d-block">Type</small>
                        <span class="badge bg-${transaction.type === 'credit' ? 'success' : 'danger'}-subtle 
                                    text-${transaction.type === 'credit' ? 'success' : 'danger'}">
                            ${transaction.type}
                        </span>
                    </div>
                    <div class="col-6 text-end">
                        <small class="text-muted d-block">Status</small>
                        <span class="badge bg-${transaction.status === 'completed' ? 'success' : 'warning'}-subtle 
                                    text-${transaction.status === 'completed' ? 'success' : 'warning'}">
                            ${transaction.status}
                        </span>
                    </div>
                </div>
                <div class="mb-4">
                    <small class="text-muted d-block">Description</small>
                    <span class="fw-medium">${transaction.description}</span>
                </div>
                <div class="d-flex gap-2">
                    <button class="btn btn-primary flex-grow-1" onclick="downloadReceipt(${transaction.id})">
                        <i class='bx bx-download me-2'></i> Download Receipt
                    </button>
                    <button class="btn btn-outline-danger" onclick="reportIssue(${transaction.id})">
                        <i class='bx bx-error-circle'></i>
                    </button>
                </div>
            </div>
        </div>
    `;
    
    modal.show();
}

// Download Receipt
function downloadReceipt(transactionId) {
    Swal.fire({
        title: 'Downloading Receipt',
        text: 'Your receipt is being generated...',
        timer: 2000,
        timerProgressBar: true,
        didOpen: () => {
            Swal.showLoading();
        }
    }).then(() => {
        Swal.fire({
            icon: 'success',
            title: 'Receipt Downloaded',
            showConfirmButton: false,
            timer: 1500
        });
    });
}

// Report Issue
function reportIssue(transactionId) {
    Swal.fire({
        title: 'Report an Issue',
        html: `
            <form id="issueForm">
                <div class="mb-3">
                    <label class="form-label">Issue Type</label>
                    <select class="form-select" required>
                        <option value="">Select an issue type</option>
                        <option value="wrong_amount">Wrong Amount</option>
                        <option value="failed">Failed Transaction</option>
                        <option value="unauthorized">Unauthorized Transaction</option>
                        <option value="other">Other</option>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label">Description</label>
                    <textarea class="form-control" rows="3" required></textarea>
                </div>
            </form>
        `,
        showCancelButton: true,
        confirmButtonText: 'Submit',
        showLoaderOnConfirm: true,
        preConfirm: () => {
            return new Promise(resolve => setTimeout(resolve, 2000));
        }
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire({
                icon: 'success',
                title: 'Issue Reported',
                text: 'We will investigate and get back to you soon.',
                timer: 2000,
                showConfirmButton: false
            });
        }
    });
}

// Real-time Balance Update
function startBalanceUpdate() {
    setInterval(() => {
        fetch('get_balance.php')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const balanceElement = document.querySelector('.balance-amount');
                    const oldBalance = parseFloat(balanceElement.textContent.replace(/[^0-9.-]+/g, ''));
                    const newBalance = parseFloat(data.balance);

                    if (oldBalance !== newBalance) {
                        balanceElement.textContent = new Intl.NumberFormat('en-US', {
                            style: 'currency',
                            currency: '<?php echo $user['currency']; ?>'
                        }).format(newBalance);

                        balanceElement.classList.add('balance-updated');
                        setTimeout(() => balanceElement.classList.remove('balance-updated'), 1000);
                    }
                }
            });
    }, 30000); // Update every 30 seconds
}

startBalanceUpdate();
</script>
<script>
    // Logout functionality
function handleLogout(event) {
    if (event) {
        event.preventDefault();
    }

    Swal.fire({
        title: 'Logout Confirmation',
        text: 'Are you sure you want to logout?',
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: 'Yes, Logout',
        cancelButtonText: 'Cancel',
        confirmButtonColor: '#dc2626',
        cancelButtonColor: '#6b7280',
        reverseButtons: true
    }).then((result) => {
        if (result.isConfirmed) {
            showLogoutProcess();
        }
    });



    
}

function showLogoutProcess() {
    Swal.fire({
        title: 'Logging Out',
        text: 'Please wait while we securely log you out...',
        timer: 1500,
        timerProgressBar: true,
        didOpen: () => {
            Swal.showLoading();
            processLogout();
        },
        allowOutsideClick: false,
        allowEscapeKey: false,
        allowEnterKey: false
    });
}

function processLogout() {
    fetch('../logout.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
        },
        credentials: 'same-origin'
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            Swal.fire({
                icon: 'success',
                title: 'Logged Out Successfully',
                text: 'You will be redirected to the login page.',
                timer: 1500,
                showConfirmButton: false
            }).then(() => {
                window.location.href = data.redirect;
            });
        } else {
            throw new Error(data.message || 'Logout failed');
        }
    })
    .catch(error => {
        Swal.fire({
            icon: 'error',
            title: 'Logout Error',
            text: error.message || 'An error occurred during logout. Please try again.',
            confirmButtonText: 'Try Again'
        });
    });
}

// Add this to your session timeout handler
function handleSessionTimeout() {
    Swal.fire({
        title: 'Session Expiring',
        text: 'Your session will expire in 1 minute. Would you like to stay logged in?',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Stay Logged In',
        cancelButtonText: 'Logout',
        reverseButtons: true
    }).then((result) => {
        if (result.isConfirmed) {
            // Refresh session
            fetch('refresh_session.php');
        } else {
            handleLogout();
        }
    });
}

// Add event listeners
document.addEventListener('DOMContentLoaded', function() {
    // Add click handler to logout buttons/links
    const logoutButtons = document.querySelectorAll('[data-action="logout"]');
    logoutButtons.forEach(button => {
        button.addEventListener('click', handleLogout);
    });

    // Handle session timeout
    let sessionTimeout;
    function resetSessionTimeout() {
        clearTimeout(sessionTimeout);
        sessionTimeout = setTimeout(handleSessionTimeout, 29 * 60 * 1000); // 29 minutes
    }

    // Reset timeout on user activity
    ['mousedown', 'keydown', 'scroll', 'touchstart'].forEach(event => {
        document.addEventListener(event, resetSessionTimeout);
    });
    resetSessionTimeout();
});


// Copy Account Number Function
function copyAccountNumber() {
    const accountNumber = document.querySelector('.account-number-text').innerText;
    
    // Create a temporary textarea element to copy from
    const textarea = document.createElement('textarea');
    textarea.value = accountNumber;
    textarea.style.position = 'fixed';  // Prevent scrolling to bottom
    document.body.appendChild(textarea);
    textarea.select();
    
    try {
        // Execute copy command
        const successful = document.execCommand('copy');
        
        if (successful) {
            // Show success tooltip or message
            const copyBtn = document.querySelector('[data-copy="account-number"]');
            
            // If using Bootstrap tooltips
            if (bootstrap.Tooltip && copyBtn) {
                const tooltip = bootstrap.Tooltip.getInstance(copyBtn);
                if (tooltip) {
                    const originalTitle = tooltip._config.title;
                    tooltip.hide();
                    tooltip._config.title = 'Copied!';
                    tooltip.show();
                    
                    // Reset tooltip after 2 seconds
                    setTimeout(() => {
                        tooltip.hide();
                        tooltip._config.title = originalTitle;
                    }, 2000);
                } else {
                    // If tooltip isn't initialized, use SweetAlert
                    showCopiedAlert();
                }
            } else {
                // Fallback to SweetAlert if Bootstrap tooltip isn't available
                showCopiedAlert();
            }
        } else {
            console.error('Copy command was unsuccessful');
        }
    } catch (err) {
        console.error('Error copying text: ', err);
    } finally {
        // Clean up
        document.body.removeChild(textarea);
    }
}

// Helper function to show a copied alert using SweetAlert
function showCopiedAlert() {
    Swal.fire({
        icon: 'success',
        title: 'Copied!',
        text: 'Account number copied to clipboard',
        toast: true,
        position: 'top-end',
        showConfirmButton: false,
        timer: 2000,
        timerProgressBar: true
    });
}

// Function to refresh balance via AJAX
function refreshBalance() {
    fetch('api/get_balance.php')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const balanceElement = document.querySelector('.amount');
                if (balanceElement) {
                    balanceElement.textContent = parseFloat(data.balance).toFixed(2);
                    
                    // Show success message
                    Swal.fire({
                        icon: 'success',
                        title: 'Balance Updated',
                        toast: true,
                        position: 'top-end',
                        showConfirmButton: false,
                        timer: 2000,
                        timerProgressBar: true
                    });
                }
            }
        })
        .catch(error => {
            console.error('Error refreshing balance:', error);
            Swal.fire({
                icon: 'error',
                title: 'Update Failed',
                text: 'Could not refresh balance',
                toast: true,
                position: 'top-end',
                showConfirmButton: false,
                timer: 2000
            });
        });
}





</script>


<!--Start of Tawk.to Script-->
<script type="text/javascript">
var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
(function(){
var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
s1.async=true;
s1.src='https://embed.tawk.to/698919832510d91c3c5b9ece/1jgvonb1o';
s1.charset='UTF-8';
s1.setAttribute('crossorigin','*');
s0.parentNode.insertBefore(s1,s0);
})();
</script>
<!--End of Tawk.to Script-->
</body>
</html>
