<div class="page-title">
    <h1><?php echo $this->user->lang("Dashboard");?></h1>
</div>

<?php if (!DEMO && ($this->loginHistory) && isset($this->loginHistory[1]['location'])) { ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
    <?php echo $this->user->lang('Your last login was from a different location on '); ?>
    <span class="fw-semibold">
        <?php echo $this->loginHistory[1]['date']->format($this->dateFormat.' g:ia'); ?>
    </span>
    <?php echo $this->user->lang('from IP'); ?>
    <span class="fw-semibold">
        <?php echo $this->loginHistory[1]['ip']
            .(isset($this->loginHistory[1]['location'])
            && $this->loginHistory[1]['location']['cityName'] != '-'
                ? ' ('.ucwords($this->loginHistory[1]['location']['cityName'])
                .', '.ucwords($this->loginHistory[1]['location']['countryName']).')'
                : ''); ?>
    </span>
    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>

<?php } ?>

<div class="dash-tile-wrapper">
    <div class="tile-wrapper dashboard-counts">
        <div class="row count-blocks">
        </div>
    </div>
</div>

<?php if ($this->settings['section_reports'] && $this->show_graph) { ?>
<div class="cm-holder">
    <div class="cm-tab-accordion">
        <div class="cm-tabs">
            <ul id="overview" class="resp-tabs-list">
                <?php
                    $count = 1;
                foreach($this->graph_options as $graph_options) { ?>
                <li data-count="<?php echo $count; ?>" data-report-value="<?php echo $graph_options['option_value'];?>">
                    <i class="icon-dash-tab-ic-<?php echo $count; ?>"></i>
                    <h5><?php echo $this->user->lang($graph_options['option_name']) ?></h5>
                    <span><?php echo $this->user->lang($graph_options['report_type']) ?></span>
                </li>
                <?php
                    $count++;
                } ?>
            </ul>

            <div class="resp-tabs-container">
                <?php
                    $count = 1;
                    foreach($this->graph_options as $graph_options) { ?>
                <div>
                    <h3><?php echo $this->user->lang($graph_options['option_name']) ?></h3>
                    <!-- <span>Your customer and product’s status.</span> -->
                    <div class="graph-wrapper mt-4" style="">
                        <canvas style="padding-left:0; margin-left:0; width: 98%; height: 300px;" id="chartCanvas-<?php echo $count; ?>"></canvas>
                    </div>
                </div>
                    <?php
                    $count++;
                } ?>
            </div>
        </div>
    </div>
</div>
<?php } ?>

            <?php if ($this->showDashboardPanel) {?>

            <?php if ($this->settings['section_orders']) { ?>
            <div class="cm-holder">
                <div class="head padding-bottom">
                    <h3><?php echo $this->user->lang('Pending Orders'); ?></h3>

                </div>
                <div class="data-table-wrapper pull-top">
                    <div class="pending-orders table-responsive">
                        <table id="order-table" class="table display">
                            <thead>
                                <tr>
                                    <th class="width1"><?php echo $this->user->lang("Date");?></th>
                                    <th class="width2"><center><?php echo $this->user->lang("Package Name");?></center></th>
                                    <th class="width3"><center><?php echo $this->user->lang("Client");?></center></th>
                                    <th class="width4"><center><?php echo $this->user->lang("Status");?></center></th>
                                </tr>
                            </thead>
                            <tbody>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            <?php } ?>


            <?php if ($this->showLastSection) { ?>

                <?php if ($this->top_dashboard_html != "") { ?>
                <div class="cm-holder">
                    <!-- html for top-active-panel -->
                    <?php echo $this->unescape($this->top_dashboard_html);?>
                    <!-- end html for top-active-panel -->
                </div>
                <?php } ?>

                <?php if ($this->settings['section_automation']) { ?>
                <div class="cm-holder">
                    <div class="head padding-bottom">
                        <h3><?php echo $this->user->lang("Automation Status");?></h3>

                    </div>
                    <div class="data-table-wrapper pull-top">
                        <div class="pending-orders table-responsive">
                            <table id="tbl-need-your-attention" class="table display">
                                <thead>
                                    <tr>
                                        <th class="width1"><?php echo $this->user->lang("Service");?></th>
                                        <th class="width2"><center><?php echo $this->user->lang("Last Run");?></center></th>
                                        <th class="width3"><center><?php echo $this->user->lang("Next Run");?></center></th>
                                        <th class="width4"><center><?php echo $this->user->lang("Execute");?></center></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr><td colspan="4"><center><?php echo $this->user->lang("Getting records ..");?></center></td></tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                    <?php if (count($this->activeServices) > 0) { ?>
                    <div class="cm-holder">
                        <div class="head padding-bottom">
                            <h3 class="float-start">
                                <i class="fas fa-bolt"></i>&nbsp;&nbsp;&nbsp;
                                <?php echo $this->user->lang("Automation Summary For"); ?>
                            </h3>

                            <div class="selectedrange float-start ms-3">
                                <div class="dropdown">
                                    <a class="dropdown-toggle dropdown-toggle-automation" href="#" role="button"
                                       data-bs-toggle="dropdown" aria-expanded="false" style="white-space: nowrap;">
                                        <span class="selected-automation-name"></span>
                                    </a>

                                    <ul class="dropdown-menu dropdown-menu-end">
                                        <?php foreach ($this->activeServices as $key => $service) { ?>
                                            <li>
                                                <a href="#"
                                                   class="dropdown-item active-service-select"
                                                   data-value="<?php echo $key; ?>">
                                                   <?php echo $this->user->lang($service); ?>
                                                </a>
                                            </li>
                                        <?php } ?>
                                    </ul>
                                </div>
                            </div>

                            <div class="clearfix"></div>
                            <div class="mt-1">
                                <i><?php echo $this->user->lang("Upcoming items that this automation service will interact with"); ?></i>
                            </div>
                        </div>

                        <div class="data-table-wrapper pull-top">
                            <div class="table-panel" id="upcoming-events-table"></div>
                        </div>
                    </div>
                    <?php } ?>

                <?php } ?>

                <?php if ($this->middle_dashboard_html != "") { ?>
                <div class="cm-holder">
                    <!-- html for middle-active-panel -->
                    <?php echo $this->unescape($this->v);?>
                    <!-- end html for middle-active-panel -->
                </div>
                <?php } ?>

                <?php if ($this->bottom_dashboard_html != "") { ?>
                <div class="cm-holder">
                    <!-- html for bottom-active-panel -->
                    <?php echo $this->unescape($this->bottom_dashboard_html);?>
                    <!-- end html for bottom-active-panel -->
                </div>
                <?php } ?>
            <?php } ?>
        <?php } ?>
