async function updateProfile() {
    const fname = document.getElementById("fname").value.trim();
    const lname = document.getElementById("lname").value.trim();
    const email = document.getElementById("email").value.trim();
    const nic = document.getElementById("nic").value.trim();
    const mobile = document.getElementById("mobile").value.trim();
    const password = document.getElementById("password").value.trim();
    const imageInput = document.getElementById("profileImageInput");

    if (!fname || !lname || !email || !nic || !mobile || !password) {
        Swal.fire({ title: "Please fill all required fields.", icon: "warning" });
        return;
    }

    // Prepare function to send data
    async function sendData(imageBase64 = null) {
        const data = {
            fname: fname,
            lname: lname,
            email: email,
            nic: nic,
            mobile: mobile,
            password: password
        };

        if (imageBase64) {
            data.image = imageBase64;
        }

        try {
            const response = await fetch("Backend/Process/UpdateProfileProcess.php", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify(data)
            });

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

            if (json.status) {
                Swal.fire({
                    title: json.message,
                    icon: "success",
                    draggable: true
                }).then(() => {
                    // Reload profile image if updated
                    if (json.newImage) {
                        const img = document.getElementById("profileImagePreview");
                        if (img) {
                            img.src = json.newImage;
                        }
                        // Update navbar profile images immediately after update
                        if (json.newImage) {
                            const desktopProfileImg = document.querySelector("#desktopProfile img");
                            const mobileProfileImg = document.querySelector("#mobileProfile img");
                            if (desktopProfileImg) {
                                desktopProfileImg.onerror = null;
                                // Force replace by directly setting src
                                desktopProfileImg.src = json.newImage;
                            }
                            if (mobileProfileImg) {
                                mobileProfileImg.onerror = null;
                                // Force replace by directly setting src
                                mobileProfileImg.src = json.newImage;
                            }
                        }
                    }
                    // Reload profile data to reflect any changes
                    loadStudentProfile();
                });
            } else {
                Swal.fire({ title: json.message, icon: "warning", draggable: true });
            }

        } catch (err) {
            Swal.fire({ title: "Error: " + err.message, icon: "error", draggable: true });
        }
    }

    // If image is selected → convert to Base64 then send
    if (imageInput.files.length > 0) {
        const reader = new FileReader();
        reader.onload = function () {
            sendData(reader.result);
        };
        reader.readAsDataURL(imageInput.files[0]);
    } else {
        sendData();
    }
}


// StudentProfile.js
async function loadStudentProfile() {
    try {
        const res = await fetch("Backend/Process/GetStudentProfile.php", {
            method: "POST",
            headers: { "Content-Type": "application/json" }
        });

        if (!res.ok) {
            console.error("Server error:", res.status);
            Swal.fire({ 
                title: "Failed to load profile", 
                text: "Server error: " + res.status, 
                icon: "error" 
            });
            return;
        }

        const json = await res.json();
        console.log(json);
        
        if (!json.status) {
            console.warn("Could not load profile:", json.message);
            Swal.fire({ 
                title: "Profile Load Failed", 
                text: json.message || "Could not load profile data", 
                icon: "warning" 
            });
            return;
        }

        const d = json.data || {};

        // Safe helper: set value if element exists
        function setVal(id, value) {
            const el = document.getElementById(id);
            if (!el) {
                console.warn(`Element with id "${id}" not found`);
                return;
            }
            el.value = value ?? "";
        }

        // Map fields (IDs should exist in your modal)
        setVal("fname", d.first_name ?? "");
        setVal("lname", d.last_name ?? "");
        setVal("email", d.email ?? "");
        setVal("nic", d.nic ?? "");
        setVal("mobile", d.mobile ?? "");
        setVal("password", d.password ?? ""); // Set password from database

        // Set profile image preview in modal
        const img = document.getElementById("profileImagePreview");
        if (img) {
            // Handle profile image path
            let imagePath = d.profile_image || "Resources/Images/Profile.jpg";
            img.src = imagePath;
            
            // Handle image load errors - fallback to default image
            img.onerror = function() {
                console.warn("Failed to load profile image:", imagePath);
                this.src = "Resources/Images/Profile.jpg"; // Fallback to default
            };
        } else {
            console.warn("Profile image preview element not found");
        }

        // Update navbar profile images (desktop and mobile)
        const desktopProfileImg = document.querySelector("#desktopProfile img");
        const mobileProfileImg = document.querySelector("#mobileProfile img");
        
        let imagePath = d.profile_image || "Resources/Images/Profile.jpg";
        
        // Always update the image src (this replaces the old image)
        if (desktopProfileImg) {
            desktopProfileImg.onerror = null; // Clear old handler
            // Force replace by setting src directly
            desktopProfileImg.src = imagePath;
            desktopProfileImg.onerror = function() {
                // Only set default if current src is not already default
                if (this.src && !this.src.includes("Resources/Images/Profile.jpg")) {
                    this.src = "Resources/Images/Profile.jpg";
                }
            };
        }
        
        if (mobileProfileImg) {
            mobileProfileImg.onerror = null; // Clear old handler
            // Force replace by setting src directly
            mobileProfileImg.src = imagePath;
            mobileProfileImg.onerror = function() {
                // Only set default if current src is not already default
                if (this.src && !this.src.includes("Resources/Images/Profile.jpg")) {
                    this.src = "Resources/Images/Profile.jpg";
                }
            };
        }

    } catch (err) {
        console.error("Error loading profile:", err);
        Swal.fire({ 
            title: "Error", 
            text: "Failed to load profile: " + err.message, 
            icon: "error" 
        });
    }
}

