// Main application script document.addEventListener('DOMContentLoaded', function() { // Student form submission const studentForm = document.getElementById('studentForm'); if (studentForm) { studentForm.addEventListener('submit', function(e) { e.preventDefault(); // Get form values const formData = { fullName: document.getElementById('fullName').value, address: document.getElementById('address').value, telephone: document.getElementById('telephone').value, school: document.getElementById('school').value, grade: document.getElementById('grade').value, ethnicity: document.getElementById('ethnicity').value }; // In a real app, you would send this to your backend console.log('Form submitted:', formData); // Show success message alert('Student information submitted successfully!'); // Reset form studentForm.reset(); }); } // Student management functionality const studentTableBody = document.getElementById('studentTableBody'); const addStudentBtn = document.getElementById('addStudentBtn'); // Student data array (initially empty) let students = []; // Function to process uploaded data function processUploadedData(processedStudents) { students = [...students, ...processedStudents]; renderStudentTable(); saveStudents(); alert(`Successfully imported ${processedStudents.length} students`); } // Render student table function renderStudentTable() { if (!studentTableBody) return; studentTableBody.innerHTML = ''; students.forEach(student => { const row = document.createElement('tr'); row.innerHTML = ` ${student.fullName} ${student.school} ${student.grade} `; studentTableBody.appendChild(row); }); // Make name, school and grade cells editable row.querySelectorAll('[data-field]').forEach(cell => { cell.addEventListener('dblclick', () => { const studentId = parseInt(cell.dataset.id); const field = cell.dataset.field; const student = students.find(s => s.id === studentId); if (student) { const input = document.createElement('input'); input.type = 'text'; input.value = cell.textContent.trim(); input.className = 'w-full border rounded px-2 py-1'; cell.innerHTML = ''; cell.appendChild(input); input.focus(); const saveEdit = () => { student[field] = input.value; cell.textContent = input.value; saveStudents(); }; input.addEventListener('blur', saveEdit); input.addEventListener('keypress', (e) => { if (e.key === 'Enter') saveEdit(); }); } }); }); // Add event listeners to edit buttons (full modal edit) row.querySelector('.edit-student-btn').addEventListener('click', () => { const studentId = parseInt(row.querySelector('.edit-student-btn').dataset.id); const student = students.find(s => s.id === studentId); if (student) { const modal = document.createElement('edit-student-modal'); modal.setStudentData(student); document.body.appendChild(modal); } }); // Add event listeners to delete buttons document.querySelectorAll('.delete-student-btn').forEach(btn => { btn.addEventListener('click', () => { const studentId = parseInt(btn.dataset.id); if (confirm('Are you sure you want to delete this student?')) { students = students.filter(s => s.id !== studentId); renderStudentTable(); saveStudents(); alert('Student deleted successfully'); } }); }); } // Add new student if (addStudentBtn) { addStudentBtn.addEventListener('click', () => { const modal = document.createElement('edit-student-modal'); modal.setStudentData({ id: Date.now(), // temporary ID fullName: '', address: '', telephone: '', school: '', grade: '', ethnicity: '' }); document.body.appendChild(modal); }); } // Handle student updates document.addEventListener('student-updated', (e) => { const updatedStudent = e.detail; const existingIndex = students.findIndex(s => s.id === updatedStudent.id); if (existingIndex >= 0) { // Update existing student students[existingIndex] = updatedStudent; } else { // Add new student students.push(updatedStudent); } renderStudentTable(); saveStudents(); alert('Student saved successfully'); }); // Initial render - try to load from localStorage if (localStorage.getItem('students')) { try { students = JSON.parse(localStorage.getItem('students')); if (students.length === 0) { // If empty, show message about uploading data if (studentTableBody) { studentTableBody.innerHTML = ` No student data found. Please upload a file to get started. `; } } } catch (e) { console.error('Error loading students from localStorage:', e); } } renderStudentTable(); // Save to localStorage whenever students array changes function saveStudents() { localStorage.setItem('students', JSON.stringify(students)); } // Report generation functionality const generateReportBtn = document.getElementById('generateReportBtn'); if (generateReportBtn) { generateReportBtn.addEventListener('click', function() { const reportType = document.getElementById('reportType').value; // In a real app, this would call your backend API console.log('Generating report type:', reportType); alert(`Generating ${reportType} report... (This would call your backend in production)`); }); } // Ensure jsPDF is loaded if (window.jspdf) { window.jsPDF = window.jspdf.jsPDF; } // File upload functionality const uploadForm = document.getElementById('uploadForm'); if (uploadForm) { uploadForm.addEventListener('submit', function(e) { e.preventDefault(); const fileInput = document.getElementById('dataFile'); const fileType = document.getElementById('fileType').value; if (fileInput.files.length === 0) { alert('Please select a file to upload'); return; } const file = fileInput.files[0]; const formData = new FormData(); formData.append('file', file); formData.append('type', fileType); // In a real app, this would be an API call to your backend console.log('Uploading file:', file.name, 'Type:', fileType); // Process the uploaded file const reader = new FileReader(); reader.onload = (e) => { const content = e.target.result; let processedStudents = []; try { if (fileType === 'csv') { // Parse CSV const lines = content.split('\n'); const headers = lines[0].split(','); for (let i = 1; i < lines.length; i++) { if (lines[i].trim() === '') continue; const values = lines[i].split(','); const student = { id: Date.now() + i, fullName: values[0] || '', address: values[1] || '', telephone: values[2] || '', school: values[3] || '', grade: values[4] || '', ethnicity: values[5] || '' }; processedStudents.push(student); } } else if (fileType === 'json') { // Parse JSON const jsonData = JSON.parse(content); processedStudents = jsonData.map((item, i) => ({ id: Date.now() + i, fullName: item.fullName || item.name || '', address: item.address || '', telephone: item.telephone || item.phone || '', school: item.school || '', grade: item.grade || '', ethnicity: item.ethnicity || item.ethnicBackground || '' })); } else if (fileType === 'excel') { try { const data = new Uint8Array(e.target.result); const workbook = XLSX.read(data, { type: 'array' }); const firstSheet = workbook.Sheets[workbook.SheetNames[0]]; const jsonData = XLSX.utils.sheet_to_json(firstSheet); processedStudents = jsonData.map((item, i) => ({ id: Date.now() + i, fullName: item['Full Name'] || item['Name'] || item['Student Name'] || '', address: item.Address || item['Home Address'] || '', telephone: item.Telephone || item.Phone || item['Phone Number'] || '', school: item.School || item['School Name'] || '', grade: item.Grade || item['Grade Level'] || '', ethnicity: item.Ethnicity || item['Ethnic Background'] || '' })); // Process the uploaded data processUploadedData(processedStudents); } catch (error) { alert(`Error processing Excel file: ${error.message}`); console.error('Excel processing error:', error); } return; } // Process the uploaded data processUploadedData(processedStudents); uploadForm.reset(); } catch (error) { alert(`Error processing file: ${error.message}`); console.error('File processing error:', error); } }; if (fileType === 'json') { reader.readAsText(file); } else if (fileType === 'csv') { reader.readAsText(file); } else if (fileType === 'excel') { // Read as array buffer for Excel files reader.readAsArrayBuffer(file); } }); } });