let select_nou = document.getElementById("select_nou")
let select_type = document.getElementById("select_type")
let select_typeDetail = document.getElementById("select_typeDetail")
select_nou.addEventListener("change", pickType)
select_type.addEventListener("change", pickDetailType)

function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}


function pickType(e) {
    const data = {"nou_id": e.target.value}
    let url = "/open/getType"

    fetch(url, {
        method: 'POST', // or 'PUT'
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCookie("csrftoken")
        },
        body: JSON.stringify(data),
    })
        .then(response => response.json())
        .then(data => {

            for (let i = 0; i < data.length; i++) {
                city_field.innerHTML += `<option value = "${data[i]["id"]}" selescted>${data[i]["name"]}</option>`
            }
        })
        .catch((error) => {
            console.error('Error:', error);
        });

}


function pickDetailType(e) {
    const data = {"type_id": e.target.value}
    let url = "/open/getTypeDetail"

    fetch(url, {
        method: 'POST', // or 'PUT'
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCookie("csrftoken")
        },
        body: JSON.stringify(data),
    })
        .then(response => response.json())
        .then(data => {

            for (let i = 0; i < data.length; i++) {
                select_typeDetail.innerHTML += `<option value = "${data[i]["id"]}" selescted>${data[i]["name"]}</option>`
            }
        })
        .catch((error) => {
            console.error('Error:', error);
        });

}