{extends file="$layouts_admin"}

<style>


 

.scroll-wrapper {
    overflow-x: auto;
    width: 100%;
    /* display: flex;
    justify-content: center; */
}

.scroll-top {
    display: flex;
    flex-wrap: nowrap;
    width: auto;
}

.contenido_leads {
    display: flex;
    flex-wrap: nowrap;
    width: 100%;
     
}

.tamano_leads {
    flex: 0 0 auto;
    white-space: nowrap;
    margin-right: 16px;
    min-width: 350px;
    /* max-width: calc(100% / 4);
    width: calc(100% / 4); */
}

.tamano_leads:last-child {
    margin-right: 0;
}

 


</style>

{block name="content"}


<style>


.scroll-wrapper {
    overflow-x: auto;
    width: 100%;
    /* display: flex;
    justify-content: center; */
}

.scroll-top {
    display: flex;
    flex-wrap: nowrap;
    width: auto;
}

.contenido_leads {
    display: flex;
    flex-wrap: nowrap;
    width:100%;
}

.tamano_leads {
    flex: 0 0 auto;
    white-space: nowrap;
    margin-right: 16px;
    min-width: 350px;
    /* max-width: calc(100% / 4);
    width: calc(100% / 4); */
}

.tamano_leads:last-child {
    margin-right: 0;
}

.style_texto {
    font-weight: 600; 
    margin: 0px; 
    text-align: center;
}

.style_box_caja {
    background-color: white;
    padding: 10px;
    border-radius: 5px;
    box-shadow: rgba(0, 0, 0, 0.16) 0px 3px 6px, rgba(0, 0, 0, 0.23) 0px 3px 6px;
    overflow-x: auto;
    margin-bottom: 20px;
}

.style_response_text {
    font-size: smaller;
}

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

<div class="row cargando_pantalla " style=" margin: 0px; ">

   <div
      class="container"
      style="
         display: flex;
         justify-content: center;
         align-items: center;
         height: 45vh;
         box-shadow: 0 0 13px 0 rgba(31,17,173,.08);
         border-radius: 11px;
         background-color: white;
      "
   >
      <div style="text-align: center">
         <span
         class="spinner-border spinner-border-sm"
         style="height: 45px; width: 45px; margin-bottom: 10px"
         role="status"
         aria-hidden="true"
         ></span>
         <br />
         <strong>Please wait while the information loads....</strong>
         <br />
      </div>
   </div>

</div>

<div class="subheader pantalla_cargada" style="display: none;">
    <h1 class="subheader-title">
         Ticket Report <span class='fw-300'></span>
    </h1>
    <div class="subheader-block d-lg-flex align-items-center">
        <a href="{$url_new_ticket}" class="btn btn-primary   waves-effect waves-light"><i class="fal fa-plus"></i> New Tickets</a>
    </div>

</div>

