// AgriCensus Pro - Main JavaScript // Global State const state = { currentUser: null, currentSurvey: null, currentStep: 1, totalSteps: 5, surveys: [], enumerators: [], households: [], loginType: 'enumerator' }; // Initialize document.addEventListener('DOMContentLoaded', () => { initializeTheme(); loadSampleData(); updateUI(); feather.replace(); }); // Theme Management function initializeTheme() { const savedTheme = localStorage.getItem('theme') || 'light'; if (savedTheme === 'dark') { document.documentElement.classList.add('dark'); } document.getElementById('themeToggle').addEventListener('click', toggleTheme); } function toggleTheme() { const isDark = document.documentElement.classList.toggle('dark'); localStorage.setItem('theme', isDark ? 'dark' : 'light'); feather.replace(); } // Sample Data for Demo function loadSampleData() { // Sample enumerators state.enumerators = [ { id: 'ENUM001', name: 'Ram Bahadur', email: 'ram@example.com', college: 'Agriculture University', status: 'active', collegeIdVerified: true }, { id: 'ENUM002', name: 'Sita Devi', email: 'sita@example.com', college: 'Tribhuvan University', status: 'pending', collegeIdVerified: false }, { id: 'ENUM003', name: 'Hari Prasad', email: 'hari@example.com', college: 'Himalayan College', status: 'active', collegeIdVerified: true } ]; // Sample surveys state.surveys = [ { id: 'SURV001', title: 'Kathmandu Valley Baseline Survey', location: 'Kathmandu District, Ward 5', status: 'draft', progress: 60, lastModified: '2024-01-15', enumeratorId: 'ENUM001', data: {} }, { id: 'SURV002', title: 'Pokhara Agricultural Census', location: 'Kaski District, Ward 3', status: 'submitted', progress: 100, lastModified: '2024-01-10', enumeratorId: 'ENUM001', data: {} }, { id: 'SURV003', title: 'Terai Region Survey', location: 'Dhanusha District, Ward 7', status: 'draft', progress: 25, lastModified: '2024-01-14', enumeratorId: 'ENUM002', data: {} } ]; } // UI Updates function updateUI() { const authButtons = document.getElementById('authButtons'); const userMenu = document.getElementById('userMenu'); const heroSection = document.getElementById('heroSection'); const dashboardSection = document.getElementById('dashboardSection'); const adminSection = document.getElementById('adminSection'); if (state.currentUser) { authButtons.classList.add('hidden'); userMenu.classList.remove('hidden'); document.getElementById('userName').textContent = state.currentUser.name; heroSection.classList.add('hidden'); if (state.currentUser.role === 'admin') { adminSection.classList.remove('hidden'); dashboardSection.classList.add('hidden'); renderAdminPanel(); } else { dashboardSection.classList.remove('hidden'); adminSection.classList.add('hidden'); renderDashboard(); } } else { authButtons.classList.remove('hidden'); userMenu.classList.add('hidden'); heroSection.classList.remove('hidden'); dashboardSection.classList.add('hidden'); adminSection.classList.add('hidden'); } } // Login System function showLoginModal() { document.getElementById('loginModal').classList.remove('hidden'); document.getElementById('loginModal').classList.add('modal-enter'); } function closeLoginModal() { document.getElementById('loginModal').classList.add('hidden'); } function switchLoginType(type) { state.loginType = type; const enumBtn = document.getElementById('enumLoginBtn'); const adminBtn = document.getElementById('adminLoginBtn'); if (type === 'enumerator') { enumBtn.classList.add('bg-primary-500', 'text-white'); enumBtn.classList.remove('bg-gray-200', 'dark:bg-gray-700', 'text-gray-700', 'dark:text-gray-300'); adminBtn.classList.remove('bg-primary-500', 'text-white'); adminBtn.classList.add('bg-gray-200', 'dark:bg-gray-700', 'text-gray-700', 'dark:text-gray-300'); } else { adminBtn.classList.add('bg-primary-500', 'text-white'); adminBtn.classList.remove('bg-gray-200', 'dark:bg-gray-700', 'text-gray-700', 'dark:text-gray-300'); enumBtn.classList.remove('bg-primary-500', 'text-white'); enumBtn.classList.add('bg-gray-200', 'dark:bg-gray-700', 'text-gray-700', 'dark:text-gray-300'); } } function handleLogin(e) { e.preventDefault(); const email = document.getElementById('loginEmail').value; const password = document.getElementById('loginPassword').value; // Demo authentication if (state.loginType === 'admin' && email === 'admin' && password === 'admin') { state.currentUser = { id: 'ADMIN001', name: 'System Administrator', role: 'admin', email: 'admin@agricensus.pro' }; showToast('Welcome, Administrator!'); closeLoginModal(); updateUI(); } else if (state.loginType === 'enumerator') { const enumerator = state.enumerators.find(e => e.email === email && password === 'password'); if (enumerator && enumerator.status === 'active') { state.currentUser = { ...enumerator, role: 'enumerator' }; showToast(`Welcome, ${enumerator.name}!`); closeLoginModal(); updateUI(); } else if (enumerator && enumerator.status === 'pending') { showToast('Your account is pending verification. Please wait for admin approval.'); } else { showToast('Invalid credentials. Try email: ram@example.com, password: password'); } } } function logout() { state.currentUser = null; state.currentSurvey = null; updateUI(); showToast('Logged out successfully'); } // Enumerator Registration function showEnumeratorRegister() { document.getElementById('registerModal').classList.remove('hidden'); } function closeRegisterModal() { document.getElementById('registerModal').classList.add('hidden'); } function previewIdCard(input) { const preview = document.getElementById('idCardPreview'); if (input.files && input.files[0]) { const reader = new FileReader(); reader.onload = function(e) { preview.src = e.target.result; preview.classList.remove('hidden'); }; reader.readAsDataURL(input.files[0]); } } function handleRegister(e) { e.preventDefault(); const formData = new FormData(e.target); // Validate college ID photo const idPhoto = document.getElementById('idCardPhoto').files[0]; if (!idPhoto) { showToast('Please upload your College ID Card photo'); return; } // Create new enumerator const newEnumerator = { id: 'ENUM' + String(state.enumerators.length + 1).padStart(3, '0'), name: formData.get('fullName'), email: formData.get('email'), phone: formData.get('phone'), college: formData.get('college'), collegeId: formData.get('collegeId'), status: 'pending', collegeIdVerified: false }; state.enumerators.push(newEnumerator); showToast('Registration submitted successfully! Your account is pending verification.'); closeRegisterModal(); e.target.reset(); document.getElementById('idCardPreview').classList.add('hidden'); } // Survey Management function renderDashboard() { const grid = document.getElementById('surveyGrid'); const mySurveys = state.surveys.filter(s => s.enumeratorId === state.currentUser.id); grid.innerHTML = mySurveys.map(survey => `
${survey.status.toUpperCase()} ${survey.lastModified}

