        </div>
    </div>

    <!-- Toast Container -->
    <div class="toast-container" id="toastContainer"></div>

    <!-- JavaScript Libraries -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap-datepicker@1.9.0/dist/js/bootstrap-datepicker.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
    <!-- Dashboard JavaScript -->
    <script>
        // Sidebar Toggle - Desktop & Mobile Support
        document.addEventListener('DOMContentLoaded', function() {
            const sidebarToggle = document.getElementById('sidebarToggle');
            const sidebar = document.getElementById('sidebar');
            const body = document.body;
            
            if (sidebarToggle && sidebar) {
                sidebarToggle.addEventListener('click', function(e) {
                    e.preventDefault();
                    
                    if (window.innerWidth > 768) {
                        // Desktop: toggle collapsed
                        sidebar.classList.toggle('collapsed');
                    } else {
                        // Mobile: toggle show overlay
                        sidebar.classList.toggle('show');
                        body.classList.toggle('sidebar-open');
                    }
                });
                
                // Mobile: Close sidebar on outside click
                document.addEventListener('click', function(e) {
                    if (window.innerWidth <= 768 &&
                        sidebar.classList.contains('show') &&
                        !sidebar.contains(e.target) &&
                        !sidebarToggle.contains(e.target)) {
                        sidebar.classList.remove('show');
                        body.classList.remove('sidebar-open');
                    }
                });
                
                // Mobile: Close sidebar on link click
                if (window.innerWidth <= 768) {
                    const sidebarLinks = sidebar.querySelectorAll('a');
                    sidebarLinks.forEach(link => {
                        link.addEventListener('click', function() {
                            sidebar.classList.remove('show');
                            body.classList.remove('sidebar-open');
                        });
                    });
                }
            }
        });

        // Toast Notification System
        function showToast(message, type = 'info', duration = 5000) {
            const toastContainer = document.getElementById('toastContainer');
            if (!toastContainer) return;
            
            const toast = document.createElement('div');
            toast.className = `toast fade-in-up`;
            
            const iconMap = {
                'success': 'fas fa-check-circle text-success',
                'error': 'fas fa-exclamation-circle text-danger',
                'warning': 'fas fa-exclamation-triangle text-warning',
                'info': 'fas fa-info-circle text-info'
            };
            
            toast.innerHTML = `
                <div class="d-flex align-items-center">
                    <i class="${iconMap[type]} me-2"></i>
                    <span>${message}</span>
                    <button type="button" class="btn-close btn-close-white ms-auto" onclick="this.parentElement.parentElement.remove()"></button>
                </div>
            `;
            
            toastContainer.appendChild(toast);
            
            setTimeout(() => {
                if (toast.parentNode) {
                    toast.remove();
                }
            }, duration);
        }

        // Enhanced DataTable initialization
        $(document).ready(function() {
            if ($('#dataTable').length) {
                $('#dataTable').DataTable({
                    "pageLength": 25,
                    "responsive": true,
                    "order": [[0, "desc"]],
                    "language": {
                        "search": "",
                        "searchPlaceholder": "Search records...",
                        "lengthMenu": "Show _MENU_ entries",
                        "info": "Showing _START_ to _END_ of _TOTAL_ entries",
                        "paginate": {
                            "first": "First",
                            "last": "Last",
                            "next": "Next",
                            "previous": "Previous"
                        }
                    },
                    "dom": '<"row"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6"f>>t<"row"<"col-sm-12 col-md-5"i><"col-sm-12 col-md-7"p>>',
                    "drawCallback": function(settings) {
                        // Add animation to new rows
                        $(this).find('tbody tr').addClass('fade-in-up');
                    }
                });
            }
        });

        // Auto-refresh functionality
        let autoRefresh = false;
        let refreshInterval;

        function toggleAutoRefresh() {
            autoRefresh = !autoRefresh;
            if (autoRefresh) {
                refreshInterval = setInterval(() => {
                    location.reload();
                }, 30000); // Refresh every 30 seconds
                showToast('Auto-refresh enabled (30s)', 'success');
            } else {
                clearInterval(refreshInterval);
                showToast('Auto-refresh disabled', 'info');
            }
        }

        // Real-time updates with live polling
        <?php if (isset($page) && $page == 'dashboard') { ?>
        
        function generateConversionHTML(conversion) {
            const country = conversion.country.toLowerCase();
            let os = '-';
            const osLower = (conversion.os || '').toLowerCase();
            
            if (['web', 'desktop', 'windows'].includes(osLower)) {
                os = '<i class="fas fa-desktop text-primary"></i>';
            } else if (['wap', 'android', 'ios'].includes(osLower)) {
                os = '<i class="fas fa-mobile-alt text-success"></i>';
            } else if (osLower === 'tablet') {
                os = '<i class="fas fa-tablet-alt text-info"></i>';
            }
            
            const payout = (parseFloat(conversion.payout) || 0).toFixed(2);
            const time = conversion.date.split(' ')[1] || '--:--:--';
            
            return `<tr class="searchable-row highlight-row">
                <td>
                    <a href="statsID.php?id=${conversion.subid}" class="text-decoration-none">
                        <i class="fas fa-user me-1"></i>${conversion.subid}
                    </a>
                </td>
                <td class="text-center"><img src="assets/network/${conversion.network}.png" alt="${conversion.network}" height="24"></td>
                <td class="text-center">${os}</td>
                <td class="text-center">
                    <span class="flag-icon flag-icon-${country} me-1"></span>${country.toUpperCase()}
                </td>
                <td class="text-center text-success fw-bold">$${payout}</td>
                <td class="text-center text-white small">${time}</td>
            </tr>`;
        }
        
        function checkForUpdates() {
            const lastId = parseInt($('#last_id').val()) || 0;
            
            console.log('Checking for updates - lastId:', lastId);
            
            $.ajax({
                url: 'notif.php',
                method: 'GET',
                dataType: 'json',
                data: {
                    last_id: lastId
                },
                success: function(response) {
                    console.log('Notif response:', response);
                    
                    if (response.result === true && response.data && response.data.length > 0) {
                        let totalNewAmount = 0;
                        const newConversions = response.data || [];
                        
                        console.log('New conversions:', newConversions.length);
                        
                        // Add new rows to table (oldest first, so newest on top)
                        for (let i = newConversions.length - 1; i >= 0; i--) {
                            const conversion = newConversions[i];
                            console.log('Adding conversion:', conversion.subid, '$' + conversion.payout);
                            
                            const html = generateConversionHTML(conversion);
                            $('#dataTable tbody').prepend(html);
                            
                            totalNewAmount += parseFloat(conversion.payout || 0);
                            
                            // Update last_id
                            const convId = parseInt(conversion.id);
                            const currentLastId = parseInt($('#last_id').val()) || 0;
                            if (convId > currentLastId) {
                                $('#last_id').val(convId);
                            }
                        }
                        
                        // Show notification toast
                        showToast(`✨ ${newConversions.length} new conversion(s)! +$${totalNewAmount.toFixed(2)}`, 'success');
                        
                        // PLAY AUDIO - direct audio creation
                        try {
                            const audio = new Audio('./audio/dingdong.wav');
                            audio.volume = 1;
                            audio.play().then(() => {
                                console.log('✅ Audio played');
                            }).catch(err => {
                                console.log('❌ Audio play error:', err);
                            });
                        } catch(e) {
                            console.log('❌ Audio error:', e);
                        }
                        
                        // Animate new rows
                        $('#dataTable tbody tr').first().addClass('highlight-row');
                        setTimeout(function() {
                            $('#dataTable tbody tr').first().removeClass('highlight-row');
                        }, 2000);
                        
                        // Update total payout in footer
                        updateTotalPayout();
                    }
                },
                error: function(err) {
                    console.log('Update check error:', err);
                }
            });
        }

        function updateTotalPayout() {
            let total = 0;
            $('#dataTable tbody tr').each(function() {
                const amountText = $(this).find('td:eq(5)').text().replace('$', '').trim();
                const amount = parseFloat(amountText);
                if (!isNaN(amount)) {
                    total += amount;
                }
            });
            
            $('#dataTable tfoot tr td:last-child').text('$' + total.toFixed(2));
        }

        // Auto-check for updates every 5 seconds
        $(document).ready(function() {
            checkForUpdates(); // First check immediately
            setInterval(checkForUpdates, 5000); // Then every 5 seconds
        });
        <?php } ?>

        // Date picker initialization
        $('.datepicker').datepicker({
            format: 'yyyy-mm-dd',
            autoclose: true,
            todayHighlight: true
        });

        // Search functionality
        $('#globalSearch').on('keyup', function() {
            const searchTerm = $(this).val().toLowerCase();
            $('.searchable-row').each(function() {
                const text = $(this).text().toLowerCase();
                $(this).toggle(text.indexOf(searchTerm) > -1);
            });
        });

        // Smooth scrolling for anchor links
        $('a[href^="#"]').on('click', function(event) {
            var target = $(this.getAttribute('href'));
            if (target.length) {
                event.preventDefault();
                $('html, body').stop().animate({
                    scrollTop: target.offset().top - 100
                }, 1000);
            }
        });

        // Loading states for buttons
        $('.btn-loading').on('click', function() {
            const btn = $(this);
            const originalText = btn.html();
            btn.html('<span class="loading me-2"></span>Loading...').prop('disabled', true);
            
            setTimeout(() => {
                btn.html(originalText).prop('disabled', false);
            }, 2000);
        });

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

    <?php if (isset($page) && $page == 'dashboard') { ?>
    <!-- Dashboard-specific scripts -->
    <!-- <script src="js/notif.js"></script> --> <!-- Disabled - using new live update system -->
    <script src="js/hitstat.js"></script>
    <audio id="notificationSound" src="audio/dingdong.wav" preload="auto"></audio>
    <?php } ?>

    <script>
        // Page-specific initialization
        <?php if (isset($page)) { ?>
        console.log('Dashboard page loaded: <?= $page; ?>');
        <?php } ?>
        
        // Add fade-in animation to cards
        $('.stat-card, .content-card').each(function(index) {
            $(this).css('animation-delay', (index * 0.1) + 's').addClass('fade-in-up');
        });
    </script>
</body>
</html>