    $(document).ready(function() {
      $("#autocomplete-search").autocomplete({
        source: function(request, response) {
          $.ajax({
            url: "getprojects", // Create this route in your controller
            dataType: "json",
            data: {
              term: request.term
            },
            success: function(data) {
              response(data);
            }
          });
        },
        minLength: 2, // Minimum characters before triggering
        select: function(event, ui) {
         // console.log("Selected: " + ui.item.value);
          console.log("Selected ID: " + ui.item.url);
            console.log("Selected Value: " + ui.item.value);
          // Optional: redirect or fill some input
          window.location.href = ui.item.url
        },
        open: function() {
            // Additional positioning if needed
            $(this).autocomplete("widget").css({
                "z-index": 10000,
                "position": "absolute"
            });
        }
      });
    });
    $(document).ready(function(){
                let selectedCountries = [];

                // Handle checkbox selection
                $('.dropdown-menu input[type="checkbox"]').on('change', function() {
                    selectedCountries = $('.dropdown-menu input[type="checkbox"]:checked')
                        .map(function() {
                            return $(this).val();
                        }).get(); // Get checked values as an array
                   
                    if (selectedCountries.length > 0) {
                        showCurrency(selectedCountries);
                    }else{
                        showCurrency();
                    } 
                });
                
                var selectedExistCountries = $('.dropdown-menu input[type="checkbox"]:checked');
                if (selectedExistCountries.length > 0) {
                    let selectedValues = [];
                    selectedExistCountries.each(function() {
                        selectedValues.push($(this).val()); // Get the value of each checked checkbox
                    });
                    console.log(selectedValues,'selectedCountries');
                        showCurrency(selectedValues); // Trigger searchData automatically
                }
    });
    
    function showCurrency(selectedCountries = []){
        $.ajax({
                url: 'getcurrency',
                method: 'get',
                data:{selected_countries:selectedCountries},
                dataType: 'json',
                beforeSend : function(){
                    //$('#loader').show();
                },
                success: function(data) {
                    html = '';
                    if(data.length > 0){
                        data.map(function(val){
                            html += '<span class="dropdown-item currency-dropdown" data-currency="'+val.currency_code+'">'+val.currency_code+'</span>';
                        })
                        html += '<span class="dropdown-item currency-dropdown" data-currency="USD">USD</span>';
                    }
                    
                    $('.currencydropdown').html(html);
                }
        });
    }
    
    document.addEventListener('DOMContentLoaded', function() {
        const notificationBell = document.querySelector('.notification-dropdown');
        
        // Load notifications when bell is clicked
        notificationBell.addEventListener('show.bs.dropdown', function() {
            fetchNotifications();
        });
    
        // Poll for new notifications every 30 seconds
        setInterval(fetchNotificationCount, 30000);
        fetchNotificationCount(); // Initial load
    });

    function fetchNotifications() {
    fetch('/notifications')
        .then(response => response.json())
        .then(data => {
            const list = document.querySelector('.notification-list');
            list.innerHTML = '';
            
            if (data.length === 0) {
                list.innerHTML = '<li class="dropdown-item">No notifications</li>';
                return;
            }
            
            data.forEach(notification => {
                const item = document.createElement('li');
                item.className = `dropdown-item notification-item ${notification.is_read ? '' : 'unread'}`;
                let innerHTML = `
                    <div class="d-flex justify-content-between align-items-center">
                        <span>${notification.message}</span>
                `;
            
                if (notification.action === 'delete') {
                    innerHTML += `
                        <button class="btn btn-sm btn-outline-primary mark-read-btn" data-id="${notification.id}">
                            Mark as Read
                        </button>
                    `;
                }
            
                innerHTML += `</div>`;
                item.innerHTML = innerHTML;

                
                item.addEventListener('click', () => {
                    markAsRead(notification.id);
                    // Optional: Redirect to relevant page
                    if(notification.action == 'delete'){
                      window.location.reload();  
                    }else{
                         window.location.href = getNotificationUrl(notification);
                    }
                    
                });
                
                list.appendChild(item);
            });
        });
}

    function fetchNotificationCount() {
        fetch('/notifications')
            .then(response => response.json())
            .then(data => {
                const unreadCount = data.filter(n => n.is_read === "0").length;
                const countBadge = document.querySelector('.notification-count');
                
                if (countBadge) {
                    countBadge.textContent = unreadCount;
                    countBadge.style.display = unreadCount > 0 ? 'inline-block' : 'none';
                }
            })
            .catch(error => console.error('Error fetching notification count:', error));
    }
    function markAsRead(notificationId) {
        fetch(`/notifications/mark-read/${notificationId}`, { 
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            }
        }).catch(error => console.error('Error marking as read:', error));
    }
    function formatTime(dateString) {
        const date = new Date(dateString);
        return date.toLocaleDateString(); 
    }
    
    // Optional: Generate URL based on notification type
    function getNotificationUrl(notification) {
        // If action is 'delete', don't redirect (mark as read only)
        if (notification.action === 'delete') {
            return 'javascript:void(0);';
        }
        
        // Otherwise, handle normal redirection based on page
        switch(notification.page) {
            case 'users': 
                return `<?= base_url($type.'/users?user_id=') ?>${notification.page_id}`;
            case 'projects': 
                return `<?= base_url($type.'/view_project/') ?>${notification.page_id}`;
            case 'events': 
                return `<?= base_url($type.'/view_event?event_id=') ?>${notification.page_id}`;
            case 'ministry': 
                return `<?= base_url($type.'/ministries?ministry_id=') ?>${notification.page_id}`;
            case 'institutions': 
                return `<?= base_url($type.'/institutions?institution_id=') ?>${notification.page_id}`;
            default: 
                return '#';
        }
    }