// SETTINGS
var contratsConf = {
    type                          : "contrat",
    baseURL                       : "contrats.php",
    // LIST
    list_selector                 : "#contratsList",
    // SEARCH
    search_selector               : "#contratsSearch .searchGrp",
    filtres_selector              : "#contratsSearch select",
    // VIEW
    view_modalSelector            : "#modalViewContrat",
    view_btnSelector              : ".btnViewContrat",
    // ADD
    add_modalSelector             : "#modalAddContrat",
    add_btnSelector               : "#btnAddContrat",
    // EDIT
    edit_modalSelector            : "#modalEditContrat",
    edit_btnSelector              : ".btnEditContrat",
    // ARCHIVE
    archive_modalSelector         : "#modalArchiveContrat",
    archive_btnSelector           : ".btnArchiveContrat",
    unarchive_btnSelector         : ".btnUnarchiveContrat",
    // DELETE
    delete_modalSelector          : "#modalDeleteContrat",
    delete_btnSelector            : ".btnDeleteContrat"
}

// MODALS
var modalViewContrat    = false;
var modalAddContrat     = false;
var modalEditContrat    = false;
var modalArchiveContrat = false;
var modalDeleteContrat  = false;

$(document).ready( function() {
    // LIST LOADER
    initListProgressLoad($(contratsConf.list_selector), contratsConf.baseURL, contratsConf.type+" list");
    
    // SEARCH / FILTRES
    $(contratsConf.search_selector).initSearchGroup();
    $(contratsConf.filtres_selector).initFiltreSelect();
    
    // VIEW
    modalViewContrat = $(contratsConf.view_modalSelector);
    if(modalViewContrat.length>0) {
        initViewContrat();
        // VIEW REQUEST
        var id = getUrlParameter("ref");
        if(id!==false && parseInt(id)>0 && current_page == "contrats") {
            modalViewContrat_clear(modalViewContrat);
            modalViewContrat_loadDatas(modalViewContrat, id);
        }
    }
    
    // ADD
    modalAddContrat = $(contratsConf.add_modalSelector);
    if(modalAddContrat.length>0) initAddContrat();

    // EDIT
    modalEditContrat = $(contratsConf.edit_modalSelector);
    if(modalEditContrat.length>0) initEditContrat();

    // ARCHIVE
    modalArchiveContrat = $(contratsConf.archive_modalSelector);
    if(modalArchiveContrat.length>0) initArchiveContrat();
    
    // DELETE
    modalDeleteContrat = $(contratsConf.delete_modalSelector);
    if(modalDeleteContrat.length>0) initDeleteContrat();
});

/***** MODAL VIEW *****/
function initViewContrat() {
    // INIT VIEW BTNs
    var initBtnFct = function() { modalForm_initBtnView(
        $(contratsConf.view_btnSelector),        // BTNs
        modalViewContrat,                        // MODAL
        modalViewContrat_clear,                  // CLEAR FUNCTION
        modalViewContrat_loadDatas               // LOAD DATAS FUNCTION
    )};
    registerListProgressLoadCbkFct( $("tbody.progressLoadList"), initBtnFct );
    initBtnFct();
    
    // TABS
    modalForm_initTabs(modalViewContrat);

    // CANCEL
    modalViewContrat.on('hidden.bs.modal', function() { modalViewContrat_clear(modalViewContrat); });
}

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

        modal.find("small.db_ref > span").html(datas.ref);
        
        modal.find("td.type").html(datas.type_nom);
        
        client = datas.client_prenom+" "+datas.client_nom;
        if((datas.client_tel!="" && datas.client_tel!=null) || (datas.client_email!="" && datas.client_email!=null)) {
            client += " <small>(";
            if(datas.client_tel!="" && datas.client_tel!=null) {
                client += '<a href="tel:'+datas.client_tel+'">'+datas.client_tel+'</a>';
                if(datas.client_email!="" && datas.client_email!=null) client += ' / <a href="mailto:'+datas.client_email+'">'+datas.client_email+'</a>';
            }
            else if(datas.client_email!="" && datas.client_email!=null) client += '<a href="mailto:'+datas.client_email+'">'+datas.client_email+'</a>';
            client += ")</small>";
        }
        modal.find("td.client").html(client);
        modal.find("td.tel").html((datas.client_tel!="") ? '<a href="tel:'+datas.client_tel+'">'+datas.client_tel+'</a>' : '.');
        modal.find("td.email").html((datas.client_email!="") ? '<a href="mailto:'+datas.client_email+'">'+datas.client_email+'</a>' : '.');
        
        modal.find("td.date").html(datas.date_print);
        modal.find("td.frequence").html(datas.frequence_print);
        modal.find("td.paniers").html(datas.nb_panier + datas.panier_type);
        modal.find("td.panier_type").html(datas.panier_type);
        modal.find("td.lieu_depot").html(datas.lieu_depot_nom);
        modal.find("td.nb_cheque").html(datas.nb_cheque);
        
        nb_panier_livre = datas.nb_paniers_livres + " / " + datas.nb_paniers;
        if(datas.np_paniers_distrib_avt_saisie>0) {
            nb_panier_livre += " <small>(dont "+datas.np_paniers_distrib_avt_saisie+" livré";
            if(datas.np_paniers_distrib_avt_saisie>1) nb_panier_livre += "s";
            nb_panier_livre += " avant la saisie du contrat)</small>";
        }
        modal.find("td.nb_panier_livre").html(nb_panier_livre);
        modal.find("td.nb_panier_restant").html(datas.nb_paniers_restants + " / " + datas.nb_paniers);
        
        // PANIERS
        $.post(contratsConf.baseURL, { 'ref' : id, 'action' : 'modalView_getTab', 'tab' : 'paniers' }, function(result) { 
            modal.find("div.tabPaniers").html(result);
        }).fail(function() { alert("ERREUR SERVEUR ! (modal view client - load tab paniers)"); });
        
        modal.modal('show');
    }).fail(function() { alert("("+contratsConf.type+" - load modal view)"); });
}

