$(document).ready(function () {

    $(document).on('change', '#stage_id', async function () {
        let html='<option value="">--</option>'
        if(!$(this).val()){
            $('#user_id').html(html)
            $('#stage_year_id').html(html)
            $('#subject_id').html(html)
            return
        }
        // Get users
        const responseUsers= await ajax({
            url: users_route,
            method: 'get',
            data:{
                stage_id: $(this).val() || null,
                role: 'teacher'
            }
        })
        // console.log({responseUsers});
        for (const row of responseUsers) {
            const selected= row.id?.toString() == user_id ? 'selected' : ''
            html+=`<option value="${row.id}" ${selected} >${(row.id || '')} ${(row.name || '')}</option>`
        }
        $('#user_id').html(html)

        // Get years
        html='<option value="">--</option>'
        const response= await ajax({
            url: stage_years_route,
            method: 'get',
            data:{
                stage_id: $(this).val() || null
            }
        })
        // console.log({response});
        for (const row of response) {
            const selected= row.id?.toString() == stage_year_id ? 'selected' : ''
            html+=`<option value="${row.id}" ${selected} >${row.current_description.name || ''}</option>`
        }
        $('#stage_year_id').html(html)
        $('#stage_year_id').trigger('change')
    });

    $(document).on('change', '#stage_year_id', async function () {
        let html='<option value="">--</option>'
        if(!$(this).val()){
            $('#subject_id').html(html)
            return
        }
        const response= await ajax({
            url: subjects_route,
            method: 'get',
            data:{
                stage_year_id: $(this).val() || null
            }
        })
        // console.log({response});
        for (const row of response) {
            const selected= row.id?.toString() == subject_id ? 'selected' : ''
            html+=`<option value="${row.id}" ${selected} >${row.current_description.name || ''}</option>`
        }
        $('#subject_id').html(html)
    });

    if($('#stage_id').length){
        $('#stage_id').trigger('change')
    }
    
    //
    $(document).on('change', '#type', async function () {
        $('.types').addClass('d-none')
        $('.type_'+$(this).val()).removeClass('d-none')
    });
    if($('#type').length){
        $('#type').trigger('change')
    }
});
