function toggleEdit() {
    document.querySelectorAll('.edit-field').forEach(el => el.style.display = 'block');
    document.querySelectorAll('.profile-info p').forEach(el => el.style.display = 'none');
    document.querySelectorAll('.profile-info h2').forEach(el => el.style.display = 'none');

    document.getElementById('edit-btn').style.display = 'none';
    document.getElementById('edit-btn2').style.display = 'none';
    document.getElementById('save-btn').style.display = 'inline-block';
}

async function saveProfile() {
    const phone = document.getElementById('input-phone').value.trim();
    const username = document.getElementById('input-username').value;
    const uname = document.getElementById('input-uname').value;
    const countryCode = document.getElementById('input-country').value;
    fetch('update_profile.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: new URLSearchParams({
            phone: phone,
            username: username,
            uname: uname,
            countryCode: countryCode
        })
    })
        .then(response => response.json())
        .then(data => {
            if (data['status'] != 'Success') {
                document.getElementById('error').style.display = 'flex';
                return;
            }else{
                alert('Data Updated Successfully!');
            }
        })
        .catch(error => {
            console.error('Error:', error);
        });

    window.location.href = "profile.php";
}

function logoutUser() {
    document.body.style.transition = "opacity 0.5s ease";
    document.body.style.setProperty("opacity", "0.5", "important");

    setTimeout(() => {
        if (confirm("Are you sure you want to log out?")) {
            window.location.href = "logout.php";
        } else {
            document.body.style.setProperty("opacity", "1", "important");
        }
    }, 300);
}


function changeAvatar(event) {
    const file = event.target.files[0];
    if (file && file.type.startsWith('image/')) {
        // Preview image
        const reader = new FileReader();
        reader.onload = function (e) {
            document.getElementById('avatar-img').src = e.target.result;
        };
        reader.readAsDataURL(file);

        // Upload to server
        const formData = new FormData();
        formData.append('avatar', file);

        fetch('upload_avatar.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.text())
        .then(url => {
            console.log("Uploaded URL:", url);
        })
        .catch(error => {
            console.error("Upload error:", error);
        });
    } else {
        alert("Please upload a valid image.");
    }
}