function modalViewContrat_clear(modal) {
    modal.removeAttr("view_id");
    modalForm_resetTabs(modal);
    
    modal.find("small.db_ref > span").html("");
    
    modal.find("ul.formContratTabs > li").removeClass('active hide');
    modal.find("ul.formContratTabs > li:first-child").addClass('active');
    modal.find("div.formContratTabs > div.tab").removeClass("active");
    modal.find("div.formContratTabs > div.tab:first-child").addClass("active");
    
    modal.find("td.nom").html("");
    modal.find("td.tel").html("");
    modal.find("td.email").html("");
    
    modal.find("td.date").html("");
    modal.find("td.frequence").html("");
    modal.find("td.nb_panier").html("");
    modal.find("td.panier_type").html("");
    modal.find("td.lieu_depot").html("");
    modal.find("td.nb_cheque").html("");
    
    modal.find("td.nb_panier_livre").html("");
    modal.find("td.nb_panier_restant").html("");
    
    modal.find("div.tabPaniers").html("");
}

/***** MODAL FORM ADD/EDIT *****/
function modalFormContrat_init(modal) {
    modal.find("form").on("submit", function(e) { e.preventDefault(); });
    
    // CLIENT AUTOCOMPLETE
    initAutocompleteInput(
        modal,                                          // FORMULAIRE
        modal.find("input[name=client]"),               // INPUT
        "clients.php",                                  // URL
        'autocomplete_list',                            // REQUEST ACTION
        "(form contrat - client autocomplete)"          // ERROR CONTEXT
    );
    
    // TYPE
    inlineSelectManager_init(
        modal,                                          // MODAL
        "contrat",                                      // MODAL FORM NAME
        modal.find("select[name=type]").parent(),       // SELECT GROUPE
        "le type de contrat",                           // VALUE NAME
        contratsConf.baseURL,                           // URL
        "type_ref",                                     // REF ATTR
        "add_contrats_type",                            // ADD ACTION
        "edit_contrats_type",                           // EDIT ACTION
        "delete_contrats_type",                         // DELETE ACTION
        "contrats_types_select_list",                   // REFRESH LIST ACTION
        modalFormContrat_contratType_selectClbkFct,     // SELECT CLBK FCT
        modalFormContrat_showCustomType,                // ADD CKBK FCT
        modalFormContrat_showCustomType,                // EDIT CKBK FCT
        modalFormContrat_hideCustomType,                // CANCEL CKBK FCT
        modalFormContrat_contratType_getDatas,          // GET DATAS FCT
        modalFormContrat_contratType_checkDatas,        // CHECK DATAS FCT
        modalFormContrat_hideCustomType                 // SAVED CLBK FCT
    );
    
    // GROUPE
    modal.find("select[name=groupe]").change(function(e) { modalFormContrat_refreshPaniersTypesSelectList(modal, $(this).val()); });
    
    // FREQUENCE => SHOW/HIDE QUINZ GROUPE
    modal.find("select[name=frequence]").change(function(e) {
        freq = $(this).val();
        if(freq=="quinz") modal.find("select[name=quinz_groupe]").parent().removeClass("hide");
        else modal.find("select[name=quinz_groupe]").parent().addClass("hide");
    });
    
    // PANIERS TYPE
    modal.find("select[name=panier_type]").change(function(e) { $(this).blur(); });
    
    // LIEU DEPOT
    inlineSelectManager_init(
        modal,                                          // MODAL
        "contrat",                                      // MODAL FORM NAME
        modal.find("select[name=lieu_depot]").parent(), // SELECT GROUPE
        "le lieu de dépôt",                             // VALUE NAME
        contratsConf.baseURL,                           // URL
        "lieu_ref",                                     // REF ATTR
        "add_lieu",                                     // ADD ACTION
        "edit_lieu",                                    // EDIT ACTION
        "delete_lieu",                                  // DELETE ACTION
        "lieux_select_list"                             // REFRESH LIST ACTION
    );
    
    // NB PANIERS
    initIntInput(modal.find("input[name=nb_paniers]"));
    
    // NB CHEQUE
    initIntInput(modal.find("input[name=nb_cheque]"));
    
    // NB PANIER AVANT SAISIE
    initIntInput(modal.find("input[name=np_paniers_distrib_avt_saisie]"));
    
    modalFormContrat_clear(modal);
}

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

        modal.find("input[name=client]").val(datas.client_prenom+" "+datas.client_nom).attr('ref', datas.client_ref);
        
        inlineSelectManager_setValue(modal.find("select[name=type]").parent(), datas.type_ref);
        if(!datas.type_ref > 0) {
            modal.find("select[name=type]").val("custom");
            modal.find("div.custom_type").removeClass("hide");
            inlineSelectManager_switchBtnAction(modal.find("div.custom_type").parent(), "save_new");
        }
        
        modal.find("select[name=groupe]").val(datas.groupe_ref);
        modal.find("select[name=frequence]").val(datas.frequence);
        modal.find("select[name=panier_type]").val(datas.panier_type_ref);
        modal.find("input[name=nb_paniers]").val(datas.nb_paniers);
        
        if(datas.frequence == "quinz") modal.find("select[name=quinz_groupe]").parent().removeClass("hide");
        modal.find("select[name=quinz_groupe]").val(datas.quinz_groupe);
        
        modal.find("input[name=date]").val(datas.date);
        
        inlineSelectManager_setValue(modal.find("select[name=lieu_depot]").parent(), datas.lieu_depot_ref);
        
        modal.find("input[name=nb_cheque]").val(datas.nb_cheque);
        modal.find("input[name=np_paniers_distrib_avt_saisie]").val(datas.np_paniers_distrib_avt_saisie);
        modal.find("input[type=checkbox][name=force_eligible]").prop("checked",datas.force_eligible>0);

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

