<script>
document.addEventListener('DOMContentLoaded', function() {
    // Handle role selection for create form
    document.getElementById('createRoleSelect').addEventListener('change', function() {
        const siswaDiv = document.getElementById('createSiswaSelect');
        const pembimbingMagangDiv = document.getElementById('createPembimbingMagangSelect');
        const pembimbingSekolahDiv = document.getElementById('createPembimbingSekolahSelect');
        
        // Hide all dropdowns first
        siswaDiv.style.display = 'none';
        pembimbingMagangDiv.style.display = 'none';
        pembimbingSekolahDiv.style.display = 'none';
        
        // Show relevant dropdown based on role
        if (this.value == '2') { // Siswa magang role
            siswaDiv.style.display = 'block';
        } else if (this.value == '3') { // Pembimbing magang role
            pembimbingMagangDiv.style.display = 'block';
        } else if (this.value == '4') { // Pembimbing sekolah role
            pembimbingSekolahDiv.style.display = 'block';
        }
    });

    // Handle role selection for edit form
    document.getElementById('editRoleSelect').addEventListener('change', function() {
        const siswaDiv = document.getElementById('editSiswaSelect');
        const pembimbingMagangDiv = document.getElementById('editPembimbingMagangSelect');
        const pembimbingSekolahDiv = document.getElementById('editPembimbingSekolahSelect');
        
        // Hide all dropdowns first
        siswaDiv.style.display = 'none';
        pembimbingMagangDiv.style.display = 'none';
        pembimbingSekolahDiv.style.display = 'none';
        
        // Show relevant dropdown based on role
        if (this.value == '2') { // Siswa magang role
            siswaDiv.style.display = 'block';
        } else if (this.value == '3') { // Pembimbing magang role
            pembimbingMagangDiv.style.display = 'block';
        } else if (this.value == '4') { // Pembimbing sekolah role
            pembimbingSekolahDiv.style.display = 'block';
        }
    });

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

function editUser(id) {
    fetch(`/admin/users/${id}/edit`)
        .then(response => response.json())
        .then(data => {
            // Set basic user data
            document.getElementById('editUsername').value = data.username;
            document.getElementById('editRoleSelect').value = data.role_id;

            // Clear and populate siswa select
            const siswaSelect = document.getElementById('editSiswaSelectInput');
            siswaSelect.innerHTML = '<option value="">Pilih Siswa</option>';
            
            if (data.available_siswa && data.available_siswa.length > 0) {
                data.available_siswa.forEach(siswa => {
                    const option = document.createElement('option');
                    option.value = siswa.id;
                    option.textContent = `${siswa.nama_siswa} - ${siswa.sekolah?.nama_sekolah || 'N/A'}`;
                    
                    if (siswa.id == data.id_siswa) {
                        option.selected = true;
                    }
                    
                    siswaSelect.appendChild(option);
                });
            }

            // Clear and populate pembimbing magang select
            const pembimbingMagangSelect = document.getElementById('editPembimbingMagangSelectInput');
            pembimbingMagangSelect.innerHTML = '<option value="">Pilih Pembimbing Magang</option>';
            
            if (data.available_pembimbing_magang && data.available_pembimbing_magang.length > 0) {
                data.available_pembimbing_magang.forEach(pembimbing => {
                    const option = document.createElement('option');
                    option.value = pembimbing.id;
                    option.textContent = `${pembimbing.nama_pembimbing} - ${pembimbing.dudi?.nama_dudi || 'N/A'}`;
                    
                    if (pembimbing.id == data.id_pembimbing_magang) {
                        option.selected = true;
                    }
                    
                    pembimbingMagangSelect.appendChild(option);
                });
            }

            // Clear and populate pembimbing sekolah select
            const pembimbingSekolahSelect = document.getElementById('editPembimbingSekolahSelectInput');
            pembimbingSekolahSelect.innerHTML = '<option value="">Pilih Pembimbing Sekolah</option>';
            
            if (data.available_pembimbing_sekolah && data.available_pembimbing_sekolah.length > 0) {
                data.available_pembimbing_sekolah.forEach(pembimbing => {
                    const option = document.createElement('option');
                    option.value = pembimbing.id;
                    option.textContent = `${pembimbing.nama_pembimbing} (${pembimbing.no_telp || 'N/A'})`;
                    
                    if (pembimbing.id == data.id_pembimbing_sekolah) {
                        option.selected = true;
                    }
                    
                    pembimbingSekolahSelect.appendChild(option);
                });
            }
            
            // Show/hide dropdowns based on role
            const siswaDiv = document.getElementById('editSiswaSelect');
            const pembimbingMagangDiv = document.getElementById('editPembimbingMagangSelect');
            const pembimbingSekolahDiv = document.getElementById('editPembimbingSekolahSelect');
            
            // Hide all first
            siswaDiv.style.display = 'none';
            pembimbingMagangDiv.style.display = 'none';
            pembimbingSekolahDiv.style.display = 'none';
            
            // Reset required attributes
            siswaSelect.required = false;
            pembimbingMagangSelect.required = false;
            pembimbingSekolahSelect.required = false;
            
            if (data.role_id == '2') { // Role siswa magang
                siswaDiv.style.display = 'block';
                siswaSelect.required = true;
            } else if (data.role_id == '3') { // Role pembimbing magang
                pembimbingMagangDiv.style.display = 'block';
                pembimbingMagangSelect.required = true;
            } else if (data.role_id == '4') { // Role pembimbing sekolah
                pembimbingSekolahDiv.style.display = 'block';
                pembimbingSekolahSelect.required = true;
            }
            
            // Set form action
            document.getElementById('editUserForm').action = `/admin/users/${id}/update`;
            
            // Show modal
            new bootstrap.Modal(document.getElementById('editUserModal')).show();
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Terjadi kesalahan saat mengambil data user');
        });
}

function confirmDelete(id, username) {
    document.getElementById('deleteName').textContent = username;
    document.getElementById('deleteForm').action = `/admin/users/${id}/delete`;
    new bootstrap.Modal(document.getElementById('deleteModal')).show();
}

function togglePassword(inputId, button) {
    const passwordInput = document.getElementById(inputId);
    const icon = button.querySelector('i');
    
    if (passwordInput.type === 'password') {
        passwordInput.type = 'text';
        icon.className = 'fas fa-eye-slash';
    } else {
        passwordInput.type = 'password';
        icon.className = 'fas fa-eye';
    }
}
</script>