var price = 0;
var privat = false;
var ownEvents = [];

window.onload = function carga() {
    
    disabledEstimatedBtn()
    
    var params = {
        ssid: getSessionId(),  
    };
    
    document.getElementById('addedNewStudents').addEventListener("click", function(){
        console.log(document.getElementsByName('eventsOptions'))
    });
    
    document.getElementById('logOut').addEventListener("click", function(){
        gotoPage('login','main',{});
    });
    
    document.getElementById('newPupils').addEventListener('blur', (e) => {
        let qty = e.target.value;
        
        newCalculate(qty);
    });
    
    loadScreen();
    callWS("GET", "schools/entry", params, respx);
    
    function respx(status, respText){
        var json = JSON.parse(respText);
        let imageDina = document.getElementsByClassName("logoStudent")[0];
        switch(status){
            case 200:
                
                // MArcamos la modalidad
                if (json.modality != null) {
                    const optionsModality = document.getElementsByName('modalidad');
                    for (let i = 0; i < optionsModality.length; i++) {
                        
                        if (optionsModality[i].value == json.modality) {
                            optionsModality[i].checked = true;
                        } else {
                            optionsModality[i].disabled = true;
                        }
                    }
                }
                
                // Marcamos los eventos
                if (json.events != null) {
                    ownEvents = json.events;
                }
                
                document.getElementsByClassName('userName')[0].innerHTML = json.contact;
                document.getElementById('schoolName').innerHTML = json.name;
                document.getElementById('pupilPrice').value = `${json.price.amount}$`;
                price = json.price.amount;
                privat = json.privat;
                showLabelPrivate(json.privat);

                if (json.editlocked) {
                    disabledButton();
                } else {
                    changeButton();
                }
                
                var studentsPerSection = [];
                var validStudents = json.estimatedpupils;
                var grades = Object.keys(validStudents);
                var totally = 0;
            
            
                for(let i = 0; i < grades.length; i++){
                    studentsPerSection[grades[i]] = Object.values(validStudents[grades[i]]);
                }
            
                for(let i = 0; i < Object.keys(studentsPerSection).length ; i++){
                    for(let j = 0; j < studentsPerSection[grades[0]].length; j++){
                        if (studentsPerSection[grades[i]][j] != undefined && studentsPerSection[grades[i]][j] != null) {
                            totally += parseInt(studentsPerSection[grades[i]][j]);
                        }
                    }
                }
                
                document.getElementById('qtyTotal').value = totally;
                
                document.getElementById('addedNewStudents').addEventListener('click', (e) => {
                    var error = document.getElementById('error');
                    
                    if(document.getElementById('newPupils').value == '' || document.getElementById('newPupils').value == 0){
                        error.innerHTML = "Campo inválido";
                        setTimeout(() => {
                            error.innerHTML = "";
                        },3000)
                        return 0;
                    }
                    
                    let qty = document.getElementById('newPupils').value;
                    
                    const events = document.getElementsByName('eventsOptions');
                    const eventsVal = [];
                    for (let i = 0; i < events.length; i++) {
                        if(events[i].checked){
                            eventsVal.push(events[i].value)
                        }
                    }
                    
                    if(eventsVal.length == 0){
                        error.innerHTML = "Debe elegir los eventos a participar";
                        setTimeout(() => {
                            error.innerHTML = "";
                        },3000)
                        return 0;
                    }
                    
                    let modalidad = '';
                    if (document.querySelector('input[name="modalidad"]:checked')) {
                        modalidad = document.querySelector('input[name="modalidad"]:checked').value;
                    }
                    
                    if(modalidad == ''){
                        error.innerHTML = "Debe elegir una modalidad";
                        setTimeout(() => {
                            error.innerHTML = "";
                        },3000)
                        return 0;
                    }
                    
                    var params = {
                        schoolid: json.id,
                        grade1: qty,
                        grade2: 0,
                        grade3: 0,
                        grade4: 0,
                        grade5: 0,
                        grade6: 0,
                        ssid: getSessionId(),
                        events: eventsVal.join('|'),
                        modalidad: modalidad == 'Online' ? 1 : 2,
                        block: 1,
                    };
                    
                    if( qty != 0 ) {
                        loadScreen();
                        callWS("GET", "schools/saveestimatedpupils", params, respx);
                    }
                    
                    function respx(status, respText){
                        var located = new URLSearchParams(location.search);
                        console.log(status);
                        console.log(JSON.parse(respText));
                        var json = JSON.parse(respText);
                        switch(status){
                            case 200:
                                gotoPage('home','main', {});
                                break;
                            case 422:
                                localStorage.setItem('qtyPupils', document.getElementById('newPupils').value);
                                localStorage.setItem('modality', modalidad)
                                localStorage.setItem('events', eventsVal.join('|'))
                    
                                var params = {
                                    ssid: getSessionId(),
                                };
                                
                                gotoPage('home','registerPay',params);
                                break;
                        }
                        closeLoad();
                    }
                });
                
                loadEvents()
                
                var paramsList = {
                    sessionid: getSessionId(),
                    schoolid: json.id,
                    filter: ``,
                    offset: 0,
                    order: `id ASC`,
                    numofrecords: 1,
                };
            
                callWS("GET", "pupils/list", paramsList, respxList);
                function respxList(status, respText){
                    console.log(JSON.parse(respText));
                    var json = JSON.parse(respText);
                    
                    if (status == 200){
                        document.getElementById('totalPupils').value = json.numofrecords;
                        document.getElementById('allowedQty').value = document.getElementById('qtyTotal').value - document.getElementById('totalPupils').value;
                    }
                    
                }
                break;
            default:
        }
        closeLoad();
        
        loadAcc(getSessionId(), 5);
    }
}