${survey.title}

${survey.location}

Progress ${survey.progress}%
${survey.status === 'draft' ? ` ` : ''}
`).join(''); feather.replace(); } function getStatusClass(status) { const classes = { draft: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200', submitted: 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200', verified: 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200', rejected: 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200' }; return classes[status] || classes.draft; } function createNewSurvey() { state.currentSurvey = { id: 'SURV' + Date.now(), title: 'New Survey ' + new Date().toLocaleDateString(), status: 'draft', progress: 0, data: {}, createdAt: new Date().toISOString() }; state.currentStep = 1; state.households = []; openSurveyModal(); updateStepIndicators(); } function openSurvey(id) { const survey = state.surveys.find(s => s.id === id); if (survey) { state.currentSurvey = {...survey}; state.currentStep = 1; state.households = survey.data.households || []; openSurveyModal(); populateSurveyData(); updateStepIndicators(); } } function openSurveyModal() { document.getElementById('surveyModal').classList.remove('hidden'); document.body.style.overflow = 'hidden'; feather.replace(); } function closeSurveyModal() { document.getElementById('surveyModal').classList.add('hidden'); document.body.style.overflow = ''; state.currentSurvey = null; state.currentStep = 1; } function populateSurveyData() { if (!state.currentSurvey || !state.currentSurvey.data) return; const data = state.currentSurvey.data; const form = document.getElementById('surveyForm'); // Populate form fields Object.keys(data).forEach(key => { const field = form.querySelector(`[name="${key}"]`); if (field) { field.value = data[key]; } }); // Restore households if (data.households && data.households.length > 0) { state.households = data.households; renderHouseholds(); } } // Step Navigation function nextStep() { if (validateCurrentStep()) { saveCurrentStepData(); if (state.currentStep < state.totalSteps) { state.currentStep++; showStep(state.currentStep); updateStepIndicators(); } } } function prevStep() { if (state.currentStep > 1) { saveCurrentStepData(); state.currentStep--; showStep(state.currentStep); updateStepIndicators(); } } function showStep(step) { // Hide all steps document.querySelectorAll('.survey-step').forEach(el => el.classList.add('hidden')); // Show current step document.getElementById(`step${step}`).classList.remove('hidden'); // Update buttons const prevBtn = document.getElementById('prevBtn'); const nextBtn = document.getElementById('nextBtn'); const submitBtn = document.getElementById('submitBtn'); if (step === 1) { prevBtn.classList.add('hidden'); } else { prevBtn.classList.remove('hidden'); } if (step === state.totalSteps) { nextBtn.classList.add('hidden'); submitBtn.classList.remove('hidden'); } else { nextBtn.classList.remove('hidden'); submitBtn.classList.add('hidden'); } // Render households if on step 5 if (step === 5) { renderHouseholds(); } feather.replace(); } function updateStepIndicators() { for (let i = 1; i <= state.totalSteps; i++) { const indicator = document.getElementById(`step${i}Indicator`); const progress = document.getElementById(`progress${i}`); if (i < state.currentStep) { // Completed indicator.className = 'w-8 h-8 rounded-full bg-green-500 text-white flex items-center justify-center'; indicator.innerHTML = ''; if (progress) progress.style.width = '100%'; } else if (i === state.currentStep) { // Current indicator.className = 'w-8 h-8 rounded-full bg-primary-500 text-white flex items-center justify-center'; indicator.innerHTML = i; if (progress) progress.style.width = '50%'; } else { // Not started indicator.className = 'w-8 h-8 rounded-full bg-gray-200 dark:bg-gray-700 text-gray-600 dark:text-gray-400 flex items-center justify-center'; indicator.innerHTML = i; if (progress) progress.style.width = '0%'; } } feather.replace(); } function validateCurrentStep() { const currentStepEl = document.getElementById(`step${state.currentStep}`); const requiredFields = currentStepEl.querySelectorAll('[required]'); let valid = true; requiredFields.forEach(field => { if (!field.value.trim()) { field.classList.add('ring-2', 'ring-red-500'); valid = false; setTimeout(() => field.classList.remove('ring-2', 'ring-red-500'), 3000); } }); if (!valid) { showToast('Please fill all required fields'); } return valid; } function saveCurrentStepData() { if (!state.currentSurvey) return; const form = document.getElementById('surveyForm'); const formData = new FormData(form); const data = {}; // Get all form fields form.querySelectorAll('input, select, textarea').forEach(field => { if (field.name) { if (field.type === 'checkbox') { data[field.name] = field.checked; } else if (field.type === 'radio') { if (field.checked) { data[field.name] = field.value; } } else { data[field.name] = field.value; } } }); // Add households data data.households = state.households; state.currentSurvey.data = data; // Update progress state.currentSurvey.progress = Math.round((state.currentStep / state.totalSteps) * 100); } function saveDraft() { saveCurrentStepData(); if (state.currentSurvey) { const existingIndex = state.surveys.findIndex(s => s.id === state.currentSurvey.id); if (existingIndex >= 0) { state.surveys[existingIndex] = {...state.currentSurvey, lastModified: new Date().toISOString().split('T')[0]}; } else { state.surveys.push({...state.currentSurvey, lastModified: new Date().toISOString().split('T')[0]}); } showToast('Draft saved successfully'); renderDashboard(); } } // Household Management function addHousehold() { const household = { id: 'HH' + Date.now(), number: state.households.length + 1, name: '', data: {} }; state.households.push(household); renderHouseholds(); } function removeHousehold(id) { state.households = state.households.filter(h => h.id !== id); // Renumber state.households.forEach((h, i) => h.number = i + 1); renderHouseholds(); } function renderHouseholds() { const container = document.getElementById('householdsContainer'); if (!container) return; if (state.households.length === 0) { container.innerHTML = `

