<script>
// Fungsi untuk membersihkan error
function clearErrors(modalId) {
    const modal = document.getElementById(modalId);
    modal.querySelectorAll('.is-invalid').forEach(el => el.classList.remove('is-invalid'));
    modal.querySelectorAll('.invalid-feedback').forEach(el => el.textContent = '');
    
    if (modalId === 'editSiswaModal') {
        const errorAlert = document.getElementById('editErrorAlert');
        if (errorAlert) {
            errorAlert.classList.add('d-none');
            document.getElementById('editErrorList').innerHTML = '';
        }
    }
}

// Auto-open add modal jika ada validation errors
document.addEventListener('DOMContentLoaded', function() {
    <?php if($errors->any()): ?>
        new bootstrap.Modal(document.getElementById('addSiswaModal')).show();
    <?php endif; ?>
});

// Clear form saat modal ditutup
document.getElementById('addSiswaModal').addEventListener('hidden.bs.modal', function() {
    document.getElementById('addSiswaForm').reset();
    clearErrors('addSiswaModal');
});

document.getElementById('editSiswaModal').addEventListener('hidden.bs.modal', function() {
    clearErrors('editSiswaModal');
});

function editSiswa(id) {
    clearErrors('editSiswaModal');
    
    fetch(`/admin/siswa-magang/${id}/edit`)
        .then(response => {
            if (!response.ok) throw new Error('Network response was not ok');
            return response.json();
        })
        .then(data => {
            // Populate form fields
            Object.keys(data).forEach(key => {
                const element = document.getElementById(`edit${key.charAt(0).toUpperCase() + key.slice(1).replace(/_(.)/g, (_, c) => c.toUpperCase())}`);
                if (element) element.value = data[key] || '';
            });
            
            document.getElementById('editSiswaForm').action = `/admin/siswa-magang/${id}/update`;
            new bootstrap.Modal(document.getElementById('editSiswaModal')).show();
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Terjadi kesalahan saat mengambil data siswa: ' + error.message);
        });
}

// Handle edit form submission
document.getElementById('editSiswaForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const form = this;
    const formData = new FormData(form);
    const submitBtn = form.querySelector('button[type="submit"]');
    const originalText = submitBtn.innerHTML;
    
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Updating...';
    
    clearErrors('editSiswaModal');
    
    fetch(form.action, {
        method: 'POST',
        body: formData,
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            bootstrap.Modal.getInstance(document.getElementById('editSiswaModal')).hide();
            location.reload();
        } else {
            if (data.errors) {
                displayErrors(data.errors);
            } else {
                showAlert([data.message || 'Terjadi kesalahan']);
            }
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showAlert(['Terjadi kesalahan saat memperbarui data']);
    })
    .finally(() => {
        submitBtn.disabled = false;
        submitBtn.innerHTML = originalText;
    });
});

function displayErrors(errors) {
    const errorList = [];
    
    Object.keys(errors).forEach(field => {
        const input = document.querySelector(`#editSiswaModal [name="${field}"]`);
        const feedback = input?.nextElementSibling;
        
        if (input) {
            input.classList.add('is-invalid');
            if (feedback?.classList.contains('invalid-feedback')) {
                feedback.textContent = errors[field][0];
            }
        }
        
        errors[field].forEach(message => errorList.push(message));
    });
    
    showAlert(errorList);
}

function showAlert(messages) {
    const errorAlert = document.getElementById('editErrorAlert');
    const errorList = document.getElementById('editErrorList');
    
    if (errorAlert && errorList) {
        errorList.innerHTML = messages.map(msg => `<li>${msg}</li>`).join('');
        errorAlert.classList.remove('d-none');
    }
}

function confirmDelete(id, name) {
    document.getElementById('deleteName').textContent = name;
    document.getElementById('deleteForm').action = `/admin/siswa-magang/${id}/delete`;
    new bootstrap.Modal(document.getElementById('deleteModal')).show();
}
</script><?php /**PATH C:\laragon\www\presensi-magang\resources\views/admin/siswa/script.blade.php ENDPATH**/ ?>