

function initApproverDropdown() {
    fetch('trips/view/get_approvers.php')
        .then(res => res.json())
        .then(data => {
            approvers = data;
            renderList(data);
        })
        .catch(err => console.error('Failed to load approvers:', err));
}

function renderList(list) {
    const container = document.getElementById("approverList");
    if (!container) return;
    
    container.innerHTML = "";

    list.forEach(user => {
        const div = document.createElement("div");
        div.className = "approver-item";
        div.onclick = () => selectApprover(user);

        div.innerHTML = `
            <img src="${user.profile_image_path || 'images/img1.jpg'}" class="approver-img" alt="">
            <div class="approver-info">
                <div class="approver-name">${user.name}</div>
                <div class="approver-email">${user.email}</div>
            </div>
        `;

        container.appendChild(div);
    });
}

function selectApprover(user) {
    const search = document.getElementById("approverSearch");
    const hidden = document.getElementById("approver_id");
    
    if (search) {
        search.value = user.name + " (" + user.email + ")";
    }
    
    if (hidden) {
        hidden.value = user.id;
    }
    
    // Close dropdown
    const dropdownList = document.getElementById("approverList");
    if (dropdownList) {
        dropdownList.style.display = 'none';
    }
}

document.addEventListener('DOMContentLoaded', function() {
    const search = document.getElementById("approverSearch");
    const dropdownList = document.getElementById("approverList");
    
    if (!search || !dropdownList) return;
    
    // Close dropdown when clicking outside
    document.addEventListener('click', function(event) {
        if (!event.target.closest('.approver-dropdown')) {
            dropdownList.style.display = 'none';
        }
    });
    
    search.addEventListener("input", function () {
        const value = this.value.toLowerCase();
        dropdownList.style.display = value ? 'block' : 'none';

        const filtered = approvers.filter(u =>
            u.name.toLowerCase().includes(value) ||
            u.email.toLowerCase().includes(value)
        );

        renderList(filtered);
    });
    
    // Show dropdown on focus
    search.addEventListener('focus', function() {
        if (approvers.length > 0) {
            dropdownList.style.display = 'block';
        }
    });
});

// Initialize when page loads
initApproverDropdown();

