let profileArray = [];

document.addEventListener("DOMContentLoaded", function(){
    let containerColumn = document.getElementById("container-row");
    getProfiles();

    // Render all profile data
    function renderProfiles(item){
        // Debug log
        console.log(item);
        let firstName = item.first_name;
        let personNumber = item.person_number;
        let personPicture = item.picture;
        
        const div = document.createElement("div");
        div.innerHTML = 
        `
        <div class='container-column'>
        <div class="block_image">
            <img src="http://localhost:8080/Images/${personPicture}" 
            id="profile-${personNumber}"
            onclick="getPicture(${personNumber})"/>
        </div>
        <div class="block_image_text">
            <p>${firstName}</p>
        </div>
        </div>
        `
        document.getElementById("container-row").appendChild(div);
    }

    // Get all profile data from DB
    function getProfiles(){
        fetch("/profile_management_api.php")
        .then(res => res.json())
        .then(data => {
            profileArray = data;
            data.forEach(row => {
                renderProfiles(row);
            })
        })
    }
    }
)

// Show data when a profile is clicked
function getPicture(personNumber){

    const profile = profileArray.find(p => p.person_number == personNumber)
    const fields = Object.entries(profile).map(([key, value]) => `<p>${key}: ${value}</p>`).join("");

    document.getElementById("container-row").innerHTML = 
    `
    <div class="block">
    <div class="block_image">
            <img src="http://localhost:8080/Images/${profile.picture}" 
            id="profile-${personNumber}"
            onclick="getPicture(${personNumber})"/>
    </div>
    <div class="block_image_text">
        ${fields}
    </div>
    </div>
    `;
}