No households added yet. Click "Add New Household" to start.

`; } else { container.innerHTML = state.households.map((hh, index) => `
${hh.number} Household #${hh.number}
`).join(''); } feather.replace(); } // Final Submission function showFinalSubmitModal() { saveCurrentStepData(); const summary = document.getElementById('submissionSummary'); const data = state.currentSurvey?.data || {}; summary.innerHTML = `
Survey ID:${state.currentSurvey?.id || 'N/A'}
Community:${data.villageName || 'N/A'}
Ward:${data.wardCode || 'N/A'}
Total Households:${data.totalHouseholds || 'N/A'}
Households Entered:${state.households.length}
Completion:${state.currentSurvey?.progress || 0}%
`; document.getElementById('finalSubmitModal').classList.remove('hidden'); } function closeFinalSubmitModal() { document.getElementById('finalSubmitModal').classList.add('hidden'); } function finalSubmit() { // Check all terms are accepted const terms1 = document.getElementById('finalTerms1').checked; const terms2 = document.getElementById('finalTerms2').checked; const terms3 = document.getElementById('finalTerms3').checked; if (!terms1 || !terms2 || !terms3) { showToast('Please accept all terms to proceed'); return; } // Submit the survey if (state.currentSurvey) { state.currentSurvey.status = 'submitted'; state.currentSurvey.progress = 100; state.currentSurvey.lastModified = new Date().toISOString().split('T')[0]; const existingIndex = state.surveys.findIndex(s => s.id === state.currentSurvey.id); if (existingIndex >= 0) { state.surveys[existingIndex] = state.currentSurvey; } else { state.surveys.push(state.currentSurvey); } closeFinalSubmitModal(); closeSurveyModal(); showToast('Survey submitted successfully! Awaiting admin verification.'); renderDashboard(); } } // Admin Functions function renderAdminPanel() { renderEnumeratorsList(); renderPendingSurveys(); renderAdminStats(); } function renderEnumeratorsList() { const container = document.getElementById('enumeratorsList'); if (!container) return; container.innerHTML = state.enumerators.map(enumerator => `

