var idCollege;
var estimated = 0;
var rowCount = 0;
var events = [];
var modality = '';

function navigation(btn) {
    
    var paramsBack ={};

    if (btn == "back") {
        window.history.back()
        //gotoPage('home','registerStudents',paramsBack);
    }else if(btn == 'register'){
        
        // Validamos que los montos de los pagos cubran la deuda
        var acum = 0;
        var arrAmounts = document.querySelectorAll('[id^=amount_]');
        for(let i = 0; i < rowCount; i++){
            
            acum += parseFloat(arrAmounts[i].value.replace(/[.]/g,"").replace(/[,]/,"."));
        }
        
        console.log(acum);
        /*
        if(acum < parseFloat(document.getElementById('amountTotal').value.replace(/[.]/g,"").replace(/[,]/,"."))){
            error.innerHTML = "Debe cubrir el total a pagar";
            gotoTop();
        }else*/ if(rowCount == 0){
            error.innerHTML = "Debe ingresar 1 pago mínimo";
            gotoTop();
        }else if(document.getElementById('operationDate').value == ''){
            error.innerHTML = "Fecha es obligatorio";
            gotoTop();
        }else{
            var accountsList = document.querySelectorAll('[id^=accountBank_]');
            var typeIdList = document.querySelectorAll('[id^=typeId_]');
            var identificationsList = document.querySelectorAll('[id^=identification_]');
            var referencesList = document.querySelectorAll('[id^=reference_]');
            var typeOfList = document.querySelectorAll('[id^=kindOp_]');
            var qtyPupils = document.getElementById('totalPupils').value;
            var currencyList = document.querySelectorAll('[id^=currencyType_]');
            var params = {};
            //recorremos los pagos para guardarlos
            for(let i = 0; i < rowCount; i++){
                if(i == 0){
                    params.schoolidlist = idCollege;
                    params.due = document.getElementById('amountTotal').value.replace(/[.]/g,"").replace(/[,]/,".");
                    params.datelist = document.getElementById('operationDate').value;
                    params.accountlist = accountsList[i].value;
                    params.riflist = typeIdList[i].value + "-" + identificationsList[i].value;
                    params.reflist = referencesList[i].value;
                    params.typelist = typeOfList[i].value;
                    params.amountlist = arrAmounts[i].value.replace(/[.]/g,"").replace(/[,]/,".");
                    params.currencyid = currencyList[i].value,
                    params.qtylist = qtyPupils;
                    params.sessionid = getSessionId();
                    params.events = events.join('|');
                    params.modalidad = modality == 'Online' ? 1 : 2;
                }else{
                    params.accountlist += '|'+accountsList[i].value;
                    params.riflist += '|'+typeIdList[i].value + "-" + identificationsList[i].value;
                    params.reflist += '|'+referencesList[i].value;
                    params.currencyid += '|'+currencyList[i].value,
                    params.typelist += '|'+typeOfList[i].value;
                    params.amountlist += '|'+arrAmounts[i].value.replace(/[.]/g,"").replace(/[,]/,".");
                    params.events = events.join('|');
                    params.modalidad = modality == 'Online' ? 1 : 2;
                }
            }
            
            console.log(params);
            loadScreen()
            callWS("GET","schools/savepayments",params,respx);
        }
    }
    
    function respx(status, respText){
        var json;
        var error = document.getElementById('error');
        
        if (status == 200){
            document.getElementsByClassName('registerPayment')[0].setAttribute('onclick','');
            json = JSON.parse(respText);
            var params ={
                show: 1,
            };
            error.innerHTML = "";
            gotoTop()
            document.getElementById('registerPayButton').disabled = true;
            closeLoad()
            document.getElementById('confirmation').innerHTML = "Registro de Pago Exitoso";
            let timerVal = 0;
            var timer = setInterval(function(){
                timerVal++;
                console.log(timerVal);
                if(timerVal == 2){
                    clearInterval(timer);
                    gotoPage('home','main',params);
                }
            },1000);
        }else{
            error.innerHTML = "Error interno";
        }
    }
    
    function gotoTop(duration = 500){
        let element = document.documentElement;
        
        let to = document.getElementById('confirmation').offsetTop - 200;
        
        element.scrollTop = to;
    }
}