function modalFormContrat_refreshPaniersTypesSelectList(modal, groupe) {
    datas = {
        'action' : 'select_list',
        'groupe' : groupe
    };
    $.post("paniers.php", datas, function(result) {
        var oldVal = parseInt( modal.find("select[name=panier_type]").val() );
        modal.find("select[name=panier_type]").html(result);
        if(oldVal>0 && modal.find("select[name=panier_type] option[value="+oldVal+"]")) modal.find("select[name=panier_type]").val(oldVal);
    }).fail(function() { alert("ERREUR SERVEUR ! (form contrat - refresh paniers types select list)"); });
}

function modalFormContrat_clear(modal) {
    modal.removeAttr("edit_id");
    modal.find("div.modaLoader").removeClass("show");
    
    modal.find("input[name=client]").val("");
    
    inlineSelectManager_setValue(modal.find("select[name=type]").parent(), 0);
    
    modal.find("select[name=groupe]").val("");
    modal.find("select[name=frequence]").val("hebdo");
    modal.find("select[name=panier_type]").val("");
    modal.find("input[name=nb_paniers]").val("");
    
    modal.find("select[name=quinz_groupe]").val("A").parent().addClass("hide");
    modal.find("input[name=date]").val(getTodayDate("yyyy-mm-dd"));
    
    inlineSelectManager_setValue(modal.find("select[name=lieu_depot]").parent(), 0);
    
    modal.find("input[name=nb_cheque]").val("");
    modal.find("input[name=np_paniers_distrib_avt_saisie]").val("");
    modal.find("input[type=checkbox][name=force_eligible]").prop("checked",false);
}

