<script>
//Final code of home page

document.getElementById('email-form').addEventListener('submit', async function (event) {
    event.preventDefault(); // Prevent default form submission

    const referredBy = localStorage.getItem('Referred By');
    const referralId = localStorage.getItem('Ref-Id'); // Ref-id for Person A's referral

    // Get data from the form
    const name = document.getElementById('name').value;
    const email = document.getElementById('email').value;
    const mobile = document.getElementById('mobile').value;
    const selectedCity = document.querySelector('input[name="city"]:checked') ? document.querySelector('input[name="city"]:checked').value : 'Not selected'; 
    const profession = document.getElementById('profession').value; 
    const income = document.querySelector('input[name="income"]:checked') ? document.querySelector('input[name="income"]:checked').value : 'Not selected'; 
    const household = document.querySelector('input[name="household"]:checked') ? document.querySelector('input[name="household"]:checked').value : 'Not selected'; 
    const why = document.getElementById('why').value; 

    // Split the name into first name and last name
    const nameParts = name.split(' ');
    const firstName = nameParts[0];
    const lastName = nameParts.slice(1).join(' '); // Join the remaining parts as the last name

    // Function to show alert messages
    const showAlertMessage = (message, color = "red") => {
        const alertDiv = document.getElementById("alertdiv");
        const alertMessage = document.getElementById("alertmessage");

        if (!alertDiv || !alertMessage) return;

        alertMessage.innerText = message;
        alertMessage.style.color = color;
        alertDiv.style.display = "flex"; // Show alert
        alertDiv.style.opacity = "1"; // Fade in

        // Hide after 3 seconds
        setTimeout(() => {
            alertDiv.style.opacity = "0"; // Fade out

            // Wait for fade-out before hiding
            setTimeout(() => alertDiv.style.display = "none", 500);
        }, 3000);
    };

    // Function to save user data to the "users" collection
    const saveUserData = () => {
        const userData = {
            firstname: firstName,
            lastname: lastName,
            email: email
        };

        // Save user data under the "users" collection with the UID as the key
        return set(ref(database, `users/${currentUserId}`), userData);
    };

    // Function to handle form submission
    const handleFormSubmission = async () => {
        const formData = {
            name: name,
            email: email,
            mobile: mobile,
            selectedCity: selectedCity,
            profession: profession,
            income: income,
            household: household,
            why: why,
            uid: currentUserId, // Currently logged-in user's UID
            referredBy: referredBy,
        };

        // Generate a timestamp-based key
        const timestampKey = Date.now().toString(); // e.g., "1736176636960"

        // Check if the email already exists in Mainformdata
        const mainFormDataRef = ref(database, 'Mainformdata');

        try {
            const snapshot = await get(mainFormDataRef);
            let existingEntryKey = null;

            // Check if the logged-in user's UID already exists in Mainformdata
            if (snapshot.exists()) {
                snapshot.forEach(childSnapshot => {
                    const childData = childSnapshot.val();
                    if (childData.uid === currentUserId) {
                        existingEntryKey = childSnapshot.key; // Key for the existing entry
                    }
                });
            }

            if (existingEntryKey) {
                // If the UID exists, update the existing entry
                await update(ref(database, `Mainformdata/${existingEntryKey}`), formData);
                showAlertMessage("Form updated successfully!", "green");
            } else {
                // If the UID does not exist, create a new entry with a timestamp key
                await set(ref(database, `Mainformdata/${timestampKey}`), formData);
                showAlertMessage("Form submitted successfully!", "green");
            }

            // Save user data to the "users" collection
            await saveUserData();

            // Additional functionality: Update Person A's referral node
            if (referredBy && referralId) {
                const personASnapshot = await get(mainFormDataRef);
                if (personASnapshot.exists()) {
                    let personAEntryKey = null;

                    // Check each entry for matching referredBy UID and Ref-id
                    personASnapshot.forEach(childSnapshot => {
                        const childData = childSnapshot.val();

                        // Match referredBy UID and Ref-id
                        if (childData.uid === referredBy && childData.referrals && childData.referrals[referralId]) {
                            personAEntryKey = childSnapshot.key; // Key for Person A's entry
                        }
                    });

                    if (personAEntryKey) {
                        // Update Person A's referral node with Person B's details
                        const referralRef = ref(database, `Mainformdata/${personAEntryKey}/referrals/${referralId}`);
                        const referralUpdate = {
                            name: formData.name,
                            email: formData.email,
                            mobile: formData.mobile,
                        };

                        await update(referralRef, referralUpdate);
                    } else {
                        console.log("No matching referral node found for referredBy UID and Ref-id.");
                    }
                }
            }

            // Submit data to Google Sheets
            const data = {
                name: name,
                email: email,
                mobile: mobile,
                selectedCity: selectedCity,
                profession: profession,
                income: income,
                household: household,
                why: why,
                referredBy: referredBy,
                referralId: referralId
            };
/*https://script.google.com/macros/s/AKfycbwY7PiAdCEa7LvMHsrdeJiITn0zZIKF7XeuHI64IhxZnVEoSbE6u1GtVRocnj2xjKcI/exec*/
            await fetch("https://script.google.com/macros/s/AKfycbw-pyZ0wZsxwP9OLsYgfk3S6AX36aKQNBQw11dvypvy-2F7gcrwJ_P7QE2tb6UVMkFHOA/exec", {
                method: "POST",
                body: JSON.stringify(data),
                headers: {
                    "Content-Type": "application/json"
                },
                mode: "no-cors" // Prevents CORS issues
            });

            this.reset(); // Reset the form after submission
               window.location.href = "/thank-you"; // Redirect to the thank you page
        } catch (error) {
            console.error("Error:", error);
            showAlertMessage("An error occurred while saving the form. Please try again.");
        }
    };

    // Function to generate a random password
    const generateRandomPassword = (length = 10) => {
        const charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()";
        let password = "";
        for (let i = 0; i < length; i++) {
            password += charset.charAt(Math.floor(Math.random() * charset.length));
        }
        return password;
    };

    // Function to send email with the generated password
    const sendEmail = async (generatedPassword) => {
        try {
            const response = await fetch("https://api.brevo.com/v3/smtp/email", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "Accept": "application/json",
                    "api-key": "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"
                },
                body: JSON.stringify({
                    sender: { email: "eahto@kypsi.com", name: "Kypsi" },
                    to: [{ email: email, name: name || "User" }],
                    subject: "Welcome! Here’s Your Password",
                    htmlContent: `<p>Hello ${name},</p>
                                  <p>Your account has been created successfully. Below is your login email & password:</p>
                                  <p><strong>Email: ${email}</strong></p>
                                  <p><strong>Password: ${generatedPassword}</strong></p>
                                  <p>Please keep this password safe or reset it after login.</p>
                                  <p>Thank you!</p>`
                })
            });

            const result = await response.json();
            console.log(result);

            if (response.ok) {
           showAlertMessage("Your login details have been sent to your email.","green")
               // alert("Your login details have been sent to your email.");
            } else {
             showAlertMessage("Failed to send email. Please check your API key and settings.","red")
               // alert("Failed to send email. Please check your API key and settings.");
            }
        } catch (error) {
            console.error("Email sending failed:", error);
        }
    };

    // Check if the user is authenticated
    if (!currentUserId) {
        // Generate a random password
        const randomPassword = generateRandomPassword();

        // No user is authenticated, so sign up the user
        try {
            const userCredential = await createUserWithEmailAndPassword(auth, email, randomPassword);
            // User signed up successfully
            currentUserId = userCredential.user.uid;
            console.log("User signed up successfully with UID:", currentUserId);
            console.log("Generated Password for the user:", randomPassword); // Log the generated password
            await sendEmail(randomPassword);
            // Proceed with form submission
            await handleFormSubmission();
        } catch (error) {
            console.error("Error signing up user:", error);
            showAlertMessage(error.message);
        }
    } else {
        // User is already authenticated, proceed with form submission
        await handleFormSubmission();
    }
});
</script>