@extends('layouts.app')
@section('meta')

@endsection
@section('title',config('app.name') . ' | ' . 'Dashboard')
@section('css_specific')
    <link href="{{ asset('gentelella/plugins/bootstrap-daterangepicker/daterangepicker.css') }}" rel="stylesheet"/>
    <link href="{{ asset('gentelella/plugins/google-code-prettify/bin/prettify.min.css') }}" rel="stylesheet"/>
@endsection
@section('css')

@endsection


@section('content')
    <!-- page content -->
    <div class="right_col" role="main">
        <div class="">

            <div class="clearfix"></div>

            <!-- Mensajes -->
            <div id="general_messages">
                @include('flash::message')
            </div>
            <!-- /Mensajes -->
            @if (\Auth::user()->sysCustomer)
            <div class="row top_tiles" style="margin: 20px 0 2px 0;">
                @if(empty(setting('disabled_folio_cart')))
                <div class="col-md-3 col-xs-12 tile text-center">
                    <a href="{{route('folios.index')}}" class="">
                        <strong>@lang('general.text_cfdi_availables')</strong>
                        @if(\App\Helpers\BaseHelper::getAvailableFolios()>10000)
                            <br/><img src="{{asset('img/infinity-128.png')}}" width="35px"/>
                        @else
                            <h2>{{\App\Helpers\BaseHelper::getAvailableFolios()}}</h2>
                        @endif
                    </a>
                </div>
                @endif
                <div class="col-md-3 col-xs-12 {{ !empty(setting('disabled_folio_cart')) ? 'col-md-offset-3' : '' }} tile text-center">
                    <a href="{{route('customers.index')}}" class="">
                        <strong>@lang('general.text_customers')</strong>
                        <h2>{{\App\Helpers\Helper::numberFormat(\App\Models\Sales\Customer::active()->count())}}</h2>
                    </a>
                </div>
                <div class="col-md-3 col-xs-12 tile text-center">
                    <a href="{{route('products.index')}}" class="">
                        <strong>@lang('general.text_products')</strong>
                        <h2>{{\App\Helpers\Helper::numberFormat(\App\Models\Catalogs\Product::active()->count())}}</h2>
                    </a>
                </div>
                @if(empty(setting('disabled_folio_cart')))
                <div class="col-md-3 col-xs-12 tile text-center">
                    <a href="{{route('shop')}}" class="btn btn-success">
                        <i class="fa fa-shopping-cart" style="font-size: 2.7rem;"></i><br/>
                        <span>@lang('general.button_buy_folios')</span>
                    </a>
                </div>
                @endif
            </div>
            @elseif(Auth::user()->superadmin || Auth::user()->distributor)
                <div class="row top_tiles" style="margin: 20px 0 2px 0;">
                    <div class=" col-md-2 col-md-offset-1 col-xs-12 tile text-center">
                        <a href="{{route('sys-customers.index')}}" class="">
                            <strong>@lang('general.text_sys_customers')</strong>
                            @if(Auth::user()->distributor)
                                <h2>{{\App\Helpers\Helper::numberFormat(\App\Models\System\SysCustomer::userDistributor()->active()->count())}}</h2>
                            @else
                                <h2>{{\App\Helpers\Helper::numberFormat(\App\Models\System\SysCustomer::active()->count())}}</h2>
                            @endif
                        </a>
                    </div>
                    <div class="col-md-2 col-xs-12 tile text-center">
                        <a href="{{route('sys-sales-orders.index',['filter_status' => \App\Models\System\SysSalesOrder::PER_ACTIVE])}}" class="">
                            <strong>@lang('general.text_sys_sales_orders')</strong>
                            @if(Auth::user()->distributor)
                                <h2>{{App\Models\System\SysSalesOrder::where('status','=',\App\Models\System\SysSalesOrder::PER_ACTIVE)->whereHas('sysCustomer', function ($q) { $q->where('sys_customers.distributor_id', '=', \Auth::user()->id); })->count()}}</h2>
                            @else
                                <h2>{{\App\Models\System\SysSalesOrder::where('status','=',\App\Models\System\SysSalesOrder::PER_ACTIVE)->count()}}</h2>
                            @endif
                        </a>
                    </div>
                    <div class="col-md-2 col-xs-12 tile text-center">
                        <a href="{{route('users.index')}}" class="">
                            <strong>@lang('general.text_users')</strong>
                            @if(Auth::user()->distributor)
                                <h2>{{\App\Helpers\Helper::numberFormat(\App\Models\Auth\User::userDistributor()->active()->count())}}</h2>
                            @else
                                <h2>{{\App\Helpers\Helper::numberFormat(\App\Models\Auth\User::active()->count())}}</h2>
                            @endif
                        </a>
                    </div>
                    <div class="col-md-2 col-xs-12 tile text-center">
                        <a href="#" class="">
                            <strong>@lang('general.text_cpu_load')</strong>
                            @if(!empty($server_stats['cpu_load']))
                            <h2>{{round($server_stats['cpu_load'],2)}}%</h2>
                            @endif
                        </a>
                    </div>
                    <div class="col-md-2 col-xs-12 tile text-center">
                        <a href="#" class="">
                            <strong>@lang('general.text_disk_used')</strong>
                            @if(!empty($server_stats['disk_total']))
                            <h2>{{round($server_stats['disk_used']/$server_stats['disk_total']*100,0)}}%</h2>
                            @endif
                        </a>
                    </div>
                </div>
            @endif
            <br/>
            @if ($link_dist_register && config('app.enabled_register_tenant'))
            <div class="row">
                <div class="col-md-12 col-xs-12">
                    <div class="x_panel mb-0">
                        <div class="x_content">
                            <button onclick="copiarAlPortapapeles()" class="btn btn-sm btn-default pull-right"><b>Copiar Link</b></button>
                            <p class="mb-0" >
                                <strong>Link de registro para usuarios: </strong> {{$link_dist_register}}<br/>
                                <small class="text-muted">* Se asocia en automático al distribuidor</small>
                            </p>
                        </div>
                    </div>
                </div>
            </div>
            @endif
            @if (\Auth::user()->sysCustomer)
            <div class="row">
                <div class="col-md-12 col-xs-12">
                    <div class="x_panel">
                        <div class="x_title">
                            <h2>
                                @lang('general.text_report')
                            </h2>
                            <div class="filter">
                                <div id="report_range" class="pull-right" style="background: #fff; cursor: pointer; padding: 5px 10px; border: 1px solid #ccc">
                                    <i class="glyphicon glyphicon-calendar fa fa-calendar"></i>
                                    <span>-</span> <b class="caret"></b>
                                </div>
                            </div>
                            <div class="clearfix"></div>
                        </div>
                        <div class="x_content">
                            <div class="col-md-12 col-xs-12">

                                <!-- Grafica -->
                                <div class="ymchart" style="height: 300px;">
                                <canvas class="" id="report_chart"></canvas>
                                </div>
                                <div class="tiles" style="margin-top: 20px;">
                                    <div class="col-md-3 col-xs-12 tile text-center" style="margin-top: 15px;">
                                        <span class="ymlabel-1">&nbsp;</span>
                                        <strong>@lang('general.text_customer_invoices')</strong>
                                        <h2 id="txt_total_customer_invoices">-</h2>
                                    </div>
                                    <div class="col-md-3 col-xs-12 tile text-center" style="margin-top: 15px;">
                                        <span class="ymlabel-2">&nbsp;</span>
                                        <strong>@lang('general.text_customer_credit_notes')</strong>
                                        <h2 id="txt_total_customer_credit_notes">-</h2>
                                    </div>
                                    <div class="col-md-3 col-xs-12 tile text-center" style="margin-top: 15px;">
                                        <span class="ymlabel-3">&nbsp;</span>
                                        <strong>@lang('general.text_customer_payments')</strong>
                                        <h2 id="txt_total_customer_payments">-</h2>
                                    </div>
                                    <div class="col-md-3 col-xs-12 tile text-center" style="margin-top: 15px;">
                                        <span class="ymlabel-4">&nbsp;</span>
                                        <strong>@lang('general.text_cfdi_receiveds')</strong>
                                        <h2 id="txt_total_cfdi_receiveds">-</h2>
                                    </div>
                                </div>
                                <div class="" style="margin-top: 30px;">
                                    <div class="col-md-12 col-xs-12 tile text-left">
                                        <i>
                                            <small class="text-muted">
                                                * @lang('general.text_help_amounts_currency')
                                            </small>
                                        </i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            @elseif(Auth::user()->superadmin || Auth::user()->distributor)
                <div class="row">
                    <div class="col-md-12 col-xs-12">
                        <div class="x_panel">
                            <div class="x_title">
                                <h2>
                                    @lang('general.text_report')
                                </h2>
                                <div class="filter">
                                    <div id="report_range_sys_sales_orders" class="pull-right" style="background: #fff; cursor: pointer; padding: 5px 10px; border: 1px solid #ccc">
                                        <i class="glyphicon glyphicon-calendar fa fa-calendar"></i>
                                        <span>-</span> <b class="caret"></b>
                                    </div>
                                </div>
                                <div class="clearfix"></div>
                            </div>
                            <div class="x_content">
                                <div class="col-md-12 col-xs-12">

                                    <!-- Grafica -->
                                    <div class="ymchart" style="height: 300px;">
                                        <canvas class="" id="report_chart_sys_sales_orders"></canvas>
                                    </div>
                                    <div class="tiles" style="margin-top: 20px;">
                                        <div class="col-md-4 col-md-offset-4 col-xs-12 tile text-center" style="margin-top: 15px;">
                                            <span class="ymlabel-1">&nbsp;</span>
                                            <strong>@lang('general.text_sys_sales_orders')</strong>
                                            <h2 id="txt_total_sys_sales_orders">-</h2>
                                        </div>
                                    </div>
                                    <div class="" style="margin-top: 30px;">
                                        <div class="col-md-12 col-xs-12 tile text-left">
                                            <i>
                                                <small class="text-muted">
                                                    * @lang('general.text_help_amounts_currency')
                                                </small>
                                            </i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            @endif
            @if (\Auth::user()->sysCustomer)
            <div class="row top_tiles" style="margin-top: 20px;">
                <div class="col-md-12 col-xs-12 text-center" style="margin-bottom: 15px;">
                    <h4>@lang('general.text_button_favorites')</h4>
                </div>
                <div class="col-md-12 col-xs-12 text-center" style="margin-bottom: 40px;">
                    <a href="{{route('customer-invoices.create')}}" class="btn btn-success btn-large"><i
                                class="fa fa-star"></i> @lang('general.text_create_customer_invoice')</a>
                    <span class="hidden-xs">&nbsp;&nbsp;&nbsp;&nbsp;</span>
                    <a href="{{route('customer-credit-notes.create')}}" class="btn btn-success btn-large"><i
                                class="fa fa-star"></i> @lang('general.text_create_customer_credit_note')</a>
                    <span class="hidden-xs">&nbsp;&nbsp;&nbsp;&nbsp;</span>
                    <a href="{{route('customer-payments.create')}}" class="btn btn-success btn-large"><i
                                class="fa fa-star"></i> @lang('general.text_create_customer_payment')</a>
                    <span class="hidden-xs">&nbsp;&nbsp;&nbsp;&nbsp;</span>
                    <a href="{{route('customers.create')}}" class="btn btn-success btn-large"><i
                                class="fa fa-star"></i> @lang('general.text_create_customer')</a>
                    <span class="hidden-xs">&nbsp;&nbsp;&nbsp;&nbsp;</span>
                    <a href="{{route('products.create')}}" class="btn btn-success btn-large"><i
                                class="fa fa-star"></i> @lang('general.text_create_product')</a>
                </div>
            </div>
            @endif
        </div>
    </div>
    <!-- /page content -->