window.onload = function carga() {
    
    disabledEstimatedBtn()
    
    var amount = document.getElementById('amount');
    var located = new URLSearchParams(location.search);
    
    //Logout
    document.getElementById('logOut').addEventListener("click", function(){
        gotoPage('login','main',{});
    });
    
    if (localStorage.getItem('events') != undefined) {
        events = localStorage.getItem('events').split('|');
    }
    
    if (localStorage.getItem('modality') != undefined) {
        modality = localStorage.getItem('modality');
    }
    
    var dateNow = document.getElementsByClassName('datePicker')[0];
    dateNow.max = new Date().toISOString().split("T")[0];
    
    if(located.get('fm') == 1 ){
        var buttonNotSelect = document.getElementsByClassName('registerStudents')[0];
        var buttonSelect = document.getElementsByClassName('informationCollege')[0];
        
        buttonNotSelect.setAttribute('class','InformationCollege');
        buttonSelect.setAttribute('class','registerStudents');
    }
    
    var params = {
      ssid: getSessionId(),
    };
    
    callWS('GET','schools/entry',params,respx);
    
    function respx(status, respText){
        var validStudents = {};
        var students = [];
        console.log(status);
        console.log(JSON.parse(respText));
        var json = JSON.parse(respText);
        idCollege = json.id;
        if( status == 200){
            
            showLabelPrivate(json.privat);
            
            json.editlocked ? disabledButton() : changeButtonLink();
            
            if(!json.privat){
                var params ={};
                
                gotoPage('home','main',params);
            }
        }
        document.getElementsByClassName('userName')[0].innerHTML = json.contact;
        document.getElementById('schoolName').innerHTML = json.name;
        
        if(localStorage.getItem('qtyPupils') == '' || localStorage.getItem('qtyPupils') == undefined || localStorage.getItem('qtyPupils') == null){
            var grades = Object.keys(json.estimatedpupils);

            for(let i = 0; i < grades.length; i++){
                students[grades[i]] = Object.values(json.estimatedpupils[grades[i]]);
            }
            
            for(let i = 0; i < Object.keys(students).length ; i++){
                for(let j = 0; j < students[grades[0]].length; j++){
                    estimated += parseInt(students[grades[i]][j]);
                }
            }
            
            if (json.payment == null || json.payment.length == 0) {
                gotoPage('home','main', {});
            }
            
        }else{
            estimated = localStorage.getItem('qtyPupils');
            var totalPrice = (json.price.amount * estimated) * (events.length > 0 ? events.length : 1);
            document.getElementById('totalPupils').value = estimated;
            
            if (modality == "Online" && events.length <= 1) {
                document.getElementById('amountTotal').value = number_format(totalPrice - (totalPrice* 0.125), 2);
            } else if (modality == "Online" && events.length == 2) {
                document.getElementById('amountTotal').value = number_format(totalPrice - (totalPrice* 0.25), 2);
            } else {
                document.getElementById('amountTotal').value = number_format(totalPrice, 2);
            }
            
            const box = document.getElementById('boxDetailsEvents');
            
            box.innerHTML += `
                    <ul class="itemsBox">
                        <li class="itemsToPay">Eventos: ${events.join(',')}</li>
                        <li class="itemsToPay">Modalidad: ${modality}</li>
                    </ul>
                `;
        }
        
        if(json.payment === null || json.payment.length === 0){
            changeButton(located.get('nvg')) 
        }else{
            loadInfo(json.payment,located.get('nvg'))
        }

        if(json.payment !== null){
            if(json.payment.length > 0){
                document.getElementsByClassName('recalculatePayment')[0].innerHTML="Volver";
                document.getElementsByClassName('recalculatePayment')[0].setAttribute('onclick',"navigation('back')");
            }
        }
    }
    
    loadAcc(getSessionId(), 5);
}

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


function loadAcc(sessionid, id){
    let params = {};
    
    params.sessionid = sessionid;
    params.id = id;
    
    loadScreen();
    callWS("GET", "settings/entry", params, respx);
    
    function respx(status, respText){
        console.log(status);
        console.log(JSON.parse(respText));
        var json = JSON.parse(respText);
        
        switch(status){
            case 200:
                
                if(document.getElementById('accountBank') != null){
                    var arrAcc = json.entry.content.split('|');
                    
                    arrAcc.forEach(el => {
                        var option = document.createElement('option');
                        option.innerHTML = el;
                        option.value = el;
                        
                        document.getElementById('accountBank').add(option);
                    }) 
                }
                
                break;
            default:
                
                break;
        }
        closeLoad();
        
        loadDate(sessionid, 4);
    }
}

