async function updateAdminProfile() {
    const fname = document.getElementById("adminFname").value.trim();
    const lname = document.getElementById("adminLname").value.trim();
    const email = document.getElementById("adminEmail").value.trim();
    const password = document.getElementById("adminPassword").value.trim();
    const imageInput = document.getElementById("profileImageInput");

    if (!fname || !lname || !email || !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,
            password: password
        };

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

        try {
            const response = await fetch("Backend/Process/UpdateAdminProfileProcess.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
                        const desktopProfileImg = document.querySelector("#desktopProfile img");
                        const mobileProfileImg = document.querySelector("#mobileProfile img");
                        if (desktopProfileImg) {
                            desktopProfileImg.onerror = null;
                            desktopProfileImg.src = json.newImage;
                        }
                        if (mobileProfileImg) {
                            mobileProfileImg.onerror = null;
                            mobileProfileImg.src = json.newImage;
                        }
                    }
                    // Reload profile data to reflect any changes
                    loadAdminProfile();
                });
            } 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 && imageInput.files.length > 0) {
        const reader = new FileReader();
        reader.onload = function () {
            sendData(reader.result);
        };
        reader.readAsDataURL(imageInput.files[0]);
    } else {
        sendData();
    }
}

// Load admin profile data
async function loadAdminProfile() {
    try {
        const res = await fetch("Backend/Process/GetAdminProfile.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
        setVal("adminFname", d.fname ?? "");
        setVal("adminLname", d.lname ?? "");
        setVal("adminEmail", d.email ?? "");
        setVal("adminPassword", d.password ?? "");

        // Set profile image preview
        const img = document.getElementById("profileImagePreview");
        if (img) {
            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
            };
        }

        // 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;
            desktopProfileImg.src = imagePath;
            desktopProfileImg.onerror = function() {
                if (this.src && !this.src.includes("Resources/Images/Profile.jpg")) {
                    this.src = "Resources/Images/Profile.jpg";
                }
            };
        }
        
        if (mobileProfileImg) {
            mobileProfileImg.onerror = null;
            mobileProfileImg.src = imagePath;
            mobileProfileImg.onerror = function() {
                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" 
        });
    }
}

// Initialize profile image handlers
function initAdminProfileImageHandlers() {
    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 -> open file chooser
    preview.onclick = function(e) {
        e.preventDefault();
        e.stopPropagation();
        fileInput.value = '';
        fileInput.click();
    };

    // Click choose button -> open file chooser
    if (chooseBtn) {
        chooseBtn.onclick = function(e) {
            e.preventDefault();
            e.stopPropagation();
            fileInput.value = '';
            fileInput.click();
        };
    }

    // Show overlay on hover (if overlay exists)
    if (overlay) {
        preview.onmouseenter = function() {
            overlay.style.opacity = "1";
        };
        preview.onmouseleave = function() {
            overlay.style.opacity = "0";
        };
    }

    // When a file is selected, preview it locally
    fileInput.onchange = function(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)
window.loadAdminNavbarProfileImage = async function() {
    try {
        const res = await fetch("Backend/Process/GetAdminProfile.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
                const desktopProfileImg = document.querySelector("#desktopProfile img");
                const mobileProfileImg = document.querySelector("#mobileProfile img");
                
                if (desktopProfileImg) {
                    desktopProfileImg.onerror = null;
                    desktopProfileImg.src = imagePath;
                    desktopProfileImg.onerror = function() {
                        this.src = "Resources/Images/Profile.jpg";
                    };
                }
                
                if (mobileProfileImg) {
                    mobileProfileImg.onerror = null;
                    mobileProfileImg.src = imagePath;
                    mobileProfileImg.onerror = function() {
                        this.src = "Resources/Images/Profile.jpg";
                    };
                }
            }
        }
    } catch (err) {
        console.warn("Could not load admin navbar profile image:", err);
    }
};

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

// Load profile data when modal is shown
document.addEventListener('DOMContentLoaded', () => {
    // Load navbar profile images when DOM is ready
    if (window.loadAdminNavbarProfileImage) {
        window.loadAdminNavbarProfileImage();
    }
    
    const profileModal = document.getElementById('profileModal');
    if (profileModal) {
        profileModal.addEventListener('show.bs.modal', () => {
            loadAdminProfile();
            // Initialize handlers when modal opens (elements are now in DOM)
            setTimeout(() => {
                initAdminProfileImageHandlers();
            }, 100);
        });
    }
    
    // Also try to initialize immediately
    initAdminProfileImageHandlers();
});

