{extends file="$layouts_admin"}
{block name="head"}

   <link href="{$theme}default/css/grupo.css?v={$config['version']}" rel="stylesheet">
   <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.6.2/css/buttons.dataTables.min.css" />



{/block}

{block name="content"}

<style type="text/css">

    .list-group{
        max-height: 150px;
        margin-bottom: 10px;
        overflow:scroll;
        -webkit-overflow-scrolling: touch;
    }    

</style>

   <input
         type="text"
         value="{$url_base}"
         disabled
         hidden
         id="URL_BASE"
    />

    <input
         type="text"
         value="{$id_user}"
         disabled
         hidden
         id="ID_USER"
    />
 
    <input
         type="text"
         value="{$roll_id}"
         disabled
         hidden
         id="roll_id"
    />

    <input
         type="text"
         value="{$ruta_original}"
         disabled
         hidden
         id="ruta_pantalla"
    />

<div class="row">

    <div class="col-md-12">
        <div class="panel">
            <div class="panel-hdr">
                <h2 style="color: #666; font-weight: 600; "><span></span>IRS Forms - Overview</h2>
                <input type="text" class=" tener_url_base" value={$url_base} disabled hidden/>
            </div>
                                                         
            <div class="panel-container show" id="ibox_form">

                <div class="panel-content">

                    <div class="px-0">
                        
                        <div class="row contenedor" style="padding: 0px">

                           <div class="col-12 col-sm-12 pt-1">
                              <label for="staff"><span style="color:#666;">Staff</span></label>
                           </div>

                           {* staff *}
                            <div class="col-12 col-sm-7 pt-1">
                                {* <label for="staff"><span style="color:#666;">Staff</span></label> *}  
                                
                                <select
                                    class="form-select form-select-sm tener_staff"
                                    name="staff"
                                    id="staff"
                                    style="width: 100%"
                                    placeholder="Select a Staff"
                                    {if $user["roleid"] eq 3}disabled{/if}
                                >
                                    <option value="" >All</option>
                                    {foreach $listado_staff as $ds}
                                        <option value="{$ds['id']}" >{$ds['fullname']}</option>
                                    {/foreach}
                                </select>

                            </div>

                            <div class="col-12 col-sm-5 pt-1" style="display: flex; justify-content: end;">
                                <button
                                    type="button"
                                    class="btn btn-sm btn-primary"
                                    id="consultar_filtros"
                                    
                                >
                                    Search forms by employees

                                    <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24px" height="24px" viewBox="0 0 24 24" version="1.1">
                                       <g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
                                          <rect x="0" y="0" width="24" height="24"/>
                                          <path d="M10,18 C14.418278,18 18,14.418278 18,10 C18,5.581722 14.418278,2 10,2 C5.581722,2 2,5.581722 2,10 C2,14.418278 5.581722,18 10,18 Z M21.7071068,20.2928932 C22.0976311,19.9023689 22.0976311,19.267767 21.7071068,18.8772427 L16.9497475,14.1198834 C17.3453784,13.4433673 17.5606602,12.6790962 17.5606602,11.8535534 C17.5606602,10.0227798 16.5606602,8.56066017 14.8535534,7.85355339 C13.1464466,7.14644661 11.5606602,7.85355339 10.8535534,9.56066017 C10.1464466,11.267767 10.8535534,12.8535534 12.5606602,13.5606602 C13.3852031,13.5606602 14.1494742,13.3453784 14.8259903,12.9497475 L19.5833496,17.7071068 C19.9738739,18.0976311 20.6084758,18.0976311 20.999,17.7071068 L21.7071068,20.2928932 Z" fill="#FFF" fill-rule="nonzero"/>
                                       </g>
                                    </svg>

                                </button>
                            </div>
                           
                            <br />
                             
                             

                        </div>

                       
                    </div>

                </div>
                
            </div>
        </div>
    </div>

    {* informacion de las card *}
    
   <div class="row tbody_envios">
 
      {foreach $listado_estados as $s}
         <div class="col-12 col-sm-4 pt-4">
            <a class="card text-center cambiar_hipervinculo" href="{$ruta}/{$s['id']}" target="_blank" data-estado_id="{$s['id']}">

               <h5 class="card-header">
                  {$s["estado"]}
               </h5>

               <div class="card-body">
                  <p class="card-text"> <strong> {$s["cantidad"]} </strong> </p>
               </div>
 
            </a>
         </div>
      {/foreach}
      
   </div>

   

</div>

 




{/block}

{block name="script"}

<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.6.2/js/dataTables.buttons.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.html5.min.js"></script>