function changeButton(){
    var link = document.getElementById('studentLink');
    link.setAttribute('href',`javascript:navigationMenu('searchStudent')`);
}

function disabledButton(){
    
    document.getElementById('studentLink').style.cursor = "default";
    document.getElementById('studentLink').setAttribute('href','javascript:void(0)');
    
    document.getElementById('linkPupils').style.opacity = 0.5;
    document.getElementById('linkPupils').style.cursor = "default";
    document.getElementById('linkPupils').setAttribute('href','javascript:void(0)');
}

function loadAcc(sessionid, id){
    let params = {
        sessionid,
        id,
    };
    
    loadScreen();
    callWS("GET", "settings/entry", params, respx);
    
    function respx(status, respText){
        console.log(JSON.parse(respText));
        var json = JSON.parse(respText);
        
        switch(status){
            case 200:
                
                break;
            default:
        }
        closeLoad();
    }
}

const newCalculate = (qty) => {
    
    if(qty < 0){
        document.getElementById('newPupils').value = 0;
        return 0;
    }
    
    let modalidad = '';
    if (document.querySelector('input[name="modalidad"]:checked')) {
        modalidad = document.querySelector('input[name="modalidad"]:checked').value;
    }
    
    const events = document.getElementsByName('eventsOptions');
    const eventsChecked = [];
    for (let i = 0; i < events.length; i++) {
        if(events[i].checked){
            eventsChecked.push(events[i]);
        }
    }
    let totalPrice = (qty * price) * (eventsChecked.length > 0 ? eventsChecked.length : 1);
    document.getElementById('newAmount').value = putPoints(totalPrice);
    
    if (privat) {
        // Colocamos el descuento en el subtotal
        if (modalidad == "Online" && eventsChecked.length <= 1) {
            document.getElementById('discount').value = "12.5%";
            document.getElementById('totalPay').value = `${totalPrice - (totalPrice* 0.125)}$`;
        } else if (modalidad == "Online" && eventsChecked.length == 2) {
            document.getElementById('discount').value = "25%";
            document.getElementById('totalPay').value = `${totalPrice - (totalPrice* 0.25)}$`;
        } else {
            document.getElementById('discount').value = "0%";
            document.getElementById('totalPay').value = `${totalPrice}$`;
        }
    } else {
        document.getElementById('discount').value = "100%";
        document.getElementById('totalPay').value = `0$`;
    }
    
}

const putPoints = number => number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".") + ",00";

function loadDate(sessionid, id){
    let params = {
        sessionid,
        id,
    };
    
    loadScreen();
    callWS("GET", "settings/entry", params, respx);
    
    function respx(status, respText){
        console.log(JSON.parse(respText));
        var json = JSON.parse(respText);
        
        switch(status){
            case 200:
                break;
            default:
                
                break;
        }
        closeLoad();
    }
}

function loadEvents() {
    let params = {};
    
    params.sessionid = getSessionId();
    params.id = 8;
    
    loadScreen();
    callWS("GET", "settings/entry", params, respx);
    
    function respx(status, respText){
        console.log(JSON.parse(respText));
        var json = JSON.parse(respText);
        
        switch(status){
            case 200:
                // Cargamos los eventos
                const eventsBox = document.getElementById('eventsBox');
                const eventsArr = json.entry.content.split("|");
                console.log(eventsArr)
                eventsBox.innerHTML = '';
                
                for (let i = 0; i < eventsArr.length; i++) {
                    eventsBox.innerHTML += `
                    <div class="optionInputBox">
                        <input type="checkbox" id="event${i}" name="eventsOptions" value="${eventsArr[i]}" onchange="recalculateTotal()" checked onclick="return false">
                        <label for="event${i}" class="labelSecond optionInputLabel">${eventsArr[i]}</label><br>
                    </div>
                    `;

                }
                
                break;
            default:
                
                break;
        }
        closeLoad();
    }
}

function recalculateTotal(){
    let qty = document.getElementById('newPupils').value;
    
    newCalculate(qty);
}

function disabledEstimatedBtn () {
    let params = {
        id: 7
    }
    loadScreen();
    callWS("GET", "settings/entryregister", params, respx);
    
    //Obtenemos los datos del servicio
    function respx(status, respText){
        var json = JSON.parse(respText);
        closeLoad();
        if (status == 200){
            if (json.entry.content == 0) {
                navigationMenu('main');
            }
        }else{
            console.log(json.msg);
        }
    }
}