<div class="row pantalla_cargada" style="display: none;">
 
 
    <div class="col-md-12">
        <div class="panel" style="
                                background-color: transparent;
                                box-shadow: none;
                                border: none;
                            ">
            <div class="panel-container show">
                <div class="panel-content">

 
                    <div class="row">
                          
                       {* {if $usuario_roll != "3" } *}
                       {*
                            <div class="col-md-12 col-sm-12 col-12 mb-4">

                                <div class="card">
                                    <div class="card-header" style="
                                                                display: flex;
                                                                justify-content: space-between;
                                                            ">
                                        <h3 style="display: inline-block;">Filter</h3>

                                        <div>
                                            <a class="btn btn-success btn-sm" target="_blank" href="{$url_download}">Download All Leads</a>       
                                            <button class="btn btn-primary btn-sm filtrar_info" type="button">Search</button>

                                            <button class="btn btn-sm btn-primary buscarFechaCargando" style="display: none;" disabled>
                                                Loading...
                                                <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>

      
                                    </div>
                                    <div class="card-body">
                                        <div class="container row p-0">
                                      
                                            <div class="col-md-6">
                                                <label for="filter_services">Services</label>
                                                <select class="form-select tenes_servicio_id" id="filter_services" name="filter_services">
                                                    <option value="">Selected</option>
                                                    {foreach $services as $s}
                                                        <option value="{$s['id']}" {if $s['is_default'] eq '1'}selected{/if}>{$s['name']}</option>
                                                    {/foreach}
                                                </select>
                                            </div>
                                           

                                          
                                            <div class="col-md-6">
                                                <label for="filter_users">Users</label>
                                                <select class="form-select tener_filter_users" id="filter_users" name="filter_users">
                                                    <option value="">Selected</option>
                                                    {foreach $usuarios as $s}
                                                    <option value="{$s['id']}"  >{$s['fullname']}</option>
                                                    {/foreach}
                                                </select>
                                            </div>
                                        
                                            <div class="col-md-6 mt-3">
                                                <label for="first_name">First Name</label>
                                                <input type="text" id="first_name" name="first_name" class="form-control tener_first_name" >
                                            </div>
                                        
                                          
                                            <div class="col-md-6 mt-3">
                                                <label for="last_name">Last Name</label>
                                                <input type="text" id="last_name" name="last_name" class="form-control tener_last_name" >
                                            </div>
                                           
                                        </div>
                                    </div>
                                </div>

                               
                            </div>
                        *}
                       {*  {/if}*}

 
                       <div class="col-12 mb-3" style="display: flex; justify-content: space-between;">
                          <a class="btn btn-primary btnIzquierda waves-effect waves-light" ><i class="fal fa-chevron-left"></i></a>                      
                          <a class="btn btn-primary btnDerecha waves-effect waves-light" ><i class="fal fa-chevron-right"></i></a>                      
                       </div>

                       <br>
                        <div class="row container-fluid text-center" style="
                                                    display: flex;
                                                    justify-content: center;
                                                    margin: auto;
                                                    padding:0px
                                                ">
                                                  
                            <div class="scroll-wrapper">
                                <div class="scroll-top">
                                    <div class="contenido_leads">

                                        {* plantilla *}

                                        <div class="tamano_leads">
                                            <h4 class="text-center">Leads New</h4>
                                            <hr>

                                            <div class="leads_html">
                                                {foreach $leads_course as $s}
                                                    <div style="
                                                            background-color: white;
                                                            padding: 5px;
                                                            border-radius: 5px;
                                                            box-shadow: 0 0 13px 0 rgba(31,17,173,.08);
                                                            overflow-x:auto;
                                                            margin-bottom:20px;
                                                        "> 
                                                    {if empty($s["title"]) == false }
                                                        <p style="font-weight:600; margin:0px; text-align:center">{$s["title"]}</p>    
                                                    {/if}
                                                    
                                                    <p style="font-weight:600; margin:0px; text-align:center">{$s["nombre_servicio"]}</p>    
                                                    <p style="font-weight:600; margin:0px; text-align:center">{$s["company"]}</p>  
                                                    <p style="font-weight:600; margin:0px; text-align:center">Created Date: {date("d/m/Y", strtotime($s["created_at"]))}</p>    
                                                    <hr>
                                                    <p style="font-weight:600; margin:0px; text-align:center">Owner: {$s["o"]}</p>    
                                                    <p style="font-weight:600; margin:0px; text-align:center">Assigned: 
                                                        {if !empty($s["nombre_usuario_asignado"]) && $s["id_admin"] != 0}
                                                            {$s["nombre_usuario_asignado"]}
                                                        {else}
                                                            unassigned
                                                        {/if}
                                                    </p>    
                                                    <p style="font-weight:600; margin:0px; text-align:center">Name: 
                                                        {if !empty($s["salutation"])}
                                                            {$s["salutation"]}
                                                        {else}
                                                            Mr.
                                                        {/if}

                                                        {if !empty($s["first_name"])}
                                                            {$s["first_name"]}
                                                        {/if}

                                                        

                                                        {if !empty($s["last_name"])}
                                                            {$s["last_name"]}
                                                        {/if}
                                                    </p>  
                                                    {if empty($s["email"]) == false }
                                                        <p style="font-weight:600; margin:0px; text-align:center">Email: {$s["email"]}</p>    
                                                    {/if}
                                                    {if empty($s["phone"]) == false }
                                                        <p style="font-weight:600; margin:0px; text-align:center">Phone: {$s["phone"]}</p>    
                                                    {/if}
                                                    
                                                    <br>
                                                    <div class="container btn-group text-center">

                                                    <a href="#" class="btn btn-dark btn-xs chistoryLead" data-id="{$s['id']}" id="{$s['id']}"><i class="fal fa-eye"></i> </a>
                                                    <a href="#" class="btn btn-primary btn-xs cview"     data-id="vid{$s['id']}" id="vid{$s['id']}"><i class="fal fa-search"></i> </a>
                                                    <a href="#" class="btn btn-warning btn-xs cedit"     data-id="eid{$s['id']}" id="eid{$s['id']}"><i class="fal fa-pencil"></i> </a>
                                                    <a href="#" class="btn btn-danger btn-xs cdelete"    data-id="did{$s['id']}" id="did{$s['id']}"><i class="fal fa-trash-alt"></i> </a>
                                                    </div>
                                                    </div>
                                                {/foreach}
                                            </div>

                                            <div class="leads_html_count">
                                                {if count($leads_course) == 0 }
                                                    <p style="font-weight:600; margin:0px; text-align:center">No Information</p>
                                                {/if}
                                            </div>
                                        </div>

                                        {* plantilla *}
 
                                    </div>
                                </div>
                            </div>
                        </div>
                         
   
                    </div>



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

