{extends file="$layouts_admin"}

{block name="content"}
    <div class="row">

        <input type="text" hidden disabled name="url_api" id="url_api" value="{$_url}">

        {* fecha *}
        <div class="col-lg-12 mb-3">
                <input type="text" name="reportrange" class="form-control" id="reportrange" style="
                                                                                                display: inline-block;
                                                                                                width: 40%;
                                                                                                float: inline-end;
                                                                                                text-align: center;
                                                                                                ">
                <button class="btn btn-sm btn-primary buscarFecha">
                    Search date
                    <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>

                <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> 
        {* fin fecha *}

        {if $user->roleid == "3"}
        <div class="col-lg-12">
            <div id="panel-3" class="panel border-0" data-panel-close="false">
                <div class="panel-hdr">
                    <h2 class="fw-bolder">Invoice of the week (Range): <span class="fecha_seleccionada">{$date_start} / {$date_end}</span></h2>

                </div>
                <div class="panel-container show p-3">

                <input type="text" hidden disabled class="tener_fecha_desde" value="{$date_start}" >
                <input type="text" hidden disabled class="tener_fecha_hasta" value="{$date_end}" >

                    <div class="table-responsive  widget-table">
                        <table class="table">
                            <thead class="thead-light">
                                <tr>
                                    <th class="h6">#</th>
                                    <th class="h6">{$_L['Account']}</th>
                                    <th class="h6">{$_L['Amount']}</th>
                                    <th class="h6">{$_L['Title']}</th>
                                    <th class="h6">{$_L['Invoice Date']}</th>
                                    <th class="h6">{$_L['Due Date']}</th>
                                    <th class="h6">{$_L['Status']}</th>
                                </tr>
                            </thead>
                            {$total=0}
                            <tbody class="invoices_tabla">

                                {foreach $invoices as $ds}

                                {$total=$ds['credit'] + $total}
                                {$mon=$ds['currency_iso_code']}

                                

                                <tr class="cursor-pointer clickable-row" data-id="{$ds['id']}">
                                    <td class="text-info h6">
                                        <a href="{$_url}invoices/view/{$ds['id']}/" class="text-info"> 
                                            <strong>
                                                {$ds['invoicenum']}{if $ds['cn'] neq ''} {$ds['cn']} {else} {$ds['id']} {/if}
                                            </strong>
                                        </a> 
                                    </td>

                                    <td class="h6">
                                        <strong>{$ds['account']}</strong> <br>
                                    </td>

                                    <td class="h6">{formatCurrency($ds['credit'],$ds['currency_iso_code'])}</td>

                                    <td class="h6">
                                        <strong>{$ds['title']}</strong>  
                                    </td>

                                    <td class="h6">

                                        {if !empty($ds['date'])}
                                        {date( $config['df'], strtotime($ds['date']))}
                                        {else}
                                        --
                                        {/if}


                                    </td>

                                    <td class="h6">

                                        {if !empty($ds['duedate'])}
                                        {date( $config['df'], strtotime($ds['duedate']))}
                                        {else}
                                        --
                                        {/if}

                                    </td>
                                    
                                    <td class="h6">
                                        {if $ds['status'] == 'Unpaid'}

                                        <span class="badge badge-outline badge-outline-danger">{ib_lan_get_line($ds['status'])}</span>

                                        {else}

                                        <span class="badge badge-outline  badge-outline-success">{ib_lan_get_line($ds['status'])}</span>

                                        {/if}


                                    </td>

                                </tr>
                                {/foreach}
                            </tbody>
                            <tfoot>
                                <tr>
                                <th></th>
                                <th></th>  

                                <th colspan="5" class="h6 total_invoices_tabla" style="text-align: left;">{formatCurrency($total,$mon)}</th>
                            </tr>
                        </tfoot>
                    </table>

                </div>

                <div class="panel-content">
                    <div id="invoice_stats"></div>
                </div>

            </div>


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


    <div class="col-lg-12">
        <div id="panel-11" class="panel border-0">
            <div class="panel-hdr">
                <h2 class="fw-bolder">
                    Appointments
                </h2>
            </div>
            <div class="panel-container show p-5">
                <div id="calendar"></div>
            </div>
        </div>
    </div>


   <!-- <div class="col-md-6">
        <div class="panel" id="panel-7">
            <div class="panel-hdr">
                <h2 class="fw-bolder">Sales</h2>
            </div>
            <div class="panel-container">
                <div class="panel-content">
                    <div class="ibox-content borrar_sales_grafica">

                        <div id="sales_pie_graph"></div>

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

