/* 
----------------------------------------------------------
  MODULE : GRID JS TOOLS AND FUNCTIONS 
  V1.0 / 2018
  AUTHOR : SGHAIER MAHMOUD  
----------------------------------------------------------
*/
/* 
---  grid onready    --- 
*/


$(function() { 
// --- GRID : Copy UI Values ---
$("#grid-total-result-top").html($("#grid-total-result").html())
// --- GRID : Quick search filter listener  ---
if ($('#search-trigger').length>0) { // only if used
$("#search-trigger").on("keyup", function() {
        var value = $(this).val().toLowerCase();
        $("#the-grid tr").filter(function() {
          $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
        });
      });
    }
// --- GRID :  popOver listener  ---
//$('.popover-data').popover();
$('.popover-data').popover({ trigger: "hover",html : true,  });

// --- GRID td click / dblclik listener ---
if ($('#the-grid').length>0) { // only if used
    cellListener = $('#the-grid').find('tr');
    cellListener.each(function() {
        cellListenerTd = $(this).find('td') ;
          cellListenerTd.each(function() {
             $(this).click(function(){ 
                id_to_pass= $(this).parents("tr:first").attr('id') ;
                if ($(this).attr('rel')!='noClickDetect') {
                 edit($('#editscript').val() , id_to_pass);
                }
           }); 
      });	
 });
}

// --- GRID td click /   listener for custom Folders/files ---
if ($('#the-folder-grid').length > 0) {
    const cellListener = $('#the-folder-grid').find('tr');
    const id_employee = $('#frmid').val();

    function loadFiles(folderId) {
        $.ajax({
            url: 'ajax/ajaxFiles.php',
            type: 'GET',
            data: { id: folderId, id_employee: id_employee },
            beforeSend: function () {
                $('#the-files-grid').html('<tr><td class="text-center">Chargement...</td></tr>');
            },
            success: function (response) {
                $('#the-files-grid').html(response);
            },
            error: function () {
                $('#the-files-grid').html('<tr><td class="text-center">Erreur de chargement...</td></tr>');
            }
        });
    }

    cellListener.each(function () {
        const cellListenerTd = $(this).find('td');
        cellListenerTd.each(function () {
            $(this).on('click', function () {
                const $tr = $(this).closest('tr');
                const folderId = $tr.attr('id'); // id crypté
                console.log('Selected folder:', folderId);
                console.log('Current user:', id_employee);

                if ($(this).attr('rel') !== 'noClickDetect') {
                    $('#the-folder-grid tr').removeClass('active');
                    $tr.addClass('active');

                    loadFiles(folderId); // AJAX call
                }
            });
        });
    });

    // --- On page init: detect active row and load files ---
    const $activeRow = $('#the-folder-grid tr.active');
    if ($activeRow.length > 0) {
        const activeFolderId = $activeRow.attr('id');
        console.log('Active folder on init:', activeFolderId);
        loadFiles(activeFolderId);
    }
}


// --- GRID edit listener ---
if ($('.ico-edit').length>0) { // only if used
    $('.ico-edit').click(function() {
    id_to_pass = $(this).parents("tr:first").attr('id')
    edit($('#editscript').val() , id_to_pass);
});
}

if ($('.ico-files').length>0) { // only if used
    $('.ico-files').click(function() {
    id_to_pass = $(this).parents("tr:first").attr('id')
    edit($('#editscript').val() , id_to_pass);
});
}

// --- GRID remove listener ---
if ($('.ico-delete').length > 0) { // only if used
    $('.ico-delete').click(function() {

        let id_to_pass = $(this).closest("tr").attr('id');
        let table_to_pass = $('#tablename').val();
        let key_to_pass = $('#tablekey').val();

        // Important: wrap the single ID into an array
        let ids = [id_to_pass];
        const fn = function() { remove(table_to_pass, key_to_pass, ids); };
        msg = "Etes-vous sûr(e) de vouloir supprimer cet enregistrement?  "; 
        box_confirm(msg, fn);
 
    });
}


// --- GRID custom push listener ---
if ($('.ico-push').length > 0) {
    $('.ico-push').click(function() {
        let notif_id = $(this).parents("tr:first").attr('id');

        let ajaxURL = 'id=' + notif_id;

        let fn = function() {
            $.ajax({
                url: app_domain_hostname + app_path + "ajax/ajaxPush.php",
                data: ajaxURL,
                cache: false,
                async: true,
                beforeSend: function() {},
                success: function() {
                    window.location.reload();
                }
            });
        };

        box_confirm("Êtes-vous sûr(e) de vouloir diffuser la notification à tout le monde ?", fn);
    });
}



// --- GRID activate/disactivate listener ---
if ($('.ico-flag').length>0) { // only if used
    $('.ico-flag').click(function() {
    id_to_pass = $(this).parents("tr:first").attr('id')
    table_to_pass = $('#tablename').val()
    field_to_pass =  $(this).data('field')
    key_to_pass =  $('#tablekey').val()
    keyvalue_to_pass = id_to_pass
    // action
    act(table_to_pass,key_to_pass, field_to_pass, keyvalue_to_pass )
});
}
// --- addnew listener --- 
if ($('#add-trigger').length > 0 ) {
	$('#add-trigger').click(function(){
     edit_action_url = $('#editscript').val()+'?actionmode=add' //Uses jQuery.load() 
     edit_window =  $('#editwindow').val() // todo : popupmode 
     location.href = edit_action_url;
     // later edit/add can popup in modal if tested above   
     //$('.modal-edit').on('shown.bs.modal', function() {
     //    $(this).find('iframe').attr('src','http://www.google.com')
     //})  
	});
    }
// --- edit listener on checked --- 
	if ($('#edit-trigger').length > 0 ) {
        $('#edit-trigger').click(function(){
            checkedBoxElement =  $('input[name=chksel]:checked')
            if (checkedBoxElement.length == 1 )
            { 
                id_to_pass =checkedBoxElement.parents("tr:first").attr('id')
                // action
                edit($('#editscript').val() , id_to_pass);
            }
            else 
            {
                 //  multi checked not permitted
            }		 
           });
        }

// --- remove listener on checked --- 
if ($('#delete-trigger').length > 0) {

    $('#delete-trigger').click(function() {

        let checkedBoxElements = $('input[name=chksel]:checked');

        if (checkedBoxElements.length === 0) {
            notify_alert("Veuillez sélectionner au moins un enregistrement à supprimer.");
            return;
        }

        let ids = [];
        checkedBoxElements.each(function() {
            let id = $(this).closest("tr").attr('id');
            ids.push(id); // encrypted
        });

        let table_to_pass = $('#tablename').val();
        let key_to_pass   = $('#tablekey').val();

        // Dynamic confirmation
        let msg = (ids.length === 1)
            ? "Êtes-vous sûr(e) de vouloir supprimer cet enregistrement ?"
            : "Êtes-vous sûr(e) de vouloir supprimer ces " + ids.length + " enregistrements ?";

        const fn = function() {
            remove(table_to_pass, key_to_pass, ids);
        };

        box_confirm(msg, fn);
    });
}


// --- row check all listener --- work only with i-check js plug 
if ($('#iCheck-chkselall').length>0) { // only if used
    $('#iCheck-chkselall').on('ifChecked', function(event){
            formElement = $('#grid-form') 
            chkbx = formElement.find('input[name=chksel]');
            chkbx.iCheck('check');  
        });
       $('#iCheck-chkselall').on('ifUnchecked', function(event){
            formElement = $('#grid-form') 
            chkbx = formElement.find('input[name=chksel]');
            chkbx = formElement.find('input[name=chksel]');
            chkbx.iCheck('uncheck');  
        });
    }
// --- row check listener ---
if ($('input[name=chksel]').length>0) { 
    checkBoxElements =  $('input[name=chksel]');
    // init 
    disable_buttons = function () {
       // $('#delete-trigger').addClass("disabled")
        $('#edit-trigger').addClass("disabled")
    };
    enable_buttons  = function () {
      //  $('#delete-trigger').removeClass("disabled")
        $('#edit-trigger').removeClass("disabled")
     };
    disable_buttons(); 
    checkBoxElements.on('ifToggled', function(event){
       checkedBoxElementsRecount =  $('input[name=chksel]:checked').length;
       if( checkedBoxElementsRecount==1 ) {
            enable_buttons(); 
        } 
        else {
            disable_buttons(); 
        }
    });
 }
/* 
---  custom behaviors - events      --- 
*/
// --- filters  : reasons muti select  
$("#grid-form #reason_fk" ).change(function() {
    $.ajax({url: app_domain_hostname + app_path +  "ajax/ajaxFetch.php?idc="+$(this).val()+"&idt="+$("#frmid").val(), 
    beforeSend :  function(){
      $("#reason_categories").parents(".form-group").find(".btn-select").removeClass("animated flash");
    },   
    success: function(result){
        $("#reason_categories").html(result);
        $('.advancedselect').selectpicker('refresh');
        $("#reason_categories").parents(".form-group").find(".btn-select").addClass("animated flash");
      }});
  });
});
/* 
---  grid functions   --- 
*/
// resubmit the form 
function resubmit(formName)
{
     $(formName).submit()
}
 // --- modify action --- 
 function edit(prmScript,prmKey) {
        edit_action_url = prmScript+'?actionmode=edit&frmid='+prmKey  
        edit_window =  $('#editwindow').val() // todo : popupmode 
        location.href = edit_action_url;
        // later edit/add can popup in modal if tested above   
        //$('.modal-edit').on('shown.bs.modal', function() {
        //    $(this).find('iframe').attr('src','http://www.google.com')
        //})  
     }
// AJAX : activate/disactivate action
function act(prmTable,prmKeyName, prmField, prmCkey  )
{
	ajaxURL = 'tbl='+prmTable+'&tblkey='+prmKeyName+'&fld='+prmField+'&id='+prmCkey,
	$.ajax({
		  url:  app_domain_hostname + app_path + $('#ajaxactivator').val(),
		  data: ajaxURL,
		  cache: false,
		  async: true, // use sync results
		  beforeSend: function() {
		       // beforeSend
		     },
		  success: function() {
			   window.location.href = window.location.href
		     }	
		});
}
// AJAX : remove action
function remove(prmTable, prmKeyName, prmKeyValues)
{
    let ajaxURL =
        'tbl=' + prmTable +
        '&tblkey=' + prmKeyName +
        '&id=' + prmKeyValues.join(",");

    $.ajax({
        url: app_domain_hostname + app_path + $('#ajaxdelete').val(),
        data: ajaxURL,
        cache: false,
        async: true,
        beforeSend: function() {},
        success: function() {
            window.location.reload();
        }
    });
}
