{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="{$id_user}"
            disabled
            hidden
            id="id_user"
      />

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

<div class="row">

    <div class="col-md-12">

       
        <div class="panel">
            <div class="panel-hdr">
                <h2 style="color: #666; font-weight: 600; "><span></span>General Form List</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-2">
                        
                        <div class="row contenedor" style="padding: 10px">


                           {* listado de customers *}
                           <div class="col-12 col-sm-12 pt-3">
                                <label for="customers"><span style="color:#666;">Customer</span> </label>
                                <select
                                    class="form-select form-control-sm tener_customers"
                                    name="customers"
                                    id="customers"
                                    style="width: 100%"
                                    placeholder="Select a state forms"
                                >
                                    <option value="">All</option>

                                    {foreach $listado_clientes as $ds}
                                       <option value="{$ds['id']}" data-email="{$ds['email']}" data-account="{$ds['account']}" >{$ds['account']}</option>
                                    {/foreach}
                                </select>
                           </div>

                           {* formulario *}
                            <div class="col-12 col-sm-12 pt-3">
                                <label for="category_form"><span style="color:#666;">Category Form</span> </label>
                                
                                <select
                                    class="form-select form-control-sm tener_category_form"
                                    name="category_form"
                                    id="category_form"
                                    style="width: 100%"
                                    placeholder="Select a Forms"
                                >
                                    <option value="" >All</option>
                                    {foreach $listado_formulario as $ds}
                                        <option value="{$ds['id']}" >{$ds['name']}</option>
                                    {/foreach}
                                </select>
                            </div>

                           {* listado de staff *}
                           <div class="col-12 col-sm-12 pt-3">
                                <label for="staff"><span style="color:#666;">Staff</span> </label>
                                <select
                                    class="form-select form-control-sm tener_staff"
                                    name="staff"
                                    id="staff"
                                    style="width: 100%"
                                    placeholder="Select a staff"
                                >
                                    <option value="">All</option>

                                    {foreach $listado_staff as $ds}
                                        <option value="{$ds['id']}" >{$ds['fullname']}</option>
                                    {/foreach}
                                </select>
                           </div>

                            {* fecha desde *}
                            <div class="col-12 col-sm-6 pt-3">
                                <label for="fecha_desde"
                                    ><span style="color:#666;">Date from</span>
                                </label>
                                <input
                                    type="date"
                                    id="fecha_desde"
                                    name="fecha_desde"
                                    class="form-control form-control-sm tener_fecha_desde"
                                />
                            </div>

                           {* fecha hasta *}
                           <div class="col-12 col-sm-6 pt-3">
                                <label for="fecha_hasta"
                                    ><span style="color:#666;">Date to date</span>
                                </label>
                                <input
                                    type="date"
                                    id="fecha_hasta"
                                    name="fecha_hasta"
                                    class="form-control form-control-sm tener_fecha_hasta"
                                />
                           </div>
 
 
                           <div class="col-12 col-sm-12 pt-3">
                                <button
                                    type="button"
                                    class="btn btn-sm btn-primary"
                                    id="consultar_filtros"
                                    style="
                                        border-color: #d3cac0;
                                        border: 1px solid #d3cac0;
                                        float: right;
                                    "
                                >
                                    Search for information

                                    <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 class="col-12 col-sm-12 pt-4">
                            
                            
                                <div class="table-responsive">
                                    <table class="table table-borderless mt-3"  id="clx_datatable">
                                        <thead>
                                        <tr>
                                            <th class="centrar">Staff</th>
                                            <th class="centrar">Forms</th>
                                            <th class="centrar">Total forms</th>
                                            <th class="centrar">Sent to the client</th>
                                            <th class="centrar">Received for review</th>
                                            <th class="centrar">IRS Sent</th>
                                            <th class="centrar">IRS Approved</th>
                                            <th class="centrar">IRS rejected</th>
                                        </tr>
                                        </thead>
                                        <tbody class="tbody_envios">
                                          {foreach $listado_formulario as $s}
                                              <tr>
                                                   <td class="centrar">{$s["nombre_usuario"]}</td>
                                                   <td class="centrar">{$s["nombre_categoria"]}</td>
                                                   <td class="centrar">{$s["total_formulario"]}</td>
                                                   <td class="centrar">{$s["enviados_al_cliente"]}</td>
                                                   <td class="centrar">{$s["recibidos_para_revision"]}</td>
                                                   <td class="centrar">{$s["enviados_a_irs"]}</td>
                                                   <td class="centrar">{$s["aprobados_por_irs"]}</td>
                                                   <td class="centrar">{$s["rechazados_por_irs"]}</td>
                                             </tr>
                                          {/foreach}
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                            </div>

                       
                    </div>

                  

                </div>
 
                
               
            </div>
        </div>
    </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();

   //tener_staff
   console.log($("#parametro_staff_id").val());
   $(".tener_staff").val($("#parametro_staff_id").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);

    //$('#clx_datatable').DataTable();
   /*  var wp_table = $("#clx_datatable").DataTable({
        dom: 
        "<'row mb-3'<'col-sm-12 col-md-6 d-flex align-items-center justify-content-start'f><'col-sm-12 col-md-6 d-flex align-items-center justify-content-end'lB>>" +
        "<'row'<'col-sm-12'tr>>" +
        "<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>",
        buttons: [
            {
                extend: 'pdfHtml5',
                text: 'PDF',
                titleAttr: 'Generate PDF',
                className: 'btn-danger-light btn-sm mr-1'
            },
            {
                extend: 'excelHtml5',
                text: 'Excel',
                titleAttr: 'Generate Excel',
                className: 'btn-success-light btn-sm mr-1'
            },
            {
                extend: 'csvHtml5',
                text: 'CSV',
                titleAttr: 'Generate CSV',
                className: 'btn-primary-light btn-sm mr-1'
            },
            {
                extend: 'copyHtml5',
                text: 'Copy',
                titleAttr: 'Copy to clipboard',
                className: 'btn-info-light btn-sm mr-1'
            },
            {
                extend: 'print',
                text: 'Print',
                titleAttr: 'Print Table',
                className: 'btn-secondary-light btn-sm'
            }
        ],
        language: {
            emptyTable: "No data available",
            info: "Mostrando _START_ a _END_ de _TOTAL_ entradas",
            infoEmpty: "Mostrando 0 a 0 de 0 entradas",
            buttons: {
                pageLength: "Mostrar todo"
            },
            searchPlaceholder: "Buscar"
        },
        
    }); */

    
         $("#consultar_filtros").click(function () {

            //tener_customers
            //tener_category_form
            //tener_staff

            //tener_fecha_desde
            //tener_fecha_hasta

            let tener_customers = $(".tener_customers").val() || "";
            let tener_category_form = $(".tener_category_form").val() || "";
            let tener_staff = $(".tener_staff").val() || "";
           
            let tener_fecha_desde   = $(".tener_fecha_desde").val() || "";
            let tener_fecha_hasta   = $(".tener_fecha_hasta").val() || "";

            if(isEmpty(tener_fecha_desde) == true)
            {
                toastr.error("!From date is required¡");
                return;
            }

            if(isEmpty(tener_fecha_hasta) == true)
            {
                toastr.error("!Date by is required¡");
                return;
            }

            let enviar_informacion = {
               fecha_desde: tener_fecha_desde,
               fecha_hasta: tener_fecha_hasta,

               customers:     tener_customers,
               category_form: tener_category_form,
               staff:         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-general-formularios",
               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="8" 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);
               },
            });
         });
 
         async function cargar_cabecera_account() {
            return new Promise((resolve, reject) => {
               $.get(
                  URL_BASE + "group/get-groups-account-headers/",
                  function (data) {
                     try {
                        let info = JSON.parse(data);
                        resolve(info.data);
                     } catch (error) {
                        console.log(
                           "Error al parsear la respuesta cargar_cabecera_account: " +
                              error.message,
                        );
                        reject({
                           type: "error",
                           data: {},
                        });
                     }
                  },
               ).fail(function (jqXHR, textStatus, errorThrown) {
                  console.log(
                     "Error en la solicitud cargar_cabecera_account: " +
                        textStatus +
                        " - " +
                        errorThrown,
                  );
                  reject({
                     type: "error",
                     data: {},
                  });
               });
            });
         }

         async function cargar_grupos() {
            return new Promise((resolve, reject) => {
               $.get(URL_BASE + "group/get-groups/", function (data) {
                  try {
                     let info = JSON.parse(data);
                     resolve(info.data);
                  } catch (error) {
                     console.log(
                        "Error al parsear la respuesta cargar_grupos: " +
                           error.message,
                     );
                     reject({
                        type: "error",
                        data: {},
                     });
                  }
               }).fail(function (jqXHR, textStatus, errorThrown) {
                  console.log(
                     "Error en la solicitud cargar_grupos: " +
                        textStatus +
                        " - " +
                        errorThrown,
                  );
                  reject({
                     type: "error",
                     data: {},
                  });
               });
            });
         }

         async function cargar_usuarios_sistema() {
            return new Promise((resolve, reject) => {
               $.get(
                  URL_BASE + "social/lista-usuarios-admin/",
                  function (data) {
                     try {
                        let info = JSON.parse(data);
                        resolve(info.data);
                     } catch (error) {
                        console.log(
                           "Error al parsear la respuesta cargar_grupos: " +
                              error.message,
                        );
                        reject({
                           type: "error",
                           data: {},
                        });
                     }
                  },
               ).fail(function (jqXHR, textStatus, errorThrown) {
                  console.log(
                     "Error en la solicitud cargar_grupos: " +
                        textStatus +
                        " - " +
                        errorThrown,
                  );
                  reject({
                     type: "error",
                     data: {},
                  });
               });
            });
         }

         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}