// SETTINGS
var clientsConf = {
    type                          : "client",
    baseURL                       : "clients.php",
    // LIST
    list_selector                 : "#clientsList",
    // SEARCH
    search_selector               : "#clientsSearch .searchGrp",
    // VIEW
    view_modalSelector            : "#modalViewClient",
    view_btnSelector              : ".btnViewClient",
    // ADD
    add_modalSelector             : "#modalAddClient",
    add_btnSelector               : "#btnAddClient",
    // EDIT
    edit_modalSelector            : "#modalEditClient",
    edit_btnSelector              : ".btnEditClient",
    // DELETE
    delete_modalSelector          : "#modalDeleteClient",
    delete_btnSelector            : ".btnDeleteClient",
}

// MODALS
var modalViewClient    = false;
var modalAddClient     = false;
var modalEditClient    = false;
var modalDeleteClient  = false;

$(document).ready( function() {
    // LIST LOADER
    initListProgressLoad($(clientsConf.list_selector), clientsConf.baseURL, clientsConf.type+" list");
    
    // SEARCH
    $(clientsConf.search_selector).initSearchGroup();
    
    // VIEW
    modalViewClient = $(clientsConf.view_modalSelector);
    if(modalViewClient.length>0) {
        initViewClient();
        // VIEW REQUEST
        var id = getUrlParameter("ref");
        if(id!==false && parseInt(id)>0 && current_page == "clients") {
            modalViewClient_clear(modalViewClient);
            modalViewClient_loadDatas(modalViewClient, id);
        }
    }
    
    // ADD
    modalAddClient = $(clientsConf.add_modalSelector);
    if(modalAddClient.length>0) initAddClient();

    // EDIT
    modalEditClient = $(clientsConf.edit_modalSelector);
    if(modalEditClient.length>0) initEditClient();

    // DELETE
    modalDeleteClient = $(clientsConf.delete_modalSelector);
    if(modalDeleteClient.length>0) initDeleteClient();
});

/***** MODAL VIEW *****/
function initViewClient() {
    // INIT VIEW BTNs
    var initBtnFct = function() { modalForm_initBtnView(
        $(clientsConf.view_btnSelector),        // BTNs
        modalViewClient,                        // MODAL
        modalViewClient_clear,                  // CLEAR FUNCTION
        modalViewClient_loadDatas               // LOAD DATAS FUNCTION
    )};
    registerListProgressLoadCbkFct( $("tbody.progressLoadList"), initBtnFct );
    initBtnFct();
    
    // TABS
    modalForm_initTabs(modalViewClient);

    // CANCEL
    modalViewClient.on('hidden.bs.modal', function() { modalViewClient_clear(modalViewClient); });
    
    // EMPECHE LA FERMETURE SI ON EST ENTRAIN D'EDITER UNE LIGNE D'ABSENCE
    modalViewClient.on('hide.bs.modal', function(e) {
        if(modalViewClient.find("tr.editable").length>0) e.preventDefault();
    });
}

function modalViewClient_loadDatas(modal, id) {
    $.post(clientsConf.baseURL, { 'ref' : id, 'action' : 'getDatas' }, function(jsonTxt) {
        var datas = JSON.parse(jsonTxt);

        modal.find("small.db_ref > span").html(datas.ref);
        
        modal.find("td.nom").html(datas.prenom+" "+datas.nom);
        modal.find("td.tel").html( (datas.tel!="" && datas.tel!=null) ? '<a href="tel:'+datas.tel+'">'+datas.tel+'</a>' : "." );
        modal.find("td.email").html( (datas.email!="" && datas.email!=null) ? '<a href="mailto:'+datas.email+'">'+datas.email+'</a>' : ".");
        
        // CONTRATS
        $.post(clientsConf.baseURL, { 'ref' : id, 'action' : 'modalView_getTab', 'tab' : 'contrats' }, function(result) { 
            modal.find("div.tabContrats").html(result);
        }).fail(function() { alert("ERREUR SERVEUR ! (client modal view - load tab contrats)"); });
        // ABSENCES
        modalViewClient_loadTabAbsences();
        
        modal.modal('show');
    }).fail(function() { alert("("+clientsConf.type+" - load modal view)"); });
}