</div>


{/block}

 
{block name="script"}

{literal}
<script>

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

    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;
   }

    $(document).ready(function () {

        cargarPrincipal();

        function cargarPrincipal()
        {
           
            $.ajax({
                type: "POST",
                url: URL_BASE + "tickets/admin/get-list-report-tickets",
                //data: JSON.stringify(data),
                contentType: "application/json", // Tipo de contenido JSON
                success: function (response) {
                    
                    //console.log("Respuesta del servidor:", response);
                    // Hacer algo con la respuesta del servidor
        
                    try {
                        let info = JSON.parse(response);

                        if (info.type == "success") {

                            let list_status_tickets = info.list_status_tickets || [];
                            let list_items_tickets  = info.list_items_tickets || [];

                            let createHtml = "";

                            list_status_tickets.forEach((data) => {

                                let {
                                    id,
                                    name,
                                    number_days,
                                    descriptions,
                                    show_services,
                                    is_can_delete,
                                    active,
                                } = data;

                                let filterDataItems = list_items_tickets.filter((lvl) => lvl.status_id == id  ) || [];
 
                                let html = "";
                                filterDataItems.forEach((data_lvl1) => {

                                    html += generarTicketHTML(data_lvl1);

                                });

                                let html_existeDataItem = "";

                                if(filterDataItems.length == 0)
                                {
                                    html_existeDataItem = '<p style="font-weight:600; margin:0px; text-align:center">No Information</p>';
                                }

                                //console.log("filterDataItems");
                                //console.log(filterDataItems);

                                createHtml += generateHtmlStatus(name, html, html_existeDataItem);

                            });

                            $(".contenido_leads").html(createHtml);

                            $(".cargando_pantalla").css("display", "none");
                            $(".pantalla_cargada").css("display", "");
                            
                        } else if (info.type == "error") {
                            Swal.fire({
                               icon: "error",
                               title: "Oops...",
                               text: info.message,
                            });
                        }

                    } catch (error) {
                        Swal.fire({
                           icon: "error",
                           title: "Oops...",
                           text: error,
                        });
                    }
                },
                error: function (xhr, status, error) {
                    console.error("Error en la solicitud:", error);
                    // Manejar errores aquí
                    Swal.fire({
                       icon: "error",
                       title: "Oops...",
                       text: error,
                    });
                },
            });

            
        }


    });


    function generateHtmlStatus(titulo, contenidoHTML, conteo) {

        return `
        <div class="tamano_leads">
            <h4 class="text-center">${titulo}</h4>
            <hr />

            <div class="leads_html">
                ${contenidoHTML}
            </div>

            <div class="leads_html_count">
                ${conteo}
            </div>
        </div>
        ` ;
    }

    function generarTicketHTML(datos) {

        let {
            id,
            tid,
            did,
            aid,
            aname_staff_assigned,
            email_client,
            phone_client,
            contact_client,
            dname,
            userid,
            account,
            created_at,
            subject,
            message,
            urgency,
            created_origin,
            opening_date,
            support_start_date,
            closing_date,
            expected_closing_date,
            UUID,
        } = datos;

        let linkVer = URL_BASE + "tickets/admin/view/" + UUID;

        let created_origin_descripcion = "";

        if(created_origin == 1)
        {
            created_origin_descripcion = "Created from CRM Administrator";
        }else{
            created_origin_descripcion = "Created from CRM Client";
        }

        if(isEmpty(aname_staff_assigned))
        {
            aname_staff_assigned = " -- ";
        }

        if(isEmpty(email_client))
        {
            email_client = " -- ";
        }

        if(isEmpty(phone_client))
        {
            phone_client = " -- ";
        }

        if(isEmpty(contact_client))
        {
            contact_client = " -- ";
        }

        if(isEmpty(dname))
        {
            dname = " -- ";
        }
 
        if(isEmpty(account))
        {
            account = " -- ";
        }

        if(isEmpty(subject))
        {
            subject = " -- ";
        }

        if(isEmpty(message))
        {
            message = " -- ";
        }

        if(isEmpty(urgency))
        {
            urgency = " -- ";
        }

        if(isEmpty(created_origin))
        {
            created_origin = " -- ";
        }

        if(isEmpty(opening_date))
        {
            opening_date = " -- ";
        }

        if(isEmpty(support_start_date))
        {
            support_start_date = " -- ";
        }

        if(isEmpty(closing_date))
        {
            closing_date = " -- ";
        }

        if(isEmpty(expected_closing_date))
        {
            expected_closing_date = " -- ";
        }

        return `
            <div class="style_box_caja">
                <p class="style_texto">Number Ticket: <strong class="style_response_text">${tid}</strong></p>
                <p class="style_texto">Clients: <strong class="style_response_text">${account}</strong></p>
                <p class="style_texto">Department: <strong class="style_response_text">${dname}</strong></p>
                <p class="style_texto">Priority: <strong class="style_response_text">${urgency}</strong></p>
                <p class="style_texto">Email: <strong class="style_response_text">${email_client}</strong></p>
                <p class="style_texto">Phone: <strong class="style_response_text">${phone_client}</strong></p>
                <p class="style_texto">Created Date: <strong class="style_response_text">${created_at}</strong></p>
                <p class="style_texto">Subject: <strong class="style_response_text">${subject}</strong></p>
                <p class="style_texto">Assigned: <strong class="style_response_text">${aname_staff_assigned}</strong></p>
                <p class="style_texto">Opening date: <strong class="style_response_text">${opening_date}</strong></p>
                <p class="style_texto">Support start date: <strong class="style_response_text">${support_start_date}</strong></p>
                <p class="style_texto">Closing date: <strong class="style_response_text">${closing_date}</strong></p>
                <p class="style_texto">Origin of creation: <strong class="style_response_text">${created_origin_descripcion}</strong></p>

                <br />
                <div class="container btn-group text-center">
                    <a
                        href="${linkVer}"
                        class="btn btn-primary btn-xs waves-effect waves-themed"
                    >
                        <i class="fal fa-search"></i>
                    </a>
                </div>
            </div>
        `;
    }


    $(function() {

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

        var $ib_data_panel = $("#ib_data_panel");

        //$ib_data_panel.block({ message:block_msg });


        var $modal = $('#cloudonex_body');

        $('[data-bs-toggle="tooltip"]').tooltip();

        var $ib_filter = $("#ib_filter");

        $('.add_item').on('click', function(e){

            e.preventDefault();

            $.fancybox.open({
                src  :  base_url + 'leads/modal_lead/new/',
                touch: false,
                type : 'ajax',
                opts : {
                    afterShow : function( instance, current ) {

                    }
                },
            });

        });

        $('.btnIzquierda').on('click', function(e){
            e.preventDefault();
            const container = $('.scroll-wrapper');
            const currentPosition = container.scrollLeft();
            container.animate({ scrollLeft: currentPosition - 350 }, 'slow');
        
        });

        $('.btnDerecha').on('click', function(e){
            e.preventDefault();
             const container = $('.scroll-wrapper');
             const currentPosition = container.scrollLeft();
             container.animate({ scrollLeft: currentPosition + 350 }, 'slow');
        
        });

 
        $ib_filter.on('click', function(e) {
            e.preventDefault();

            //$ib_data_panel.block({ message:block_msg });

            /* ib_dt.ajax.reload(
                function () {
                    $ib_data_panel.unblock();
                }
                ); */


        });


        $('.filtrar_info').on('click', function(event) {
            event.preventDefault();
            
            let info = {
                servicio_id:$(".tenes_servicio_id").val(),
                usuario_id: $(".tener_filter_users").val(),
                first_name: $(".tener_first_name").val(),
                last_name: $(".tener_last_name").val(),
            }
 
            $(".buscarFechaCargando").show();
            $(".filtrar_info").hide();

            $.post( base_url + "leads/filtro-leands-post/", JSON.stringify(info) )
            .done(function( data ) {
                
                //console.log(data);

                $(".buscarFechaCargando").hide();
                $(".filtrar_info").show();

                try {
                    const info = JSON.parse(data);
                      
                   if(info.type == "success")
                   {

                        $(".leads_html").html(info.leads_course);
 
                        if(info.leads_course == "")
                        {
                            $(".leads_html_count").html("<p style='font-weight:600; margin:0px; text-align:center'>No Information</p>");
                        }else{
                            $(".leads_html_count").html("");
                        }

                        $(".leads_discarded_html").html(info.leads_discarded);

                        if(info.leads_discarded == "")
                        {
                            $(".leads_discarded_html_count").html("<p style='font-weight:600; margin:0px; text-align:center'>No Information</p>");
                        }else{
                            $(".leads_discarded_html_count").html("");
                        }

                        $(".leads_process_html").html(info.leads_in_process);

                        if(info.leads_in_process == "")
                        {
                            $(".leads_process_html_count").html("<p style='font-weight:600; margin:0px; text-align:center'>No Information</p>");
                        }else{
                            $(".leads_process_html_count").html("");
                        }

                        $(".leads_qualified_html").html(info.leads_in_qualified);

                        if(info.leads_in_qualified == "")
                        {
                            $(".leads_qualified_html_count").html("<p style='font-weight:600; margin:0px; text-align:center'>No Information</p>");
                        }else{
                            $(".leads_qualified_html_count").html("");
                        }

                         

                        $('.chistoryLead').on('click', function(event) {
                            event.preventDefault();
                            var id = $(this).data('id');
                            //console.log('chistoryLead ID:', id);
                            var lid = id;
                            let link = _url+"leads/lead-history/"+lid;
                            //console.log(link);
                            window.location.href = link;
                        });

                        $('.cview').on('click', function(event) {
                            event.preventDefault();
                            var id = $(this).data('id');
                            //console.log('cview ID:', id);
                            var lid = id;

                            $.fancybox.open({
                                src  :  base_url + 'leads/modal_lead/view/'+lid,
                                type : 'ajax',
                                opts : {
                                    afterShow : function( instance, current ) {

                                    }
                                },
                            });
                        });

                        $('.cedit').on('click', function(event) {
                            event.preventDefault();
                            var id = $(this).data('id');
                            //console.log('cedit ID:', id);
                            var lid = id;

                            $.fancybox.open({
                                src  :  base_url + 'leads/modal_lead/edit/'+lid,
                                type : 'ajax',
                                opts : {
                                    afterShow : function( instance, current ) {

                                    }
                                },
                            });
                        });

                        $('.cdelete').on('click', function(event) {
                            event.preventDefault();
                            var id = $(this).data('id');
                            //console.log('cedit ID:', id);
                            var lid = id;

                            app.confirm(_L['are_you_sure'], function(result) {
                                if(result){

                                    $.get( base_url + "delete/lead/"+lid, function( data ) {
                                        //$ib_data_panel.block({ message:block_msg });

                                        location.reload();
                                    });


                                }
                            });
                        });
                      
                   }else{
                        
                       toastr.error(info.mensaje);
                   }

                } catch (error) {
                    toastr.error(data);
                }

            });

        });
 
 
    });
</script>
{/literal}

{/block}
