top of page
Screenshot 2023-04-22 at 1.21.25 PM.png
Book an Appointment

Schedule your appointments here

 

Appointment Fixed!

113/2, B. Ramachandra Adithanar Road (4th Main Road), Gandhi Nagar, Adyar, Chennai-600020.

044-24452424, 044-42117424 | +91 9677004999

  • Instagram
  • White Twitter Icon

© 2024 by Tooth Friendly. Creatively designed by The Designing Factory

bottom of page
// Treatment type mapping - matches backend enum values const TREATMENT_TYPES = [ { value: 'Toothfilling', label: 'Tooth Filling' }, { value: 'TeethWhitening', label: 'Teeth Whitening' }, { value: 'TeethCleaning', label: 'Teeth Cleaning' }, { value: 'RootCanalTreatment', label: 'Root Canal Treatment' }, { value: 'ImpactedTeethRemoval', label: 'Impacted Teeth Removal' }, { value: 'ChildDentistry', label: 'Child Dentistry' }, { value: 'Periodontics', label: 'Periodontics' }, { value: 'Dentures', label: 'Dentures' }, { value: 'DentalImplants', label: 'Dental Implants' }, { value: 'CrownsAndBridge', label: 'Crowns And Bridge' }, { value: 'TeethAlignment', label: 'Teeth Alignment' }, { value: 'SedationDentistry', label: 'Sedation Dentistry' }, { value: 'PRF', label: 'PRF' }, { value: 'Consultation', label: 'Consultation' }, { value: 'Braces', label: 'Braces' }, { value: 'MinorOralSurgery', label: 'Minor Oral Surgery' }, { value: 'Invisalign', label: 'Invisalign' } ]; // Time slot options - matches backend enum values const TIME_SLOTS = [ { value: 'Morning', label: 'Morning (9:00 AM - 12:00 PM)' }, { value: 'Evening', label: 'Evening (4:00 PM - 7:00 PM)' } ]; /** * Initialize the form when page loads */ document.addEventListener('DOMContentLoaded', function() { console.log('🦷 Tooth Friendly - Initializing appointment form integration...'); // Populate treatment dropdown populateTreatmentDropdown(); // Populate time slot dropdown populateTimeSlotDropdown(); // Set up form submission handler setupFormSubmission(); // Set minimum date to today for date picker setupDatePicker(); console.log('✅ Tooth Friendly - Form integration initialized successfully'); }); /** * Populate the treatments dropdown with available options */ function populateTreatmentDropdown() { const treatmentSelect = document.getElementById('collection_comp-lh4jjlit'); if (!treatmentSelect) { console.error('❌ Treatment dropdown not found'); return; } // Clear existing options except the first placeholder const placeholder = treatmentSelect.querySelector('option[value=""]'); treatmentSelect.innerHTML = ''; if (placeholder) { treatmentSelect.appendChild(placeholder); } // Add treatment options TREATMENT_TYPES.forEach(treatment => { const option = document.createElement('option'); option.value = treatment.value; option.textContent = treatment.label; option.className = 'R4tv1w U5WS_f'; treatmentSelect.appendChild(option); }); console.log('✅ Treatment dropdown populated with', TREATMENT_TYPES.length, 'options'); } /** * Populate the time slot dropdown with available options */ function populateTimeSlotDropdown() { const timeSlotSelect = document.getElementById('collection_comp-lhtzktvl'); if (!timeSlotSelect) { console.error('❌ Time slot dropdown not found'); return; } // Clear existing options except the first placeholder const placeholder = timeSlotSelect.querySelector('option[value=""]'); timeSlotSelect.innerHTML = ''; if (placeholder) { timeSlotSelect.appendChild(placeholder); } // Add time slot options TIME_SLOTS.forEach(slot => { const option = document.createElement('option'); option.value = slot.value; option.textContent = slot.label; option.className = 'R4tv1w U5WS_f'; timeSlotSelect.appendChild(option); }); console.log('✅ Time slot dropdown populated with', TIME_SLOTS.length, 'options'); } /** * Set up the date picker with minimum date as today */ function setupDatePicker() { const dateInput = document.getElementById('input_comp-lh4jpvs2'); if (dateInput) { const today = new Date().toISOString().split('T')[0]; dateInput.setAttribute('min', today); dateInput.setAttribute('type', 'date'); // Format the display dateInput.addEventListener('change', function() { if (this.value) { const date = new Date(this.value); const formattedDate = date.toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }); console.log('📅 Selected date:', formattedDate); } }); console.log('✅ Date picker configured with minimum date:', today); } } /** * Set up form submission handler */ function setupFormSubmission() { const form = document.getElementById('comp-lh4jflzw'); if (!form) { console.error('❌ Form not found'); return; } // Find and modify the submit button const submitButton = form.querySelector('button[aria-label="Fix Appointment"]'); if (submitButton) { submitButton.addEventListener('click', handleFormSubmission); console.log('✅ Submit button handler attached'); } else { console.error('❌ Submit button not found'); } } /** * Handle form submission */ async function handleFormSubmission(event) { event.preventDefault(); console.log('📤 Form submission started...'); // Show loading state const submitButton = event.target; const originalText = submitButton.querySelector('.wixui-button__label').textContent; submitButton.querySelector('.wixui-button__label').textContent = 'Submitting...'; submitButton.disabled = true; try { // Collect form data const formData = collectFormData(); console.log('📋 Collected form data:', formData); // Validate required fields const validationResult = validateFormData(formData); if (!validationResult.valid) { throw new Error(validationResult.message); } console.log('✅ Validation passed, submitting appointment data:', formData); // Submit to clinic API const response = await submitAppointment(formData); if (response.success) { // Show success message showSuccessMessage(); // Reset form resetForm(); console.log('🎉 Appointment submitted successfully'); } else { throw new Error(response.message || 'Failed to submit appointment'); } } catch (error) { console.error('❌ Form submission error:', error); showErrorMessage(error.message); } finally { // Reset button state submitButton.querySelector('.wixui-button__label').textContent = originalText; submitButton.disabled = false; } } /** * Collect form data from all inputs */ function collectFormData() { const firstName = document.getElementById('input_comp-lh4jfm013').value.trim(); const lastName = document.getElementById('input_comp-lh4jfm042').value.trim(); const email = document.getElementById('input_comp-lh4jfm054').value.trim(); const phone = document.getElementById('input_comp-lh4jotam').value.trim(); const treatment = document.getElementById('collection_comp-lh4jjlit').value; const appointmentDate = document.getElementById('input_comp-lh4jpvs2').value; const timeSlot = document.getElementById('collection_comp-lhtzktvl').value; return { firstname: firstName, lastname: lastName, email: email, phone_number: phone, treatment_type: treatment, date: appointmentDate, time_slot: timeSlot }; } /** * Validate form data - 🔧 FIXED DATE VALIDATION */ function validateFormData(data) { // Check required fields if (!data.firstname) { return { valid: false, message: 'First name is required' }; } if (!data.email) { return { valid: false, message: 'Email is required' }; } if (!data.phone_number) { return { valid: false, message: 'Phone number is required' }; } if (!data.treatment_type) { return { valid: false, message: 'Please select a treatment type' }; } if (!data.date) { return { valid: false, message: 'Please select an appointment date' }; } if (!data.time_slot) { return { valid: false, message: 'Please select a time slot' }; } // Validate email format const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; if (!emailRegex.test(data.email)) { return { valid: false, message: 'Please enter a valid email address' }; } // Validate phone format (basic check) const phoneRegex = /^[+]?[(]?[0-9\s\-()]+$/; if (!phoneRegex.test(data.phone_number)) { return { valid: false, message: 'Please enter a valid phone number' }; } // 🔧 FIXED: Allow today's date (changed < to <=) const selectedDate = new Date(data.date); const today = new Date(); today.setHours(0, 0, 0, 0); selectedDate.setHours(0, 0, 0, 0); // ⚠️ ADDED: Normalize time for comparison if (selectedDate < today) { // This now correctly allows today's date return { valid: false, message: 'Please select today or a future date' }; } console.log('✅ All validation checks passed'); return { valid: true }; } /** * Submit appointment data to clinic API */ async function submitAppointment(formData) { const url = `${CLINIC_API_BASE_URL}${CLINIC_API_ENDPOINT}`; try { console.log('📡 Submitting to URL:', url); console.log('📦 Form data:', formData); const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' }, body: JSON.stringify(formData) }); console.log('📊 Response status:', response.status); if (!response.ok) { const errorData = await response.json().catch(() => ({})); console.error('❌ Error response:', errorData); throw new Error(errorData.message || `HTTP ${response.status}: ${response.statusText}`); } const result = await response.json(); console.log('✅ Success response:', result); return result; } catch (error) { console.error('❌ Network error:', error); if (error.name === 'TypeError' && error.message.includes('fetch')) { throw new Error('Unable to connect to clinic system. Please try again later or call us directly.'); } throw error; } } /** * Show success message to user */ function showSuccessMessage() { const messageElement = document.getElementById('comp-lh4jfm0i3'); if (messageElement) { messageElement.style.display = 'block'; messageElement.style.color = '#28a745'; messageElement.querySelector('p').innerHTML = '✅ Appointment Request Submitted Successfully!
' + 'Our clinic team will contact you soon to confirm your appointment.'; // Scroll to success message messageElement.scrollIntoView({ behavior: 'smooth', block: 'center' }); // Auto-hide after 10 seconds setTimeout(() => { messageElement.style.display = 'none'; }, 10000); } } /** * Show error message to user */ function showErrorMessage(message) { const messageElement = document.getElementById('comp-lh4jfm0i3'); if (messageElement) { messageElement.style.display = 'block'; messageElement.style.color = '#dc3545'; messageElement.querySelector('p').innerHTML = '⚠️ Error: ' + message + '
' + 'Please try again or call us directly at your convenience.'; // Scroll to error message messageElement.scrollIntoView({ behavior: 'smooth', block: 'center' }); // Auto-hide after 8 seconds setTimeout(() => { messageElement.style.display = 'none'; }, 8000); } } /** * Reset form to initial state */ function resetForm() { const form = document.getElementById('comp-lh4jflzw'); if (form) { // Reset all input fields const inputs = form.querySelectorAll('input'); inputs.forEach(input => { input.value = ''; }); // Reset dropdowns const selects = form.querySelectorAll('select'); selects.forEach(select => { select.selectedIndex = 0; }); console.log('✅ Form reset to initial state'); } } // Error handling for missing dependencies window.addEventListener('error', function(event) { if (event.message.includes('fetch')) { console.error('❌ Tooth Friendly Integration: Fetch API not supported. Please use a modern browser.'); } }); // Export for testing (if needed) if (typeof module !== 'undefined' && module.exports) { module.exports = { TREATMENT_TYPES, TIME_SLOTS, collectFormData, validateFormData, submitAppointment }; } console.log('🦷 Tooth Friendly booking form integration loaded (FIXED VERSION)');