function modalViewClient_clear(modal) {
    modal.removeAttr("view_id");
    
    modal.find("small.db_ref > span").html("");
    
    modalForm_resetTabs(modal);
    
    modal.find("td.nom").html("");
    modal.find("td.tel").html("");
    modal.find("td.email").html("");
    
    modal.find("div.tabContrats").html("");
    modal.find("div.tabAbsences").html("");
    
    modal.find("table.modal-body tfoot").addClass("hide").find("tr:not(.header)").remove();
}

function modalViewClient_loadTabAbsences() {
    $.post(clientsConf.baseURL, { 'ref' : modalViewClient.attr("view_id"), 'action' : 'modalView_getTab', 'tab' : 'absences' }, function(result) { 
        modalViewClient.find("div.tabAbsences").html(result);
        modalViewClient_initTabAbsences();
    }).fail(function() { alert(srvErrorMsg+" (load modal view client - tab absences)"); });
}

function modalViewClient_initTabAbsences() {
    // BTN ADD ABSENCES
    modalViewClient.find("#btnAddAbsence").click(function(e) {
        e.preventDefault(); $(this).blur();
        
        var tr = $("<tr ref='new'></tr>").html( modalViewClient.find("tr.absenceNewRowTemplate").html() );
        modalViewClient.find("div.tabAbsences table tbody").append(tr);
        
        nullChild = modalViewClient.find("div.tabAbsences table tbody tr.nullChild");
        if(nullChild.length>0) nullChild.remove();
        
        modalViewClient_initAbsenceRow(tr);
    });
    
    // INIT ROWS
    modalViewClient.find("div.tabAbsences table tbody tr.absence").each(function(n,e) { modalViewClient_initAbsenceRow($(this)); })
}

