New Member Registration - Ashrey Fitness Simpson
function validateForm() {
const requiredFields = document.querySelectorAll('input[required], select[required], textarea[required]');
let isValid = true;
let firstInvalidField = null;
requiredFields.forEach(field => {
if (!field.value.trim()) {
field.style.borderColor = '#E10F84';
field.style.borderWidth = '2px';
if (!firstInvalidField) {
firstInvalidField = field;
}
isValid = false;
} else {
field.style.borderColor = 'rgba(0, 0, 0, 0.1)';
field.style.borderWidth = '1px';
}
});
// Check duration selection
const durationSelected = document.querySelector('input[name="duration"]:checked');
if (!durationSelected) {
alert('Please select a membership duration');
isValid = false;
}
// Check terms and conditions
const termsChecked = document.getElementById('terms')?.checked;
const waiverChecked = document.getElementById('waiver')?.checked;
if (!termsChecked || !waiverChecked) {
alert('Please accept the terms and conditions and waiver');
isValid = false;
}
// Focus on first invalid field
if (firstInvalidField) {
firstInvalidField.focus();
firstInvalidField.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
return isValid;
}
function collectFormData() {
const duration = document.querySelector('input[name="duration"]:checked')?.value;
return {
firstName: document.getElementById('firstName')?.value.trim() || '',
lastName: document.getElementById('lastName')?.value.trim() || '',
email: document.getElementById('email')?.value.trim() || '',
phone: document.getElementById('phone')?.value.trim() || '',
dateOfBirth: document.getElementById('dateOfBirth')?.value || '',
gender: document.getElementById('gender')?.value || '',
address: document.getElementById('address')?.value.trim() || '',
duration: duration || '',
height: document.getElementById('height')?.value || '',
weight: document.getElementById('weight')?.value || '',
fitnessGoals: document.getElementById('fitnessGoals')?.value || '',
fitnessLevel: document.getElementById('fitnessLevel')?.value || '',
medicalConditions: document.getElementById('medicalConditions')?.value.trim() || '',
emergencyName: document.getElementById('emergencyName')?.value.trim() || '',
emergencyRelationship: document.getElementById('emergencyRelationship')?.value.trim() || '',
emergencyPhone: document.getElementById('emergencyPhone')?.value.trim() || '',
marketing: document.getElementById('marketing')?.checked || false
};
}
function calculateAmount(duration) {
// Simpson branch pricing - ₦30,000 for both 3 and 6 months
const amounts = {
'1': 30000 * 100, // 1 month - ₦30,000
'6': 25000 * 100 // 6 months - ₦150,000
};
return amounts[duration] || 30000 * 100;
}
function initializePayment(formData, amount) {
console.log('🔄 Initializing payment...');
console.log('💰 Amount:', amount / 100, 'NGN');
try {
const handler = PaystackPop.setup({
key: PAYSTACK_PUBLIC_KEY,
email: formData.email,
amount: amount,
currency: 'NGN',
ref: 'ASHREY_SIMPSON_' + Date.now() + '_' + Math.floor(Math.random() * 10000),
metadata: {
custom_fields: [
{
display_name: "Full Name",
variable_name: "full_name",
value: `${formData.firstName} ${formData.lastName}`
},
{
display_name: "Phone Number",
variable_name: "phone",
value: formData.phone
},
{
display_name: "Membership Duration",
variable_name: "duration",
value: `${formData.duration} months`
},
{
display_name: "Branch",
variable_name: "branch",
value: "Simpson"
}
]
},
callback: function (response) {
console.log('✅ Payment successful:', response);
formData.payment_reference = response.reference;
formData.branch = "Simpson";
formData.amount_paid = amount / 100;
saveToFirebase(formData)
.then(() => {
console.log('✅ Data saved to Firebase successfully');
sendConfirmationEmail(formData);
})
.catch((error) => {
console.error('❌ Failed to save to Firebase:', error);
sendConfirmationEmail(formData); // Still send email
});
},
onClose: function () {
console.log('❌ Payment was closed');
hideLoading();
alert('Payment was cancelled. Please try again.');
}
});
handler.openIframe();
} catch (error) {
console.error('❌ Payment initialization failed:', error);
hideLoading();
alert('Failed to initialize payment. Please try again.');
}
}
// Firebase save function
function saveToFirebase(data) {
console.log('🔄 Saving to Firebase...');
console.log('📊 Data to save:', data);
const userId = data.email.replace(/[.#$\[\]]/g, "_");
const database = firebase.database();
return database.ref('members/' + userId).set({
...data,
timestamp: new Date().toISOString(),
registrationDate: new Date().toLocaleDateString(),
status: 'active'
});
}
function sendConfirmationEmail(formData) {
if (typeof emailjs === 'undefined') {
console.error('❌ EmailJS not loaded');
hideLoading();
showSuccessMessage();
alert('Registration successful! However, confirmation email could not be sent. Please contact support for your receipt.');
return;
}
console.log('📧 Sending confirmation email...');
// Initialize EmailJS if not already done
if (!emailjs.init) {
emailjs.init("TuXYLuoyodwhUznQC"); // Replace with your actual public key
}
emailjs.send("service_21dunzv", "template_h2dogqp", {
full_name: `${formData.firstName} ${formData.lastName}`,
email: formData.email,
phone: formData.phone,
branch: formData.branch || "Simpson",
duration: `${formData.duration} months`,
amount: formData.amount_paid || 'N/A',
payment_reference: formData.payment_reference || 'N/A',
registration_date: new Date().toLocaleDateString()
})
.then(function (emailResponse) {
console.log("✅ Email sent successfully", emailResponse);
hideLoading();
showSuccessMessage();
alert('Registration successful! Welcome to Ashrey Fitness Center. Check your email for confirmation.');
})
.catch(function (error) {
console.error("❌ Failed to send email", error);
hideLoading();
showSuccessMessage();
alert('Registration successful! However, email confirmation failed. Please contact support for your receipt.');
});
}
function showLoading() {
const form = document.getElementById('registrationForm');
const loading = document.getElementById('loadingDiv');
if (form) form.style.display = 'none';
if (loading) loading.classList.add('show');
}
function hideLoading() {
const loading = document.getElementById('loadingDiv');
if (loading) loading.classList.remove('show');
}
function showSuccessMessage() {
const form = document.getElementById('registrationForm');
const success = document.getElementById('successMessage');
if (form) form.style.display = 'none';
if (success) success.classList.add('show');
}
// Event listeners for duration options
document.querySelectorAll('.duration-option').forEach(option => {
option.addEventListener('click', function () {
document.querySelectorAll('.duration-option').forEach(opt => opt.classList.remove('selected'));
this.classList.add('selected');
const radio = this.querySelector('input[type="radio"]');
if (radio) radio.checked = true;
});
});
// Enhanced placeholder handling for WordPress compatibility
document.addEventListener('DOMContentLoaded', function() {
const inputs = document.querySelectorAll('input[type="text"], input[type="email"], input[type="tel"], input[type="number"], textarea');
inputs.forEach(input => {
const placeholder = input.getAttribute('placeholder');
if (input.value === placeholder) {
input.value = '';
}
input.setAttribute('placeholder', placeholder);
input.style.setProperty('color', '#333', 'important');
input.addEventListener('focus', function() {
if (this.value === placeholder) {
this.value = '';
}
this.style.setProperty('color', '#333', 'important');
});
input.addEventListener('blur', function() {
if (this.value === '') {
this.setAttribute('placeholder', placeholder);
}
});
});
});
// Phone number formatting
const phoneField = document.getElementById('phone');
if (phoneField) {
phoneField.addEventListener('input', function (e) {
let value = e.target.value.replace(/\D/g, '');
if (value.length > 0) {
if (value.startsWith('234')) {
value = '+' + value;
} else if (value.startsWith('0')) {
value = '+234' + value.substring(1);
} else if (!value.startsWith('234') && value.length >= 10) {
value = '+234' + value;
}
}
e.target.value = value;
});
}
// Auto-calculate age from date of birth
document.getElementById('dateOfBirth').addEventListener('change', function() {
const birthDate = new Date(this.value);
const today = new Date();
const age = today.getFullYear() - birthDate.getFullYear();
console.log('Age calculated:', age);
});
// Field validation on blur
document.querySelectorAll('input[required], select[required], textarea[required]').forEach(element => {
element.addEventListener('blur', function () {
if (!this.value.trim()) {
this.style.borderColor = '#E10F84';
this.style.borderWidth = '2px';
} else {
this.style.borderColor = 'rgba(0, 0, 0, 0.1)';
this.style.borderWidth = '1px';
}
});
});
console.log('✅ Registration form script loaded successfully');
});