// small helper to wire preview + choose behaviour
function initProfileImageHandlers() {
    const preview = document.getElementById("profileImagePreview");
    const overlay = document.getElementById("profileOverlayText");
    const chooseBtn = document.getElementById("choosePicBtn");
    const fileInput = document.getElementById("profileImageInput");

    if (!preview || !fileInput) return;

    // Click preview or the choosePic button -> open file chooser
    preview.addEventListener("click", () => fileInput.click());
    if (chooseBtn) chooseBtn.addEventListener("click", () => fileInput.click());

    // Show overlay on hover (if overlay exists)
    if (overlay) {
        preview.addEventListener("mouseenter", () => overlay.style.opacity = "1");
        preview.addEventListener("mouseleave", () => overlay.style.opacity = "0");
    }

    // When a file is selected, preview it locally
    fileInput.addEventListener("change", (e) => {
        const f = e.target.files[0];
        if (!f) return;
        const reader = new FileReader();
        reader.onload = function (evt) {
            preview.src = evt.target.result;
        };
        reader.readAsDataURL(f);
    });
}

// Load navbar profile images on page load (without loading full profile data)
// Make this function globally available
window.loadNavbarProfileImage = async function() {
    try {
        const res = await fetch("Backend/Process/GetStudentProfile.php", {
            method: "POST",
            headers: { "Content-Type": "application/json" }
        });

        if (res.ok) {
            const json = await res.json();
            if (json.status && json.data && json.data.profile_image) {
                const imagePath = json.data.profile_image || "Resources/Images/Profile.jpg";
                
                // Update navbar profile images - try multiple times if elements not ready
                const updateImages = () => {
                    const desktopProfileImg = document.querySelector("#desktopProfile img");
                    const mobileProfileImg = document.querySelector("#mobileProfile img");
                    
                    // Always update the image (this replaces whatever is there)
                    if (desktopProfileImg) {
                        // Remove old onerror handler to prevent conflicts
                        desktopProfileImg.onerror = null;
                        // Set new image - this will replace the current image
                        desktopProfileImg.src = imagePath;
                        // Only fallback to default if image fails to load
                        desktopProfileImg.onerror = function() {
                            // Prevent infinite loop - only set default if current src is not already default
                            if (this.src && !this.src.includes("Resources/Images/Profile.jpg")) {
                                this.src = "Resources/Images/Profile.jpg";
                            }
                        };
                    }
                    
                    if (mobileProfileImg) {
                        // Remove old onerror handler to prevent conflicts
                        mobileProfileImg.onerror = null;
                        // Set new image - this will replace the current image
                        mobileProfileImg.src = imagePath;
                        // Only fallback to default if image fails to load
                        mobileProfileImg.onerror = function() {
                            // Prevent infinite loop - only set default if current src is not already default
                            if (this.src && !this.src.includes("Resources/Images/Profile.jpg")) {
                                this.src = "Resources/Images/Profile.jpg";
                            }
                        };
                    }
                };

                // Try immediately
                updateImages();
                
                // If elements not found, try again after a short delay
                setTimeout(() => {
                    updateImages();
                }, 100);
            }
        }
    } catch (err) {
        console.warn("Could not load navbar profile image:", err);
    }
};

// Initialize profile image handlers on page load
window.addEventListener("load", () => {
    initProfileImageHandlers();
    // Load navbar profile images on page load
    if (window.loadNavbarProfileImage) {
        window.loadNavbarProfileImage();
    }
});

// Load profile data when modal is shown
document.addEventListener('DOMContentLoaded', () => {
    // Load navbar profile images when DOM is ready
    if (window.loadNavbarProfileImage) {
        window.loadNavbarProfileImage();
    }

    const profileModal = document.getElementById('profileModal');
    if (profileModal) {
        profileModal.addEventListener('show.bs.modal', () => {
            loadStudentProfile();
        });
    }
});