<script>

   const URL_BASE = $(".tener_url_base").val();

   let ruta_pantalla = $("#ruta_pantalla").val();

    //cargar_usuarios_sistema().then((listado_usuarios_admin) =>{
    //    $(".tener_usuario_id").html(
    //        select_html_usuario_sistema(listado_usuarios_admin),
    //    );
    //});

   //$country = $(".tener_customers");
   //$country.select2();

   let fecha = cargar_fecha();
   $(".tener_fecha_desde").val(fecha);
   $(".tener_fecha_hasta").val(fecha);

   var ID_USER = $("#ID_USER").val();
   var url_dashboard = $("#url_dashboard").val();

   var roll_id = $("#roll_id").val();

   $(".tener_staff").val(ID_USER);

    //$('#clx_datatable').DataTable();
 
    
         $("#consultar_filtros").click(function () {
 
            let tener_staff = $(".tener_staff").val() || "";
 
            let enviar_informacion = {
               staff_id: tener_staff,
            };

            //console.log(enviar_informacion);
            //console.log("aqui abajo ahi un return");
            //return;

            $("#consultar_filtros").prop("disabled", true);

            $.ajax({
               type: "POST",
               url: URL_BASE + "forms/filtro-vista-global",
               data: JSON.stringify(enviar_informacion), // Convertir datos a formato JSON
               contentType: "application/json", // Tipo de contenido JSON
               success: function (response) {
                  $("#consultar_filtros").prop("disabled", false);
                  //console.log("Respuesta del servidor:", response);
                  // Hacer algo con la respuesta del servidor
                  //$("#myModal").modal("hide");
                  $(".tbody_envios").html("");

                  try {
                     let info = JSON.parse(response);
                     if (info.type == "success") {
                        let arr = info.data;

                        if (arr == "") {
                           $(".tbody_envios").html(
                              '<tr><th colspan="9" class="centrar pt-4"> No information</th></tr>',
                           );
                        } else {
                           $(".tbody_envios").html(arr);
                        }

                        /*  if (Array.isArray(arr)) {
                           if (arr.length != 0) {
                              var newRow = "";

                              arr.forEach((element) => {
                                 let {
                                    id,
                                    campaign,
                                    crm_groups_id,
                                    channel,
                                    template,
                                    send_date,
                                    configuration_whatsapp_other_id,
                                    contacts_total,
                                    contact_sent,
                                    contacts_pending,
                                    state_description,
                                    state,
                                    users_id,
                                    user_fullname,
                                    user_username,
                                    config_identifier,
                                 } = element;

                                 // Crear una nueva fila de la tabla concatenando cadenas
                                 newRow +=
                                    "<tr>" +
                                    '<td class="centrar">' +
                                    send_date +
                                    "</td>" +
                                    '<td class="centrar">' +
                                    channel +
                                    "</td>" +
                                    '<td class="centrar">' +
                                    campaign +
                                    "</td>" +
                                    '<td class="centrar">' +
                                    config_identifier +
                                    "</td>" +
                                    '<td class="centrar">' +
                                    contacts_total +
                                    "</td>" +
                                    '<td class="centrar">' +
                                    contact_sent +
                                    "</td>" +
                                    '<td class="centrar">' +
                                    contacts_pending +
                                    "</td>" +
                                    '<td class="centrar">' +
                                    state_description +
                                    "</td>" +
                                    "</tr>";
                              });

                              // Agregar la nueva fila al tbody
                              $(".tbody_envios").html(newRow);
                           } else {
                              $(".tbody_envios").html(
                                 '<tr><th colspan="8" class="centrar pt-4"> No information</th></tr>',
                              );
                           }
                        }
                      */
                     } else {
                        alert("Error sending group messages");
                     }
                  } catch (error) {
                     $(".tbody_envios").html("");
                     alert("Error:" + error);
                  }
               },
               error: function (xhr, status, error) {
                  $("#consultar_filtros").prop("disabled", false);
                  $(".tbody_envios").html("");
                  console.error("Error en la solicitud:", error);
               },
            });
         });
 
         $('#staff').change(function() {
            var selectedValue = $(this).val();
            //console.log('Nuevo valor seleccionado:', selectedValue);
      
            // Puedes realizar acciones aquí
            //if (selectedValue) {
            //} else {
            //   //alert('Has seleccionado "All"');
            //}

            //if(selectedValue == "")
            //{
            //   selectedValue = "*";
            //}

            $('.cambiar_hipervinculo').each(function() {
               var estadoId = $(this).data('estado_id');

               var nuevoHref = ruta_pantalla + selectedValue + "/" + estadoId; 
               $(this).attr('href', nuevoHref);  // Cambiar el atributo href
            });

         });

 

         function cargar_fecha() {
            const today = new Date();

            // Formatear la fecha como YYYY-MM-DD
            const year = today.getFullYear();
            const month = String(today.getMonth() + 1).padStart(2, "0"); // Mes de 2 dígitos
            const day = String(today.getDate()).padStart(2, "0"); // Día de 2 dígitos

            const formattedDate = year + "-" + month + "-" + day;
            return formattedDate;
         }

         function select_html_usuario_sistema(arr) {
            if (arr.length == 0) {
               return;
            }

            var html = '<option value="">' + "None" + "</option>";

            arr.forEach((element) => {
               let value = element;

               html +=
                  '<option value="' +
                  value["id"] +
                  '">' +
                  value["fullname"] +
                  "</option>";
            });

            return html;
         }

         function isEmpty(value) {
            // Verificar si es null o undefined
            if (value == null) return true;

            // Verificar si es una cadena vacía
            if (typeof value === "string" && value.trim() === "") return true;

            // Verificar si es un array vacío
            if (Array.isArray(value) && value.length === 0) return true;

            // Verificar si es un objeto vacío
            if (typeof value === "object" && Object.keys(value).length === 0) return true;

            return false;
         }
     

</script>
{/block}