document.addEventListener('DOMContentLoaded', function () {
    const fname = document.getElementById('fname');
    const campus = document.getElementById('campus');
    const branch = document.getElementById('branch');
    const lang = document.getElementById('lang');
    const counselor = document.getElementById('counselor');

    function fetchCounselors() {
        const campusValue = campus.value;
        const branchValue = branch.value;
        const langValue = lang.value;

        if (!campusValue || !branchValue || !langValue) {
            counselor.innerHTML = '<option value="">Select a Counselor</option>';
            counselor.classList.add('disabled');
            counselor.disabled = true;
            return;
        }

        const xhr = new XMLHttpRequest();
        xhr.open('GET', `fetch_counselors.php?campus=${campusValue}&branch=${branchValue}&lang=${langValue}`, true);
        xhr.onload = function () {
            if (xhr.status === 200) {
                const response = JSON.parse(xhr.responseText);
                counselor.innerHTML = '<option value="">Select a Counselor</option>';
                response.forEach(function (item) {
                    const option = document.createElement('option');
                    option.value = item.user_id;
                    option.textContent = item.user_first_name;
                    counselor.appendChild(option);
                });
                counselor.classList.remove('disabled');
                counselor.disabled = false;
            }
        };
        xhr.send();
    }

    fname.addEventListener('input', fetchCounselors);
    campus.addEventListener('change', fetchCounselors);
    branch.addEventListener('change', fetchCounselors);
    lang.addEventListener('change', fetchCounselors);

    // Initialize the state of the select element
    fetchCounselors();
});