<script>
var dashboard = dashboard || {
    renderAtAGlance: function(payload) {
        // count can contain html (currency)
        var at_a_glance_template = '{{#arr}}<div class="col-xl col-lg-3 col-md-3 col-sm-6 col-xs-6 count-block {{#yesterday}}count-block-yesterday{{/yesterday}}"><div class="tile-item {{bg}} eq-height"><div class="box-holder"><span class="value">{{{count}}}</span><span class="title">{{name}}</span></div><span class="prev">Yesterday : {{{yesterday}}}</span></div></div>{{/arr}}';
        var output = Mustache.render(at_a_glance_template, {arr: payload});
        $('.dashboard-counts .count-blocks').html(output);

        // //update style for currency
        // var cur_count = $('.dashboard-counts .count-block > .ataglance-currency-item').length;
        // if (cur_count > 2) {
        //     $('.dashboard-counts .count-block > .ataglance-currency-item').parent().addClass('count-block-smaller');
        // } else if (cur_count > 1) {
        //     $('.dashboard-counts .count-block > .ataglance-currency-item').parent().addClass('count-block-small');
        // }

        // //update style for yesterday currency
        // var cur_count = $('.dashboard-counts .count-yesterday > .ataglance-currency-item').length;
        // if (cur_count > 2) {
        //     $('.dashboard-counts .count-yesterday > .ataglance-currency-item').parent().addClass('count-yesterday-smaller');
        // } else if (cur_count > 1) {
        //     $('.dashboard-counts .count-yesterday > .ataglance-currency-item').parent().addClass('count-yesterday-small');
        // }
    },
    orders: {
        renderPendingOrders: function(payload) {
            if ( payload.length > 0 ) {
                var orders_template = '{{#arr}}<tr><td>{{{dateActivated}}}</td><td style="text-align: center"><a class="link2" href="index.php?fuse=clients&controller=userprofile&view=profileproduct&groupinfo&id={{{pendingpackageid}}}&frmClientID={{{pendingpackageuserid}}}">{{{pendingpackagereference}}}</a></td><td style="text-align: center"><span class="avatar"><img src="{{{avatar}}}" class="img-fluid" /></span><a class="link2" href="index.php?fuse=clients&controller=userprofile&view=profilecontact&frmClientID={{{pendingpackageuserid}}}">{{{pendingpackagecustomername}}}</a></td><td style="text-align: center"><span class="status-btn {{{statusclass}}}">{{{packagepaidstatus}}}</span></tr>{{/arr}}';
                var output = Mustache.render(orders_template, {arr: payload});
            } else {
                var output = "<tr><td colspan='5'><center>" + clientexec.lang('No Pending Orders') + '</center></td></tr>';
            }
            $('#order-table tbody').html(output);
        },
        getPendingOrders: function() {
            if ( $('#order-table').length > 0 ) {
                $.ajax({
                    url: 'index.php?fuse=clients&action=getpendingorderslist',
                    dataType: 'json',
                    success: function(response) {
                        response = clientexec.parseResponse(response);
                        dashboard.orders.renderPendingOrders(response.data);
                    }
                });
            }
        }
    },
    tickets: {
        renderFavoriteTickets: function(payload) {

            if ( payload.length > 0 ) {
                var ticket_template = '{{#arr}}<tr><td><a href="index.php?fuse=support&view=viewtickets&controller=ticket&id={{{id}}}">#{{{id}}} - {{{subject}}}</a></td><td style="text-align: center">{{{submittedby}}}</td><td style="text-align: center">{{{assignedtofull}}}</td><td style="text-align: center">{{{timeelapsed}}}</td><td style="text-align: center">{{{lastReply}}}</td><td style="text-align: center">{{{statusname}}}</td></tr>{{/arr}}';
                var output = Mustache.render(ticket_template, {arr: payload});
            } else {
                var output = "<tr><td colspan='6'><center>" + clientexec.lang('No Tickets Found') + '</center></td></tr>';
            }
            $('.favorited-tickets-table tbody').html(output);
        },
        getFavoriteTickets: function() {
            if ( dashboard.ticketfilter != '' ) {
                $.ajax({
                    url: 'index.php?fuse=support&action=gettickets&controller=tickets&dir=asc&start=0&limit=15&filter='+dashboard.ticketfilter,
                    dataType: 'json',
                    success: function(response) {
                        response = clientexec.parseResponse(response);
                        $('.favorite-tickets-label').text(dashboard.ticketfilter_name);
                        dashboard.tickets.renderFavoriteTickets(response.items);
                    }
                });
            }
        }
    },
    vital: {
        getTodayAtAGlance:function() {
            $.ajax({
                url: 'index.php?fuse=home&controller=index&action=getataglance',
                dataType: 'json',
                success: function(response) {
                    response = clientexec.parseResponse(response);
                    if (response.ataglance.length > 0) {
                        dashboard.renderAtAGlance(response.ataglance);
                    }
                }
            });

        },

        automation_status_template : "{{#arr}}<tr><td>{{{name}}}</td><td><center>{{last}}</center></td><td><center>{{next}}</center></td><td><center>{{{status}}}</center></td></tr>{{/arr}}{{^arr}}<tr><td colspan='4'><center>" + clientexec.lang("There are no services enabled") + "</center></td></tr>{{/arr}}",

        getAutomationStatus: function() {
            if ( $('#tbl-need-your-attention').length > 0 ) {
                $.ajax({
                    url: 'index.php?fuse=home&controller=index&action=getautomationstatus',
                    dataType: 'json',
                    success: function(response) {
                        response = clientexec.parseResponse(response);
                        var output = Mustache.render(dashboard.vital.automation_status_template, {arr:response.automationstatus});
                        $('#tbl-need-your-attention tbody').html(output);
                    }
                });
            }
        }
    },
    events: {
        activeService: null,
        getUpcomingEvents: function(service) {
            if ( service == '' ) return;
            $.ajax({
                url: 'index.php?fuse=home&controller=index&action=getupcomingevents',
                data: {
                    service: service
                },
                dataType: 'json',
                success: function (response) {
                    var output = response.output;
                    $('.selected-automation-name').text(response.servicename);
                    $.get('../templates/admin/views/home/index/upcomingevents.mustache', function(template) {
                        var items = {
                            headers: output.headers,
                            data: output.data,
                            extract: function() {
                                returnString = '';
                                $.each(this, function(i,o) {
                                    returnString += '<td>' + o + '</td>';
                                });
                                return returnString;
                            }
                        };
                        $('#upcoming-events-table').html(Mustache.render(template, items));
                    });
                }
            });
        }
    }
};