function modalViewClient_initAbsenceRow(row) {
    var ref = row.attr("ref"); if(parseInt(ref)>0) ref = parseInt(ref);
    
    var tdDebut = row.find("td.debut"); var tdFin = row.find("td.fin"); var tdRmq = row.find("td.remarque");
    
    var oldDebut = tdDebut.html();
    var d = parseDate(oldDebut, "dd/mm/yyyy"); if(!d) d = new Date();
    var debut = formatDate(d, "yyyy-mm-dd");
    
    var oldFin = tdFin.html();
    var f = parseDate(oldFin, "dd/mm/yyyy"); if(!f) f = new Date();
    var fin = formatDate(f, "yyyy-mm-dd");
    
    var oldRmq = tdRmq.html();
    var rmq    = `${oldRmq}`;
    
    var iptDebut = $("<input type='date' class='editable' name='debut'>").val(debut).blur(function(e) {
        debut = $(this).val();
        d = parseDate(debut, "yyyy-mm-dd");
        if(f<d) {
            fin = `${debut}`;
            f = parseDate(fin, "yyyy-mm-dd");
            iptFin.val(fin).focus();
        }
    });
    var iptFin = $("<input type='date' class='editable' name='fin'>").val(fin).blur(function(e) {
        fin = $(this).val();
        f = parseDate(fin, "yyyy-mm-dd");
        if(d>f) {
            debut = `${fin}`;
            d = parseDate(debut, "yyyy-mm-dd");
            iptDebut.val(debut).focus();
        }
    });
    var iptRmq = $("<input type='text' class='editable' name='remarque'>").val(rmq).blur(function(e) { rmq = $(this).val(); });
    
    var btnEdit = row.find("button.btnEditAbsence");
    var btnDel = row.find("button.btnDeleteAbsence");
    
    btnEdit.click(function(e) {
        e.preventDefault(); $(this).blur();
        if(modalViewClient.find("tr.editable").length>0 && !row.hasClass("editable")) return;
        
        // SAVE
        if(row.hasClass("editable")) {
            iptDebut.blur(); iptFin.blur(); iptRmq.blur();
            datas = { 
                'client' : modalViewClient.attr("view_id"), 
                'debut' : debut, 
                'fin' : fin, 
                'remarque' : rmq
            };
            if(ref=='new') datas.action = "add_client_absence";
            else { datas.action = "edit_client_absence"; datas.absence_ref = ref; }
            
            $.post(clientsConf.baseURL, datas, function(result) {
                if(parseInt(result)>0) modalViewClient_loadTabAbsences();
                else { console.error(result); alert(result); }
            }).fail(function() { alert("ERREUR SERVEUR ! (modal view client - save absence)"); });
        }
        // EDIT
        else {
            row.addClass("editable");
            btnEdit.removeClass('glyphicon-edit').addClass('glyphicon-floppy-saved');
            btnDel.removeClass('glyphicon-trash').addClass('glyphicon-floppy-remove');
            
            tdDebut.html('').append(iptDebut);
            tdFin.html('').append(iptFin);
            tdRmq.html('').append(iptRmq);
            
            iptDebut.focus();
        }
    });
    
    btnDel.click(function(e) {
        e.preventDefault(); $(this).blur();
        if(modalViewClient.find("tr.editable").length>0 && !row.hasClass("editable")) return;
        
        // CANCEL
        if(row.hasClass("editable")) {
            if(ref == 'new') row.remove();
            else {
                iptDebut.blur(); iptFin.blur(); iptRmq.blur();
                
                tdDebut.html(oldDebut);
                tdFin.html(oldFin);
                tdRmq.html(oldRmq);
                
                row.removeClass("editable");
                btnEdit.removeClass('glyphicon-floppy-saved').addClass('glyphicon-edit');
                btnDel.removeClass('glyphicon-floppy-remove').addClass('glyphicon-trash');
            }
        }
        // DELETE
        else {
            if(!ref>0) return;
            if(confirm("Êtes-vous sur de vouloir supprimer cette absence ?")) {
                $.post(clientsConf.baseURL, { 'action': "delete_client_absence", 'absence_ref': ref }, function(result) {
                    if(parseInt(result)>0) modalViewClient_loadTabAbsences();
                    else { console.error(result); alert(result); }
                }).fail(function() { alert("ERREUR SERVEUR ! (modal view client - delete absence)"); });
            }
        }
    });
    
    if(ref == "new") row.find("button.btnEditAbsence").click();
}

/***** MODAL FORM ADD/EDIT *****/
function modalFormClient_init(modal) {
    modal.find("form").on("submit", function(e) { e.preventDefault(); });
    
    // NOM
    initUpperCaseInput(modal.find("input[name=nom]"), null, function() { $(this).blur(); });
    // PRENOM
    initFirstUpperCaseInput(modal.find("input[name=prenom]"), null, function() { $(this).blur(); });
    // TEL
    initTelInput(modal.find("input[name=tel]"), true, "libs/intl-tel-input-15.0.0/build/js/utils.js");
    // EMAIL
    initEmailInput(modal.find("input[name=email]"));
}

function modalFormClient_loadDatas(modal,id) {
    $.post(clientsConf.baseURL, { 'ref' : id, 'action' : 'getDatas' }, function(jsonTxt) {
        var datas = JSON.parse(jsonTxt);

        modal.find("input[name=nom]").val(datas.nom);
        modal.find("input[name=prenom]").val(datas.prenom);
        modal.find("input[name=tel]").val(datas.tel);
        modal.find("input[name=email]").val(datas.email);

        if(modal) modal.modal('show');
    }).fail(function() { alert("("+clientsConf.type+" - load datas in modal form)"); });
}

function modalFormClient_clear(modal) {
    modal.removeAttr("edit_id");
    modal.find("div.modaLoader").removeClass("show");
    
    modal.find("input[name=nom]").val("");
    modal.find("input[name=prenom]").val("");
    modal.find("input[name=tel]").val("");
    modal.find("input[name=email]").val("");
}

function modalFormClient_getDatas(modal) {
    var datas = {
        'nom' :     modal.find("input[name=nom]").val(),
        'prenom' :  modal.find("input[name=prenom]").val(),
        'tel' :     modal.find("input[name=tel]").intlTelInput("isValidNumber") ? modal.find("input[name=tel]").val() : "",
        'email' :   validateEmail(modal.find("input[name=email]").val()) ? modal.find("input[name=email]").val() : ""
    };
    return datas;
}