function disabledButton(){
    document.getElementsByClassName('registerStudents')[0].style.opacity = 0.5;
    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 deleteSelect(){
    document.getElementById('typeId').style.display = "none";
}

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

function changeButton(nvg) {
    var buttonPay = document.getElementsByClassName('recalculatePayment')[0];
    buttonPay.innerHTML = "Volver";
    buttonPay.setAttribute('onclick',`navigation('back')`);
}

function loadInfo(payment, nvg = 0){
    var bottonBack =  document.getElementsByClassName('registerPayment')[0];
    let haveMore = 0;
    var currentGroup = 0;
    
    // Obtenemos la cantidad de grupos que tenemos
    for(let i = 0; i < payment.length; i++){
        
        if(payment[i].group != currentGroup){
            haveMore++;
        }
        
         currentGroup = payment[i].group;
    }
    
    console.log(haveMore);
    
    if((localStorage.getItem('qtyPupils') == '' || localStorage.getItem('qtyPupils') == undefined || localStorage.getItem('qtyPupils') == null) && haveMore > 1){
        document.getElementsByClassName('msg')[0].style.display = 'none';
        document.getElementById('headerForm').innerHTML = '';
        document.getElementById('formTable').innerHTML = '';
    }else if( (localStorage.getItem('qtyPupils') == '' || localStorage.getItem('qtyPupils') == undefined || localStorage.getItem('qtyPupils') == null) && haveMore == 1){
        document.getElementById('formTable').innerHTML = '';
    }
    
    currentGroup = 0;
    
    for(let i = 0; i < payment.length; i++){
        
        if((localStorage.getItem('qtyPupils') == '' || localStorage.getItem('qtyPupils') == undefined || localStorage.getItem('qtyPupils') == null) && haveMore < 2){
            console.log('alo');
            document.getElementsByClassName('msg')[0].innerHTML = "Informaci\u00F3n de Pago"
            document.getElementById('operationDate').value = payment[0].datepay.short;
            document.getElementById('amountTotal').value = payment[0].due.formatted;
            document.getElementById('totalPupils').value = payment[0].pupilqty;
            document.getElementById('operationDate').setAttribute('readonly',true);
            bottonBack.style.display = 'none';
            //document.getElementById('formTable').innerHTML = '';
        }else if(payment[i].group != currentGroup || i == 0){
    
            document.getElementById('formTable').innerHTML += '<p class="msg" style="text-align: center;">Informaci\u00F3n de Pago</p>';
            
            document.getElementById('formTable').innerHTML += `
            <div class="dataEntry">
                <div class="inputEntry">
                    <div class="inputLabel inputlabelStick">
                        <label for="operationDate">Fecha de Operaci&oacute;n</label>
                        <input type="date" class="datePicker operationDateClass" value="${payment[i].datepay.short}">
                    </div>
                    <div class="inputLabel inputlabelStick">
                        <label for="amountTotal">Monto total</label>
                        <div class="currencyAmount amountTotalBoxClass">
                            <label>${payment[i].currencyid == 1 ? 'Bs.' : '$'}</label>
                            <input type="text" placeholder="monto" class="amountTotalClass" readonly value="${payment[i].due.formatted}">
                        </div>
                    </div>
                    
                    <div class="inputLabel inputlabelStick">
                        <label for="totalPupils">Total de Alumnos</label>
                        <input type="number" class="totalPupilsClass" readonly value="${payment[i].pupilqty}">
                    </div>
                    
                </div>
            </div>
            `;
        }
        
        currentGroup = payment[i].group;
        
        document.getElementById('formTable').innerHTML += `
            <div class="inputEntry" id="row${i+1}" style="margin-top: 15px;">
                <div class="inputLabel">
                    <label for="accountBank_${i+1}">Cuenta Bancaria</label>
                    <select id="accountBank_${i+1}" readonly >
                        <option disabled selected value="${(payment[i].account)}">${(payment[i].account)}</option>
                    </select>
                </div>
                <div class="inputLabel">
                    <label for="reference_${i+1}">N&uacute;mero de Operaci&oacute;n</label>
                    <input type="text" placeholder="últimos 6 dígitos" id="reference_${i+1}" maxlength="6" value="${payment[i].ref}" readonly>
                </div>
                <div class="inputLabel">
                    <label for="amount_${i+1}">Monto</label>
                    <div class="currencyAmount">
                        <label>${payment[i].currencyid == 1 ? 'Bs.' : '$'}</label>
                        <input type="text" placeholder="monto" id="amount_${i+1}" class="amounts" value="${(payment[i].amount.formatted)}" readonly>
                    </div>
                </div>
                <div class="inputLabel">
                    <label for="kindOp_${i+1}">Tipo de Operaci&oacute;n</label>
                    <select id="kindOp_${i+1}" readonly value="">
                        <option disabled selected value="${payment[i].type.id}">${(payment[i].type.dsc)}</option>
                    </select>
                </div>
                <div class="inputLabel">
                    <label for="identification_${i+1}">C&eacute;dula - RIF</label>
                    <div class="nac">
                        <select id="typeId_${i+1}" class="typesId" readonly>
                            <option selected value="${payment[i].rif.split('-')[0]}">${payment[i].rif.split('-')[0]}</option>
                        </select>
                        <input type="text" placeholder="00000000" id="identification_${i+1}" value="${payment[i].rif.split('-')[1]}" class="identifications" readonly>
                    </div>
                </div>
                `;
    }
    
    if(localStorage.getItem('qtyPupils') == '' || localStorage.getItem('qtyPupils') == undefined || localStorage.getItem('qtyPupils') == null){
        document.getElementById('formTable').innerHTML += `
            <div class="buttons">
                <button type="button" class="registerPayment" onclick="navigation('register')">Registrar Pago</button>
                <button type="button" class="recalculatePayment" onclick="navigation('back')">Volver</button>
            </div>
        `;
        bottonBack =  document.getElementsByClassName('registerPayment')[0];
        bottonBack.style.display = 'none';
    }
}

function makeRegister() {
    var valNumber=/^(([0-9])|(ext|x)){6}$/;
    var valAmount=/^[0-9.,]+$/;
    var valId=/^(([0-9])|(ext|x)){6,10}$/;
    
    var rif = document.getElementById('identification').value
    var mount = document.getElementById('amount').value;
    var currency = document.getElementById('currencyType').value;
    var error = document.getElementById('error');
    
    var params ={
        schoolidlist: idCollege,
        accountlist: document.getElementById('accountBank').value,
        riflist: document.getElementById('typeId').value + "-" + document.getElementById('identification').value,
        reflist: document.getElementById('reference').value,
        typelist: document.getElementById('kindOp').value,
        currency: currency,
        amountlist: document.getElementById('amount').value.replace(/[.]/g,"").replace(/[,]/,"."),
        sessionid: getSessionId()
    };
    
    if(params.accountlist == "0" || params.riflist === "" || params.reflist === "" || params.typelist == "0" || params.amountlist === ""){
        error.innerHTML = "Campos vac\u00EDos";
        gotoTop();
    }else if(!valId.test(rif)) {
        error.innerHTML = "Identificaci\u00F3n incorrecta";
        gotoTop();
    }else if (!valAmount.test(mount) ){
        error.innerHTML = "Monto incorrecto";
        gotoTop();
    }else if(!valNumber.test(params.reflist)){
        error.innerHTML = "Referencia incorrecta";
        gotoTop();
    //}else if(params.amountlist > parseFloat(document.getElementById('amount').placeholder.replace(/[.]/g,"").replace(/[,]/,"."))){
    //    console.log(params.amountlist);
    //    console.log((document.getElementById('amount').placeholder.replace(/[.]/g,"").replace(/[,]/,".")));
     //   error.innerHTML = "Monto mayor al monto a pagar";
       // gotoTop();
    }else{
        rowCount++;
        error.innerHTML = "";
        document.getElementById('infoData').innerHTML += `
            <div class="inputEntry" id="row${rowCount}" style="margin-top: 15px;">
                <div class="inputLabel">
                    <label for="accountBank_${rowCount}">Cuenta Bancaria</label>
                    <select id="accountBank_${rowCount}" readonly value="${params.accountlist}">
                        <option disabled selected value="${params.accountlist}">${params.accountlist}</option>
                    </select>
                </div>
                <div class="inputLabel">
                    <label for="reference_${rowCount}">N&uacute;mero de Operaci&oacute;n</label>
                    <input type="text" placeholder="últimos 6 dígitos" id="reference_${rowCount}" maxlength="6" value="${params.reflist}" readonly>
                </div>
                <div class="inputLabel">
                    <label for="amount_${rowCount}">Monto</label>
                    <div class="currencyAmount">
                        <select class="selectCurrency" id="currencyType_${rowCount}">
                            <option value="${params.currency}">${params.currency == 1 ? 'Bs.' : '$'}</option>
                        </select>
                        <input type="text" placeholder="monto" id="amount_${rowCount}" class="amounts" value="${(number_format(params.amountlist,2))}" readonly>
                    </div>
                </div>
                <div class="inputLabel">
                    <label for="kindOp_${rowCount}">Tipo de Operaci&oacute;n</label>
                    <select id="kindOp_${rowCount}" readonly value="">
                        <option disabled selected value="${params.typelist}">${(getKindOP(parseInt(params.typelist)))}</option>
                    </select>
                </div>
                <div class="inputLabel">
                    <label for="identification_${rowCount}">C&eacute;dula - RIF</label>
                    <div class="nac">
                        <select id="typeId_${rowCount}" class="typesId" readonly>
                            <option selected value="${document.getElementById('typeId').value}">${document.getElementById('typeId').value}</option>
                        </select>
                        <input type="text" placeholder="00000000" id="identification_${rowCount}" value="${document.getElementById('identification').value}" class="identifications" readonly>
                    </div>
                </div>
                
                <span class="lessCircle" onclick="deleteRow('${rowCount}')"></span>
                `;
        
        //document.getElementById('typeId').value = "";
        document.getElementById('accountBank').value = "0";
        document.getElementById('identification').value = "";
        document.getElementById('currencyType').value = "1";
        document.getElementById('kindOp').value = "0";
        document.getElementById('reference').value = "";
        document.getElementById('amount').value = "";
        document.getElementById('amount').addEventListener('keyup',function(event){ 
            var number = event.target.value.replace(/\D/g, "")
            .replace(/([0-9])([0-9]{2})$/, '$1,$2')
            .replace(/\B(?=(\d{3})+(?!\d)\.?)/g, ".");
            event.target.value = number;
        } );
        
        //document.getElementById('amount').placeholder = number_format((document.getElementById('amount').placeholder.replace(/[.]/g,"").replace(/[,]/,".") - params.amountlist),2);
    }
    
    function gotoTop(duration = 500){
        let element = document.documentElement;
        
        let to = document.getElementById('confirmation').offsetTop - 200;
        
        element.scrollTop = to;
    }
}

function deleteRow(id){
    rowCount--;
    
    //let placeholder = parseFloat(document.getElementById('amount').placeholder.replace(/[.]/g,"").replace(/[,]/,"."));
    let valueDeleted = parseFloat(document.getElementById('amount_'+id).value.replace(/[.]/g,"").replace(/[,]/,"."));
    
    //document.getElementById('amount').placeholder = number_format((valueDeleted + placeholder),2);
    
    document.getElementById('row'+id).remove();
}

function getKindOP(id){
    var str = '';
    
    switch(id){
        case 1:
            str = 'Mismo banco';
            break;
        case 2:
            str = 'Otro banco';
            break;
    }
    
    return str;
}

function loadScreen() {
    var popup = document.getElementsByClassName("popupLoad")[0];
    
    var style = document.createElement('style');
    document.head.appendChild(style);
    style.sheet.insertRule(`.popupLoad {position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: ${window.screen.height <= 635 ? "auto" : '100%'};
        background-color: rgba(0,0,0,0.5); display:flex; align-items: center;
        ${window.screen.height <= 635 ? 'padding: 10px 0px;' : null}}`);
    
    document.body.style.overflowY = window.screen.height <= 635 ? "scroll" : "hidden";
        
    popup.innerHTML = `
    <div class="loaded">
        <div class="loaderWrapper">
            <div class="loader"></div>
        </div>
    </div>`;
}

function closeLoad() {
    var popup = document.getElementsByClassName("popupLoad")[0];
    var style = document.createElement('style');
    document.head.appendChild(style);
    
    style.sheet.insertRule(`.popupLoad {display: none}`);
        document.body.style.overflowY = "scroll";
}

function formattedAmount(event){ 
    console.log('testing');
    var number = event.value.replace(/\D/g, "")
    .replace(/([0-9])([0-9]{2})$/, '$1,$2')
    .replace(/\B(?=(\d{3})+(?!\d)\.?)/g, ".");
    event.value = number;
}

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);
        }
    }
}