document.addEventListener('DOMContentLoaded', function () { const registrationForm = document.getElementById('registrationForm'); const patientTableBody = document.getElementById('patientTableBody'); const toastContainer = document.getElementById('toastContainer'); // --- Function to show a toast notification --- function showToast(message, type = 'success') { const toastId = 'toast-' + Date.now(); const toastHTML = ` `; toastContainer.innerHTML += toastHTML; const toastElement = document.getElementById(toastId); const toast = new bootstrap.Toast(toastElement, { delay: 5000 }); toast.show(); toastElement.addEventListener('hidden.bs.toast', () => toastElement.remove()); } // --- Function to add a patient to the table --- function addPatientToTable(patient) { const row = document.createElement('tr'); row.innerHTML = ` ${patient.id} ${patient.first_name} ${patient.last_name} ${patient.date_of_birth} ${patient.gender} ${patient.contact_number} ${patient.registration_date || new Date().toISOString().split('T')[0]} `; patientTableBody.prepend(row); } // --- Fetch and display initial patients --- async function loadInitialPatients() { try { const response = await fetch('api/patients.php'); if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`); const data = await response.json(); if (data.status === 'success' && data.patients) { patientTableBody.innerHTML = ''; // Clear existing rows data.patients.forEach(addPatientToTable); } else { showToast(data.message || 'Could not load patients.', 'danger'); } } catch (error) { console.error('Fetch error:', error); showToast('An error occurred while fetching patient data.', 'danger'); } } // --- Handle form submission --- if (registrationForm) { registrationForm.addEventListener('submit', async function (e) { e.preventDefault(); const formData = new FormData(registrationForm); const patientData = Object.fromEntries(formData.entries()); try { const response = await fetch('api/patients.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(patientData) }); if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`); const result = await response.json(); if (result.status === 'success') { showToast('Patient registered successfully!'); addPatientToTable(result.patient); registrationForm.reset(); const modal = bootstrap.Modal.getInstance(document.getElementById('registerPatientModal')); modal.hide(); } else { showToast(result.message || 'Registration failed.', 'danger'); } } catch (error) { console.error('Submit error:', error); showToast('An error occurred during registration.', 'danger'); } }); } // --- Initial load --- loadInitialPatients(); });