$(document).ready(function() {

    <?php if ($this->cache_at_a_glance != "") { ?>
    // watch out for backslashes that are interpreted in js
    var cache_at_a_glance = jQuery.parseJSON('<?php echo str_replace('\\', '\\\\',  $this->unescape($this->cache_at_a_glance)) ?>');
    dashboard.renderAtAGlance(cache_at_a_glance);
    $('.dashboard-counts').attr('data-has-cache-data',true);
    <?php }?>

    dashboard.orders.getPendingOrders();
    dashboard.vital.getAutomationStatus();
    dashboard.events.getUpcomingEvents('<?php echo $this->activeService; ?>');
    <?php if ($this->show_graph && $this->selected_graph != "") { ?>
    var count = $('li[data-report-value="<?php echo $this->selected_graph; ?>"]').data('count');
    var chartId = '#chartCanvas-' + count;
    clientexec.populate_report('<?php echo $this->selected_graph;?>', chartId, {indashboard:1});
    const reportValue = "<?php echo $this->selected_graph; ?>";
    $(`li[data-report-value="${reportValue}"]`).trigger('click');
    <?php } ?>

    $('.active-service-select').bind('click', function() {
        dashboard.events.getUpcomingEvents($(this).attr('data-value'));
    });

    //if we have cache data delay this call to allow other background calls that are needed quicker
    if ($('.dashboard-counts[data-has-cache-data]').length > 0) {
        window.setTimeout(dashboard.vital.getTodayAtAGlance,2000);
    } else {
        dashboard.vital.getTodayAtAGlance();
    }

    $('.resp-accordion').each(function(index){
        var li = $('#overview li').eq(index);
        $(this).attr('data-count', li.data('count'));
        $(this).attr('data-report-value', li.data('report-value'));
    });

    $(document).on('click', '#overview li, .resp-accordion', function () {
        var report = $(this).data('report-value');
        var count = $(this).data('count');
        var chartId = '#chartCanvas-' + count;

        clientexec.populate_report(report, chartId, { indashboard: 1 });
    });
});

</script>