function modalFormClient_checkDatas(datas) { 
    if(datas.nom=="" || datas.prenom=="") { 
        alert("ERREUR : au minimum, un nom et un prénom doivent être renseigné !");
        return false;
    }
    return true;
}

/***** ADD *****/
function initAddClient() {
    // INIT FORM
    modalFormClient_init(modalAddClient);

    // INIT ADD BTN
    modalForm_initBtnAdd(
        $(clientsConf.add_btnSelector),         // BTN ADD
        modalAddClient,                         // MODAL
        modalFormClient_clear                   // CLEAR FORM FUNCTION
    );
    
    // INIT SAVE BTN
    modalForm_initBtnSaveAdd(
        modalAddClient.find(".btnSave"),        // BTN SAVE
        clientsConf.type,                       // ADD TYPE
        modalAddClient,                         // MODAL
        modalFormClient_getDatas,               // GET FORM DATAS FUNCTION
        modalFormClient_checkDatas,             // CHECK FORM DATAS FUNCTION
        clientsConf.baseURL                     // SAVE URL
    );

    // CANCEL
    modalAddClient.on('hidden.bs.modal', function (e) { modalFormClient_clear(modalAddClient); });
}

/***** EDIT *****/
function initEditClient() {
    // INIT FORM
    modalFormClient_init(modalEditClient);

    // INIT EDIT BTNs
    var initBtnFct = function() { modalForm_initBtnEdit(
        $(clientsConf.edit_btnSelector),        // BTNs
        modalEditClient,                        // MODAL
        modalFormClient_clear,                  // CLEAR FUNCTION
        modalFormClient_loadDatas               // LOAD DATAS FUNCTION
    )};
    registerListProgressLoadCbkFct( $("tbody.progressLoadList"), initBtnFct );
    initBtnFct();
    
    // INIT SAVE EDIT BTN
    modalForm_initBtnSaveEdit(
        modalEditClient.find(".btnSave"),       // BTN SAVE
        clientsConf.type,                       // EDIT TYPE
        modalEditClient,                        // MODAL
        modalFormClient_getDatas,               // GET FORM DATAS FUNCTION
        modalFormClient_checkDatas,             // CHECK FORM DATAS FUNCTION
        clientsConf.baseURL                     // SAVE URL
    );

    // CANCEL
    modalEditClient.on('hidden.bs.modal', function (e) { modalFormClient_clear(modalEditClient); });
}

/***** DELETE *****/
function initDeleteClient() {
    // INIT DELETE BTNs
    var initBtnFct = function() { modalForm_initBtnDelete(
        $(clientsConf.delete_btnSelector),      // BTNs
        modalDeleteClient,                      // MODAL
        modalDeleteClient_clear,                // CLEAR MODAL FUNCTION
        modalDeleteClient_loadDatas             // LOAD DATAS FUNCTION
    )};
    registerListProgressLoadCbkFct( $("tbody.progressLoadList"), initBtnFct );
    initBtnFct();

    // INIT SAVE DELETE BTN
    modalForm_initBtnSaveDelete(
        modalDeleteClient.find(".btnSave"),     // BTN SAVE
        clientsConf.type,                       // DELETE TYPE
        modalDeleteClient,                      // MODAL
        false,                                  // GET FORM DATAS FUNCTION
        false,                                  // CHECK FORM DATAS FUNCTION
        clientsConf.baseURL                     // SAVE URL
    );

    // CANCEL
    modalDeleteClient.on('hidden.bs.modal', function (e) { modalDeleteClient_clear(); });
}

function modalDeleteClient_loadDatas(btn, id) {
    modalDeleteClient.find('b.name').html( btn.attr('nom') );
    modalDeleteClient.modal('show');
}

function modalDeleteClient_clear() {
    modalDeleteClient.removeAttr("delete_id");
    modalDeleteClient.find('b.name').html("");
}