</div>
{/block}

{block name="script"}

<script type="text/javascript">

        var options = {
            series: [
                {foreach $item_sold as $sold}
                {$sold['sold_count']},
                {/foreach}
            ],
            chart: {
                height: 350,
                type: 'radialBar',
                {if !empty($config['admin_dark_theme'])}
                foreColor: '#fff',
                colors: ["#4586DB", "#C23C3E"],
                {else}
                colors: ["#7E5FF4", "#FB8141"],
                {/if}


            },
            plotOptions: {
                radialBar: {
                    dataLabels: {
                        name: {
                            fontSize: '22px',
                        },
                        value: {
                            fontSize: '16px',
                        },
                        total: {
                            show: true,
                            label: '{$_L['Total']}',
                            formatter: function (w) {
                                // By default this function returns the average of all series. The below is just an example to show the use of custom formatter function
                                return {count($item_sold)}
                            }
                        }
                    }
                }
            },
            labels: [
                {foreach $item_sold as $sold}
                '{strTrunc(addslashes($sold['name']),30)}',
                {/foreach}
            ],
            {if !empty($config['admin_dark_theme'])}
            background: '#000',
            {/if}
        } 
   
        //var chart = new ApexCharts(document.querySelector("#sales_pie_graph"), options);
        //chart.render();

        /* var start = moment().subtract(29, 'days');
        var end = moment(); */

        var startDate = moment($(".tener_fecha_desde").val(), 'YYYY-MM-DD');
        var endDate = moment($(".tener_fecha_hasta").val(), 'YYYY-MM-DD');

        function cb(start, end) {
            $('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
            startDate = start;
            endDate = end;
        }

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

        $reportrange.daterangepicker({
            startDate: startDate, // aqui podemos poner la variable start
            endDate: endDate, // aqui podemos poner la variable end
            ranges: {
                '{__('Today')}': [moment(), moment()],
                '{__('Yesterday')}': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                '{__('Last 7 Days')}': [moment().subtract(6, 'days'), moment()],
                '{__('Last 30 Days')}': [moment().subtract(29, 'days'), moment()],
                '{__('This Month')}': [moment().startOf('month'), moment().endOf('month')],
                '{__('Last Month')}': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
            },
            locale: {
                format: 'YYYY/MM/DD'
            }
        }, cb);

        cb(startDate, endDate);
        
        function strTrunc(str, length) {
            return str.length > length ? str.substring(0, length) + '...' : str;
        }

        $('.buscarFecha').on('click', function() {
                //alert('Fechas seleccionadas: ' + startDate.format('YYYY-MM-DD') + ' - ' + endDate.format('YYYY-MM-DD'));
                 let informacion = {                 
                    startDate: startDate.format('YYYY-MM-DD'),
                    endDate:   endDate.format('YYYY-MM-DD'),
                };

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


                const jsonString = JSON.stringify(informacion);

                /* console.log(jsonString);
                return;  */
                 
                var _url = $("#url_api").val();
                $.post(_url + 'dashboard/filtro-fecha-cliente/', jsonString, function (data) {

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

                    //console.log(data);
                    /* console.log(data);
                    return; */

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

                            if (info.item_sold_circular && Array.isArray(info.item_sold_circular)) {

                                if(info.item_sold_circular.length == 0)
                                {
                                    $(".borrar_sales_grafica").html("<div id='sales_pie_graph'></div>");
                                }else{
                                    const names = info.item_sold_circular.map(item => item.name);
                                    const soldCounts = info.item_sold_circular.map(item => item.sold_count);

                                    var options = {
                                        series: soldCounts,
                                        chart: {
                                            height: 350,
                                            type: 'radialBar',
                                            {if !empty($config['admin_dark_theme'])}
                                            foreColor: '#fff',
                                            colors: ["#4586DB", "#C23C3E"],
                                            {else}
                                            colors: ["#7E5FF4", "#FB8141"],
                                            {/if}


                                        },
                                        plotOptions: {
                                            radialBar: {
                                                dataLabels: {
                                                    name: {
                                                        fontSize: '22px',
                                                    },
                                                    value: {
                                                        fontSize: '16px',
                                                    },
                                                    total: {
                                                        show: true,
                                                        label: '{$_L['Total']}',
                                                        formatter: function (w) {
                                                            // By default this function returns the average of all series. The below is just an example to show the use of custom formatter function
                                                            return info.item_sold_circular.length
                                                        }
                                                    }
                                                }
                                            }
                                        },
                                        labels: names,
                                        {if !empty($config['admin_dark_theme'])}
                                        background: '#000',
                                        {/if}
                                    } 

                                    
                                    //var chart = new ApexCharts(document.querySelector("#sales_pie_graph"), options);
                                    //chart.render(); 
                                }

                                 
                            }

                            //console.log(info.recent_customers); 
                            $('.invoices_tabla').html(info.invoices_html); 
                            $('.total_invoices_tabla').html(info.total_invoices); 

                            let fecha = startDate.format('YYYY-MM-DD');
                            let fecha_hasta = endDate.format('YYYY-MM-DD');
                           
                            $(".fecha_seleccionada").html(fecha+" / "+fecha_hasta);

           
                        }else{
                            toastr.error(info.message);
                        }
                    } catch (error) {
                        toastr.error(data);
                    }
                    
                });
        });

        function displayEvent(event_id=0,date=0)
        {
            $.fancybox.open({
                src  :  base_url + 'dashboard/modal-calendar/'+event_id+'/'+date,
                type : 'ajax',
                opts : {
                    afterShow : function( instance, current ) {
                        // $('[data-toggle="datepicker"]').datepicker();
                        // $start_time.timepicker();
                        // $end_time.timepicker();

                        $('#start').datepicker();
                        $('#start_time').timepicker();
                        $('#end').datepicker();

                        let eventForm = $('#eventForm');
                        eventForm.on('submit',function (e) {
                            e.preventDefault();
                            $.post( base_url + "calendar/save_event/", eventForm.serialize())
                                .done(function( data ) {



                                    if ($.isNumeric(data)) {

                                        location.reload();

                                    }

                                    else {
                                        toastr.error(data);
                                    }

                                });


                            return false;
                        });

                    }
                },
            });
        }

        $(function () {

            var calendarEl = document.getElementById('calendar');

            var calendar = new FullCalendar.Calendar(calendarEl,
                {
                    plugins: ['dayGrid', 'list', 'timeGrid', 'interaction', 'bootstrap'],
                    themeSystem: 'bootstrap',
                    timeZone: 'UTC',
                    //dateAlignment: "month", //week, month
                    buttonText:
                        {
                            today: 'today',
                            month: 'month',
                            week: 'week',
                            day: 'day',
                            list: 'list'
                        },
                    eventTimeFormat:
                        {
                            hour: 'numeric',
                            minute: '2-digit',
                            meridiem: 'short'
                        },
                    navLinks: false,
                    header:
                        {
                            left: 'title',
                            center: '',
                            right: 'today prev,next'
                        },
                    footer:
                        {
                            left: 'dayGridMonth,timeGridWeek,timeGridDay,listWeek',
                            center: '',
                            right: ''
                        },
                    editable: true,
                    eventLimit: true, // allow "more" link when too many events
                    eventSources: [{
                        url: base_url + 'dashboard/data-calendar/',
                        type: 'GET',
                        error: function() {

                        }
                    } ],
                    viewSkeletonRender: function()
                    {
                        $('.fc-toolbar .btn-default').addClass('btn-sm');
                        $('.fc-header-toolbar h2').addClass('fs-md');
                        $('#calendar').addClass('fc-reset-order')
                    },

                    dateClick: function(info) {
                        displayEvent(0,info.dateStr);
                    },
                    eventClick: function(info) {
                        displayEvent(info.event.id);
                    }


                });

            calendar.render();
        });

</script>
{/block}