${enumerator.name}

${enumerator.college}

${enumerator.status} ${enumerator.status === 'pending' ? ` ` : ''}
`).join(''); feather.replace(); } function renderPendingSurveys() { const container = document.getElementById('pendingSurveysList'); if (!container) return; const pendingSurveys = state.surveys.filter(s => s.status === 'submitted'); if (pendingSurveys.length === 0) { container.innerHTML = `

No pending surveys

`; } else { container.innerHTML = pendingSurveys.map(survey => `

${survey.title}

Submitted

${survey.location}

`).join(''); } feather.replace(); } function renderAdminStats() { const container = document.getElementById('adminStats'); if (!container) return; const stats = { totalEnumerators: state.enumerators.length, activeEnumerators: state.enumerators.filter(e => e.status === 'active').length, pendingEnumerators: state.enumerators.filter(e => e.status === 'pending').length, totalSurveys: state.surveys.length, draftSurveys: state.surveys.filter(s => s.status === 'draft').length, submittedSurveys: state.surveys.filter(s => s.status === 'submitted').length, verifiedSurveys: state.surveys.filter(s => s.status === 'verified').length }; container.innerHTML = `
${stats.totalEnumerators}
Total Enumerators
${stats.activeEnumerators}
Active
${stats.totalSurveys}
Total Surveys
${stats.submittedSurveys}
Pending Review

Survey Status Distribution

Draft
${stats.draftSurveys}
Submitted
${stats.submittedSurveys}
Verified
${stats.verifiedSurveys}
`; } function approveEnumerator(id) { const enumerator = state.enumerators.find(e => e.id === id); if (enumerator) { enumerator.status = 'active'; enumerator.collegeIdVerified = true; showToast(`Enumerator ${enumerator.name} approved`); renderEnumeratorsList(); renderAdminStats(); } } function verifySurvey(id, status) { const survey = state.surveys.find(s => s.id === id); if (survey) { survey.status = status; showToast(`Survey ${status === 'verified' ? 'verified' : 'rejected'}`); renderPendingSurveys(); renderAdminStats(); } } function deleteSurvey(id) { if (confirm('Are you sure you want to delete this survey?')) { state.surveys = state.surveys.filter(s => s.id !== id); showToast('Survey deleted'); renderDashboard(); } } // Toast Notification function showToast(message) { const toast = document.getElementById('toast'); const toastMessage = document.getElementById('toastMessage'); toastMessage.textContent = message; toast.classList.remove('translate-y-20', 'opacity-0'); setTimeout(() => { toast.classList.add('translate-y-20', 'opacity-0'); }, 3000); } // Close modals on backdrop click document.addEventListener('click', (e) => { if (e.target.id === 'loginModal') { closeLoginModal(); } if (e.target.id === 'registerModal') { closeRegisterModal(); } if (e.target.id === 'surveyModal') { closeSurveyModal(); } if (e.target.id === 'finalSubmitModal') { closeFinalSubmitModal(); } });