@endsection
@section('scripts_specific')
    <script src="{{ asset('gentelella/plugins/bootstrap-daterangepicker/daterangepicker.js') }}"></script>
    <script src="{{ asset('gentelella/plugins/Chart.js/dist/Chart.min.js') }}"></script>
    <script src="{{ asset('gentelella/plugins/Chart.js/dist/Chart.bundle.js') }}"></script>
    <script src="{{ asset('gentelella/plugins/DateJS/build/date.js') }}"></script>
    <script src="{{ asset('vendor/numeral/min/numeral.min.js') }}"></script>
@endsection
@section('scripts')
    <script type="text/javascript">
        var report_chart = null;
        var report_chart_sys_sales_orders = null;

        function getReportDashboard(filter_date_from,filter_date_to){
            if(filter_date_from && filter_date_to){
                $.ajax({
                    url: "{{ route('home/get-data-chart-dashboard') }}",
                    type: "GET",
                    dataType: "JSON",
                    data: "filter_date_from="+filter_date_from+"&filter_date_to="+filter_date_to,
                    success: function (data) {
                        if (data) {
                            //Totales
                            $("#txt_total_customer_invoices").html(data.total_customer_invoices);
                            $("#txt_total_customer_credit_notes").html(data.total_customer_credit_notes);
                            $("#txt_total_customer_payments").html(data.total_customer_payments);
                            $("#txt_total_cfdi_receiveds").html(data.total_cfdi_receiveds);

                            //Grafica
                            let labels = data.labels;
                            let data1 = {
                                label: "{{__('general.text_customer_invoices')}}",
                                backgroundColor: "#03586A",
                                data: data.data_customer_invoices
                            };
                            let data2 = {
                                label: "{{__('general.text_customer_credit_notes')}}",
                                backgroundColor: "#26B99A",
                                data: data.data_customer_credit_notes
                            };
                            let data3 = {
                                label: "{{__('general.text_customer_payments')}}",
                                backgroundColor: "#3498DB",
                                data: data.data_customer_payments
                            };
                            let data4 = {
                                label: "{{__('general.text_cfdi_receiveds')}}",
                                backgroundColor: "#FF9933",
                                data: data.data_cfdi_receiveds
                            };
                            //Fix redraw
                            if(report_chart !== undefined && report_chart !== null ){
                                report_chart.destroy();
                            }
                            report_chart = new Chart(document.getElementById("report_chart"), {
                                type: "bar",
                                data: {
                                    labels: labels,
                                    datasets: [data1, data2, data3,data4]
                                },
                                options: {
                                    legend: {
                                        display: false,
                                    },
                                    scales: {
                                        yAxes: [{
                                            ticks: {
                                                beginAtZero: true,
                                                callback: function (value) {
                                                    return numeral(value).format("$ 0,0.00")
                                                }
                                            }
                                        }]
                                    },
                                    maintainAspectRatio: false,
                                    tooltips: {
                                        callbacks: {
                                            label: function(tooltipItem, data) {
                                                var label = data.datasets[tooltipItem.datasetIndex].label || "";

                                                if (label) {
                                                    label += ": ";
                                                }
                                                label += numeral(tooltipItem.yLabel).format("$ 0,0.00");
                                                return label;
                                            }
                                        }
                                    }
                                }
                            });
                            //report_chart.destroy();
                        }
                    },
                    error: function (error, textStatus, errorThrown) {
                        if (error.status == 422) {
                            var message = error.responseJSON.error;
                            $("#general_messages").html(alertMessage("danger", message));
                        } else {
                            alert(errorThrown + "\r\n" + error.statusText + "\r\n" + error.responseText);
                        }
                    }
                });
            }
        }

        function getReportDashboardSysSalesOrders(filter_date_from,filter_date_to){
            if(filter_date_from && filter_date_to){
                $.ajax({
                    url: "{{ route('home/get-data-chart-dashboard-sys-sales-orders') }}",
                    type: "GET",
                    dataType: "JSON",
                    data: "filter_date_from="+filter_date_from+"&filter_date_to="+filter_date_to,
                    success: function (data) {
                        if (data) {
                            //Totales
                            $("#txt_total_sys_sales_orders").html(data.total_sys_sales_orders);

                            //Grafica
                            let labels = data.labels;
                            let data1 = {
                                label: "{{__('general.text_sys_sales_orders')}}",
                                backgroundColor: "#03586A",
                                data: data.data_sys_sales_orders
                            };
                            //Fix redraw
                            if(report_chart_sys_sales_orders !== undefined && report_chart_sys_sales_orders !== null ){
                                report_chart_sys_sales_orders.destroy();
                            }
                            report_chart_sys_sales_orders = new Chart(document.getElementById("report_chart_sys_sales_orders"), {
                                type: "bar",
                                data: {
                                    labels: labels,
                                    datasets: [data1]
                                },
                                options: {
                                    legend: {
                                        display: false,
                                    },
                                    scales: {
                                        yAxes: [{
                                            ticks: {
                                                beginAtZero: true,
                                                callback: function (value) {
                                                    return numeral(value).format("$ 0,0.00")
                                                }
                                            }
                                        }]
                                    },
                                    maintainAspectRatio: false,
                                    tooltips: {
                                        callbacks: {
                                            label: function(tooltipItem, data) {
                                                var label = data.datasets[tooltipItem.datasetIndex].label || "";

                                                if (label) {
                                                    label += ": ";
                                                }
                                                label += numeral(tooltipItem.yLabel).format("$ 0,0.00");
                                                return label;
                                            }
                                        }
                                    }
                                }
                            });
                            //report_chart.destroy();
                        }
                    },
                    error: function (error, textStatus, errorThrown) {
                        if (error.status == 422) {
                            var message = error.responseJSON.error;
                            $("#general_messages").html(alertMessage("danger", message));
                        } else {
                            alert(errorThrown + "\r\n" + error.statusText + "\r\n" + error.responseText);
                        }
                    }
                });
            }
        }

        function copiarAlPortapapeles() {
            var aux = document.createElement("input");
            aux.setAttribute("value", '{{ $link_dist_register }}');
            document.body.appendChild(aux);
            aux.select();
            document.execCommand("copy");
            document.body.removeChild(aux);
        }

        $(function () {
            /*Fechas*/
            moment.locale("{{ substr(app()->getLocale(),0,2) }}");
            var start = moment().subtract(6, "days");
            var end = moment();
            function cb(start, end) {
                $("#report_range span").html(start.format("MMMM D, YYYY") + " - " + end.format("MMMM D, YYYY"));
            }
            $("#report_range").daterangepicker({
                startDate: start,
                endDate: end,
                ranges: {
                    "Hoy": [moment(), moment()],
                    "Ayer": [moment().subtract(1, "days"), moment().subtract(1, "days")],
                    "Últimos 7 días": [moment().subtract(6, "days"), moment()],
                    "Últimos 30 días": [moment().subtract(29, "days"), moment()],
                    "Este mes": [moment().startOf("month"), moment().endOf("month")],
                    "Mes pasado": [moment().subtract(1, "month").startOf("month"), moment().subtract(1, "month").endOf("month")]
                },
                locale: {
                    "applyLabel": "Aplicar",
                    "cancelLabel": "Cancelar",
                    "customRangeLabel": "Rango",
                }
            }, cb).on("apply.daterangepicker", function(ev, picker) {
                getReportDashboard(picker.startDate.format("{{ setting('date_picker_format','DD-MM-YYYY') }}"),picker.endDate.format("{{ setting('date_picker_format','DD-MM-YYYY') }}"));
            });
            cb(start, end);
            //$(".range_inputs .applyBtn").removeAttr("disabled").trigger("click");

            //Pedidos de venta
            function cbsl(start, end) {
                $("#report_range_sys_sales_orders span").html(start.format("MMMM D, YYYY") + " - " + end.format("MMMM D, YYYY"));
            }
            $("#report_range_sys_sales_orders").daterangepicker({
                startDate: start,
                endDate: end,
                ranges: {
                    "Hoy": [moment(), moment()],
                    "Ayer": [moment().subtract(1, "days"), moment().subtract(1, "days")],
                    "Últimos 7 días": [moment().subtract(6, "days"), moment()],
                    "Últimos 30 días": [moment().subtract(29, "days"), moment()],
                    "Este mes": [moment().startOf("month"), moment().endOf("month")],
                    "Mes pasado": [moment().subtract(1, "month").startOf("month"), moment().subtract(1, "month").endOf("month")]
                },
                locale: {
                    "applyLabel": "Aplicar",
                    "cancelLabel": "Cancelar",
                    "customRangeLabel": "Rango",
                }
            }, cbsl).on("apply.daterangepicker", function(ev, picker) {
                getReportDashboardSysSalesOrders(picker.startDate.format("{{ setting('date_picker_format','DD-MM-YYYY') }}"),picker.endDate.format("{{ setting('date_picker_format','DD-MM-YYYY') }}"));
            });
            cbsl(start, end);
            $(".range_inputs .applyBtn").removeAttr("disabled").trigger("click");

        });
    </script>
    @if(!empty(config('app.optinly_key')))
        <script id="optinly_script" async="true" data-app_id='{{config('app.optinly_key')}}' src='https://cdn.optinly.net/v1/optinly.js' type='text/javascript'> </script>
    @endif
    @if(!empty(config('app.usetiful_key')))
        <script>
            (function (w, d, s) {
                var a = d.getElementsByTagName('head')[0];
                var r = d.createElement('script');
                r.async = 1;
                r.src = s;
                r.setAttribute('id', 'usetifulScript');
                r.dataset.token = "{{config('app.usetiful_key')}}";
                a.appendChild(r);
            })(window, document, "https://www.usetiful.com/dist/usetiful.js");
        </script>
    @endif
@endsection
