/* 
----------------------------------------------------------
  MODULE : MASK JS TOOLS AND FUNCTIONS 
  V1.0 / 2018
  AUTHOR : SGHAIER MAHMOUD  
----------------------------------------------------------
*/
// --- on mask ready listener --- 
Dropzone.autoDiscover = false;

(function ($) {
    "use strict";
    // load detected 
    // $('[href="#nav-follow"]').tab('show');
    /*
    nav-client-tab 
    nav-ticket-tab
    nav-follow-tab
    nav-escalade-tab
    */
 //  global vars 
 var last_fetched_clients ; 
 //   paging onchange 
$("#bypage" ).change(function() {
    resubmit('#grid-form')
  });
// --- validate listener --- 
if ($('#validate-trigger,#validate-trigger-bottom').length > 0 ) {
    // Validation API  :  validation and submit auto submit event already attached main.js 
    $('#validate-trigger,#validate-trigger-bottom').click(function(){
        $('#actionmode').val($('#prmnextmode').val());  
        if ( $('#mask-form')[0].checkValidity() === false ) { 
             $('#mask-form').addClass('was-validated')
             attach_advanced_select_change()
             notify_warning('Merci de remplir les champs obligatoires')
        } else {
             $("#mask-form").submit() 
        }
    })  
    }
 // --- cancel listener --- 
if ($('#cancel-trigger, #cancel-trigger-bottom').length > 0) {
    $('#cancel-trigger, #cancel-trigger-bottom').click(function() {
        var edit_window = $('#editwindow').val(); // todo : popup mode (test)
        var grid_url = $('#gridscript').val();
        const employeeId = $('#frmid').val();

        // Redirection avec paramètre correct
        location.href = grid_url + "?frmid=" + employeeId;
    });
}

// --- Dropzone Uploader / Listener ---
if ($("#fileDropzone").length != 0) {
  const log = false; // ← mettre false pour désactiver tous les console.log
  const myDropzone = new Dropzone("#fileDropzone", {
    url: "ajax/ajaxUpload.php",
    maxFilesize: 20,
    paramName: "file",
    acceptedFiles: ".jpg,.jpeg,.png,.pdf,.doc,.docx,.xls,.xlsx,.zip",
    addRemoveLinks: true,
    dictDefaultMessage: "Déposez vos fichiers ici ou cliquez pour les sélectionner",
    dictFileUploading: "", // <-- texte pendant l'upload (vide pour rien afficher)
    dictRemoveFile: "Supprimer",
    dictCancelUpload: "Annuler", // ← texte personnalisé
    parallelUploads: 4,
    timeout: 0,
    autoProcessQueue: false,
    init: function () {
      const dz = this;
      function logMsg(...args) {
        if (log) console.log(...args);
      }
      function canUpload() {
        const activeRow = $('#the-folder-grid tr.active');
        const folderId = activeRow.attr('id');
        const employeeId = $('#frmid').val();
        logMsg("Test JS avant upload :", { folderId, employeeId });
        if (!folderId || !employeeId) {
          notify_warning("Merci de sélectionner un dossier !")
          if (log) console.warn("Upload bloqué, données manquantes !");
          return false;
        }
        return true;
      }
      document.querySelector("#upload-trigger").addEventListener("click", function (e) {
        e.preventDefault();
        logMsg("Clic sur submit, fichiers dans la queue :", dz.getQueuedFiles());
        if (canUpload()) {
          logMsg("Test OK, lancement de l'upload !");
          dz.processQueue();
        }
      });
      dz.on("addedfile", function(file) {
        logMsg("Fichier ajouté :", file);
      });
      dz.on("sending", function(file, xhr, formData) {
        const activeRow = $('#the-folder-grid tr.active');
        const folderId = activeRow.attr('id');
        const employeeId = $('#frmid').val();
        const smsConfirm = $('#sms_confirm').is(':checked') ? 1 : 0;
        logMsg("Envoi du fichier :", file.name);
        logMsg("Données ajoutées au formData :", { folderId, employeeId, smsConfirm });
        formData.append("folder_id", folderId);
        formData.append("employee_id", employeeId);
        formData.append("sms_confirm", smsConfirm);
        for (let pair of formData.entries()) {
          logMsg("FormData:", pair[0], "=", pair[1]);
        }
      });
      dz.on("success", function(file, response) {
        let data;
        if (typeof response === "string") {
          try {
            data = JSON.parse(response);
          } catch (e) {
            if (log) console.error("Erreur JSON :", e, response);
            return;
          }
        } else {
          data = response;
        }
        logMsg("Upload réussi :", file.name, "Données :", data);
        if (data.success) {
          notify_success("Fichier ajouté avec succès !")
             setTimeout(function() {
             location.reload();
            }, 2000); // 2000 ms = 2 secondes
        } else {
            notify_alert("Erreur serveur : " + (data.error || "Inconnue"))
        }
      });
      dz.on("error", function(file, errorMessage) {
        if (log) console.error("Erreur Dropzone :", errorMessage, "Fichier :", file);
      });
      dz.on("removedfile", function(file) {
        logMsg("Fichier retiré :", file);
      });
    }
  });

}

// --- Remove file  / Listener ---
// --- Remove file / Listener ---
$(document).on('click', '.delete-file-btn', function(e) {
    e.preventDefault();

    const btn = $(this);
    const fileId = btn.data('file-id');

    if (!fileId) {
        console.error("ID du fichier manquant pour suppression");
        return;
    }

    // Fonction à exécuter après confirmation
    const fnRemove = function() {
        $.ajax({
            url: 'ajax/ajaxDeleteFile.php', // script PHP côté serveur
            method: 'POST',
            data: { file_id: fileId },
            dataType: 'json',
            beforeSend: function() {
                // tu peux ajouter un loader ici si nécessaire
                console.log("Suppression en cours du fichier :", fileId);
            },
            success: function(resp) {
                if (resp.success) {
                    notify_success("Fichier supprimé avec succès !");
                    btn.closest('tr').fadeOut(300, function() { $(this).remove(); });
                } else {
                    notify_alert("Erreur : " + (resp.error || "Inconnue"));
                }
            },
            error: function(xhr, status, error) {
                notify_alert("Erreur AJAX : " + error);
                console.error("Erreur AJAX :", status, error);
            }
        });
    };

    // Affiche la confirmation avant suppression
    box_confirm("Voulez-vous vraiment supprimer ce fichier ?", fnRemove);
});


// --- custom behaviors - events    
// ticket edit : reasons muti select  
$(".mask-ticket #reason_fk" ).change(function() {
    $.ajax({url: app_domain_hostname + app_path + "ajax/ajaxFetch.php?idc="+$(this).val()+"&idt="+$("#frmid").val(), 
    success: function(result){
        $("#reason_categories").html(result);
        $('.advancedselect').selectpicker('refresh');
      }});
  });
// ticket edit : make fields required for status 3 
  $("#status_fk" ).change(function() {
   if ( $(this).val()==3 ) {
    $("#close_comment").prop('required',true);
    $("#close_rating_fk").prop('required',true);
    $("#sla_fk").prop('required',true);
   } else {
    $("#close_comment").prop('required',false);
    $("#close_rating_fk").prop('required',false);
    $("#sla_fk").prop('required',false);
   }
  });
//  $('.nav-tabs a').on('shown.bs.tab', function(event){
//  var current = $(event.target).attr('id');   // active tab
//  if ( current == "nav-follow-tab") { 
// ticket edit : detect ticket tab / button 
if ($('#validate-history-button').length > 0 ) {
    // ---
    $('#history-table').on( "click","#validate-history-button", function(e){ 
        e.preventDefault();
        var typed_text  =  $('#history-description').val()
        if (!(typed_text))  {
            $('#history-description-error').removeClass('d-none').slideDown().delay(500).slideUp()
            return false 
          }
        $.ajax(
             { 
                url: app_domain_hostname + app_path +  "ajax/ajaxTicketHistory.php",
                type: "post", 
                /*contentType: "application/json; charset=utf-8",*/
                data : {  id : $("#frmid").val() , description : typed_text },
            beforeSend: function(){
                $("#validate-history-loader").removeClass("fa-circle").addClass("fa-cog fa-spin") // Handle the beforeSend event
                $("#validate-history-button").prop('disabled', true)
                },
            success: function(result){
                $("#validate-history-loader").removeClass("fa-cog fa-spin").addClass("fa-circle")
                $("#validate-history-button").prop('disabled', false)
                $('#history-description').val('')
                var jsonResult = JSON.parse(result)  
                var str = '<tr><td> '+jsonResult[0].data[0].user_name+ ' <br> <span class="badge badge-secondary">'
                str = str + jsonResult[0].data[0].created_on + ' </span> <span class="small text-secondary">SU'+jsonResult[0].data[0].ticket_history_id+ '</span> '
                str = str + '</td> <td>'+jsonResult[0].data[0].message+ '</td><td></td></tr> '
            $("#ajax-history").prepend(str) 
            },
            error: function(error_result){
                /*contentType: "application/json; charset=utf-8",*/
                console.log (error_result) 
                }
        });
    })  
   // ---
    }
// ticket edit : detect the input used_phone_number change
$('input#used_phone_number').bind("keyup",function() { 
    var typed_number  =  $(this).val()
    $('#fetched-search').hide().removeClass("d-none")
    if ( $.isNumeric( typed_number ) && typed_number.length >= 8 && $('#prmnextmode').val() != 'update' ) {
    $("a#search-loader i").removeClass("fa-search").addClass("fa-cog fa-spin") // Handle the beforeSend event
    $("#mobile1").val(typed_number) // transfer temp number to client file 
    // --- ajax
    $.ajax(
        { 
           url: app_domain_hostname + app_path +  "ajax/ajaxSearchClient.php",
           type: "post", 
           /*contentType: "application/json; charset=utf-8",*/
           data : {  nb : typed_number },
           success: function(result){
                $('#fetched-search li').not('li:last').remove()
                $("a#search-loader i").removeClass("fa-cog fa-spin").addClass("fa-search") 
                //animateCSS('#fetched-search', 'fadeInLeft', function() {})
                var jsonResult = JSON.parse(result)  
                last_fetched_clients =  jsonResult[0].data  
                if  (jsonResult[0].data.length> 0 ) {
                    // iterates rows
                    $('#fetched-search').slideDown(200)
                    for(var item in jsonResult[0].data) {
                        var str =   '<li data-clid ="'+jsonResult[0].data[item].client_id+'" class="list-group-item d-flex align-items-center">'
                        str = str + '<span class="mr-auto"> '+jsonResult[0].data[item].first_name+' '+jsonResult[0].data[item].last_name+' </span>'
                        str = str + '<!--<span class="mr-1 badge badge-dark badge-pill">0</span>-->'
                        str = str + '<button class="btn btn-primary" id="validate-client-button" type="button"> <i class="fa fa-plus" aria-hidden="true"></i> </button>'
                        str = str + '</li> '
                        $("#fetched-search").prepend(str) 
                        //iterate columns 
                        //$.each(jsonResult[0].data[item], function (key, data) {
                        // console.log(key+"===>"+data);
                        //})
                    }
                }
       },
       error: function(error_result){
           /*contentType: "application/json; charset=utf-8",*/
           console.log (error_result) 
           }
       });
    } 
    // ---
    else {
        $('#fetched-search').slideUp(200)  
    }
});
// ticket edit : detect the click on fetched result 
 $('#fetched-search').on("click","li",function() { 
        var clicked_item  =  $(this).data("clid")
        if (clicked_item=='close') {
           $('#fetched-search').slideUp(200)   
           return  
        }
        var thisClient = getObjects(last_fetched_clients, 'client_id', clicked_item); // Returns an array of matching objects
        // iterate columns and inject to dom 
         $.each(thisClient[0], function (key, data) {
            $("#"+key).val(data); 
                //console.log(key+":::>"+data);
          })
          $("#client_fk").val(thisClient[0].client_id); // custom foreign key value
          $('#fetched-search').slideUp(200)   
          notify_success('Client attaché a ce ticket avec succès')
    });
// reason edit : filter sub reasons 
var filter_raison_category = function() {
    var category_id = $(".mask-reason-categories #reason_fk" ).val()
    $("#raison_category_parent_id option").hide()
    $("#raison_category_parent_id option")
    .filter(function( index ) {
        return index === 0 || index === 1 || $(this).data( "fk-filter" ) == category_id;
      })
    .show()
}
filter_raison_category() // init
$(".mask-reason-categories #reason_fk" ).change(filter_raison_category); // attach on change 
// store edit : make fields required for status 3 
$("#sign" ).change(function() {
    if ( $(this).val() != "" ) {
      $("#sign_title" ).val( $("#sign option:selected").text() )  
    } else {
      $("#sign_title" ).val("")    
    }
});
})(jQuery); 
// --- custom behaviors - functions    
// custom validation for bootstrap-select mask mode (onchange) 
function attach_advanced_select_change () {
    $("select.advancedselect:invalid").closest(".form-group").find(".invalid-tooltip").css("display","block") 
    $("select.advancedselect:invalid").closest(".form-group").find(".btn-select").addClass("invalid").removeClass("valid") 
    $("select.advancedselect").on('change', function () {
        if ($(this)[0].checkValidity() === false ) { 
            $("select.advancedselect:invalid").closest(".form-group").find(".invalid-tooltip").css("display","block") 
            $("select.advancedselect:invalid").closest(".form-group").find(".btn-select").addClass("invalid").removeClass("valid") 
        }
        else {
            $("select.advancedselect:valid").closest(".form-group").find(".invalid-tooltip").css("display","none") 
            $("select.advancedselect:valid").closest(".form-group").find(".btn-select").addClass("valid").removeClass("invalid") 
        }
    });
} 