function modalFormContrat_getDatas(modal) {
    var datas = {
        'client' :                parseInt( modal.find("input[name=client]").attr('ref') ),
        'type' :                  parseInt( modal.find("select[name=type]").val() ),
        'groupe' :                parseInt( modal.find("select[name=groupe]").val() ),
        'frequence' :                       modal.find("select[name=frequence]").val(),
        'panier_type' :           parseInt( modal.find("select[name=panier_type]").val() ),
        'nb_paniers' :            parseInt( modal.find("input[name=nb_paniers]").val() ),
        'quinz_groupe' :                    modal.find("select[name=quinz_groupe]").val(),
        'date' :                            modal.find("input[name=date]").val(),
        'lieu_depot' :            parseInt( modal.find("select[name=lieu_depot]").val() ),
        'nb_cheque' :             parseInt( modal.find("input[name=nb_cheque]").val() ),
        'np_paniers_distrib_avt_saisie' :   modal.find("input[name=np_paniers_distrib_avt_saisie]").val(),
        'force_eligible' :                  modal.find("input[type=checkbox][name=force_eligible]").prop("checked") ? 1 : 0
    };
    
    // CHECK TYPE_EXIST
    if(!datas.type>0) {
        datas.type = "custom";
        
        sel = "select[name=type] option[grp="+datas.groupe+"]";
        sel+= "[freq="+datas.frequence+"]";
        sel+= "[panier="+datas.panier_type+"]";
        sel+= "[nb_paniers="+datas.nb_paniers+"]";
        var opt = modal.find(sel);
        if(opt.length>0) datas.type = parseInt( opt.attr("value") );
    }
    
    return datas;
}

function modalFormContrat_checkDatas(datas) { 
    if(datas.nom=="") { 
        alert("ERREUR : au minimum, un nom doit être renseigné !");
        return false;
    }
    return true;
}

// CONTRAT TYPE

function modalFormContrat_contratType_selectClbkFct(modal, grp, select) {
    // CUSTOM
    if(select.val() == "custom") {
        modal.find("div.custom_type").removeClass("hide");
        
        inlineSelectManager_switchBtnAction(grp, "save_new");
        inlineSelectManager_switchBtnSecondAction(grp, "hide");
    }
    // EXISTING
    else if(parseInt(select.val())>0) {
        modal.find("div.custom_type").addClass("hide");

        sel = select.find("option:selected");
        grp = sel.attr('grp');
        freq = sel.attr('freq');
        panier = parseInt( sel.attr('panier') );
        nb_paniers = parseInt( sel.attr('nb_paniers') );

        modal.find("select[name=groupe]").val(grp);
        modal.find("select[name=frequence]").val(freq);
        modal.find("select[name=panier_type]").val(panier);
        modal.find("input[name=nb_paniers]").val(nb_paniers);

        // QUINZE-GROUPE
        if(freq=="quinz") modal.find("select[name=quinz_groupe]").parent().removeClass("hide");
        else modal.find("select[name=quinz_groupe]").parent().addClass("hide");
    }
    // CHOISIR...
    else modal.find("div.custom_type").addClass("hide");
}

function modalFormContrat_showCustomType(modal) { modal.find("div.custom_type").removeClass("hide"); }

function modalFormContrat_hideCustomType(modal) { modal.find("div.custom_type").addClass("hide"); }

function modalFormContrat_contratType_getDatas(modal, grp) {
    var datas = {
        'nom' :                 grp.find("input[name=name]").val(),
        'groupe' :              parseInt(modal.find("select[name=groupe]").val()),
        'frequence' :           modal.find("select[name=frequence]").val(),
        'panier_type' :         parseInt(modal.find("select[name=panier_type]").val()),
        'panier_type_valeur' :  parseFloat(modal.find("select[name=panier_type] option:selected").attr("valeur")),
        'nb_paniers' :          parseInt(modal.find("input[name=nb_paniers]").val())
    };
    datas.prix_total = datas.panier_type_valeur * datas.nb_paniers;
    return datas;
}

function modalFormContrat_contratType_checkDatas(datas) {
    if(datas.nom=="" || !datas.groupe>0 || (datas.frequence!="hebdo" && datas.frequence!="quinz") || !datas.panier_type>0 || !datas.nb_paniers>0 || !datas.panier_type_valeur>0) {
        alert("Merci de renseigner tous les critères du contrat !");
        return false;
    }
    return true;
}

/***** ADD *****/
function initAddContrat() {
    // INIT FORM
    modalFormContrat_init(modalAddContrat);

    // INIT ADD BTN
    modalForm_initBtnAdd(
        $(contratsConf.add_btnSelector),         // BTN ADD
        modalAddContrat,                         // MODAL
        modalFormContrat_clear                   // CLEAR FORM FUNCTION
    );
    
    // INIT SAVE BTN
    modalForm_initBtnSaveAdd(
        modalAddContrat.find(".btnSave"),        // BTN SAVE
        contratsConf.type,                       // ADD TYPE
        modalAddContrat,                         // MODAL
        modalFormContrat_getDatas,               // GET FORM DATAS FUNCTION
        modalFormContrat_checkDatas,             // CHECK FORM DATAS FUNCTION
        contratsConf.baseURL                     // SAVE URL
    );

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

/***** EDIT *****/
function initEditContrat() {
    // INIT FORM
    modalFormContrat_init(modalEditContrat);

    // INIT EDIT BTNs
    var initBtnFct = function() { modalForm_initBtnEdit(
        $(contratsConf.edit_btnSelector),        // BTNs
        modalEditContrat,                        // MODAL
        modalFormContrat_clear,                  // CLEAR FUNCTION
        modalFormContrat_loadDatas               // LOAD DATAS FUNCTION
    )};
    registerListProgressLoadCbkFct( $("tbody.progressLoadList"), initBtnFct );
    initBtnFct();
    
    // INIT SAVE EDIT BTN
    modalForm_initBtnSaveEdit(
        modalEditContrat.find(".btnSave"),       // BTN SAVE
        contratsConf.type,                       // EDIT TYPE
        modalEditContrat,                        // MODAL
        modalFormContrat_getDatas,               // GET FORM DATAS FUNCTION
        modalFormContrat_checkDatas,             // CHECK FORM DATAS FUNCTION
        contratsConf.baseURL                     // SAVE URL
    );

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

/***** ARCHIVE *****/
function initArchiveContrat() {
    // INIT ARCHIVE BTNs
    var initBtnFct = function() { modalForm_initBtnArchive(
        $(contratsConf.archive_btnSelector),     // BTNs
        modalArchiveContrat,                     // MODAL
        modalArchiveContrat_clear,               // CLEAR MODAL FUNCTION
        modalArchiveContrat_loadDatas            // LOAD DATAS FUNCTION
    )};
    registerListProgressLoadCbkFct( $("tbody.progressLoadList"), initBtnFct );
    initBtnFct();
    
    // INIT UNARCHIVE BTNs
    var initUnBtnFct = function() { modalForm_initBtnUnarchive(
        $(contratsConf.unarchive_btnSelector),   // BTNs
        contratsConf.type,                       // DELETE TYPE
        modalArchiveContrat,                     // MODAL
        contratsConf.baseURL                     // SAVE URL
    )};
    registerListProgressLoadCbkFct( $("tbody.progressLoadList"), initUnBtnFct );
    initUnBtnFct();

    // INIT SAVE DELETE BTN
    modalForm_initBtnSaveArchive(
        modalArchiveContrat.find(".btnSave"),    // BTN SAVE
        contratsConf.type,                       // DELETE TYPE
        modalArchiveContrat,                     // MODAL
        contratsConf.baseURL                     // SAVE URL
    );

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

function modalArchiveContrat_loadDatas(btn, id) {
    modalArchiveContrat.find('b.ref').html( "#"+btn.attr('ref') );
    modalArchiveContrat.find('b.name').html( btn.attr('nom') );
    modalArchiveContrat.modal('show');
}

function modalArchiveContrat_clear() {
    modalArchiveContrat.removeAttr("archive_id");
    modalArchiveContrat.find('b.ref').html("");
    modalArchiveContrat.find('b.name').html("");
}

/***** DELETE *****/
function initDeleteContrat() {
    // INIT DELETE BTNs
    var initBtnFct = function() { modalForm_initBtnDelete(
        $(contratsConf.delete_btnSelector),      // BTNs
        modalDeleteContrat,                      // MODAL
        modalDeleteContrat_clear,                // CLEAR MODAL FUNCTION
        modalDeleteContrat_loadDatas             // LOAD DATAS FUNCTION
    )};
    registerListProgressLoadCbkFct( $("tbody.progressLoadList"), initBtnFct );
    initBtnFct();

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

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

function modalDeleteContrat_loadDatas(btn, id) {
    modalDeleteContrat.find('b.ref').html( "#"+btn.attr('ref') );
    modalDeleteContrat.find('b.name').html( btn.attr('nom') );
    modalDeleteContrat.modal('show');
}

function modalDeleteContrat_clear() {
    modalDeleteContrat.removeAttr("delete_id");
    modalDeleteContrat.find('b.ref').html("");
    modalDeleteContrat.find('b.name').html("");
}