<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 overflow-auto">
                            <div class="pending-orders table-responsive">
                                <table id="order-table" class="table display">
                                    <thead>
                                    <tr>
                                        <th><?php echo $this->user->lang("Order ID");?></th>
                                        <th><?php echo $this->user->lang("Date");?></th>
                                        <th class="text-center"><?php echo $this->user->lang("Client");?></th>
                                        <th class="text-center"><?php echo $this->user->lang("Status");?></th>
                                    </tr>
                                    </thead>
                                    <tbody>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                <?php } ?>

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

                        </div>
                        <div class="data-table-wrapper pull-top overflow-auto">
                            <div class="awaiting-tickets table-responsive">
                                <table id="tickets-table" class="table display">
                                    <thead>
                                    <tr>
                                        <th><?php echo $this->user->lang("Subject");?></th>
                                        <th class="text-center"><?php echo $this->user->lang("Created By");?></th>
                                        <th class="text-center"><?php echo $this->user->lang("Assigned To");?></th>
                                        <th class="text-center"><?php echo $this->user->lang("Elapsed");?></th>
                                        <th class="text-center"><?php echo $this->user->lang("Last Reply");?></th>
                                        <th class="text-center"><?php echo $this->user->lang("Status");?></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 overflow-auto">
                        <div class="pending-orders table-responsive">
                            <table id="tbl-need-your-attention" class="table display">
                                <thead>
                                <tr>
                                    <th><?php echo $this->user->lang("Service");?></th>
                                    <th class="text-center"><?php echo $this->user->lang("Last Run");?></th>
                                    <th class="text-center"><?php echo $this->user->lang("Next Run");?></th>
                                    <th class="text-center"><?php echo $this->user->lang("Execute");?></th>
                                </tr>
                                </thead>
                                <tbody>
                                <tr><td colspan="4" class="text-center"><?php echo $this->user->lang("Getting records ..");?></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 overflow-auto">
                            <div class="table-panel upcoming-events table-responsive" 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 data-cfasync="false">
var dashboard = dashboard || {

    renderAtAGlance: function(payload) {

        payload.forEach(function(item) {

            item.isRevenue = item.name === 'Revenue';

            if (Array.isArray(item.count)) {
                item.count = item.count[0];
            }

            if (Array.isArray(item.yesterday)) {
                item.yesterday = item.yesterday[0];
            }

        });

        // count can contain html (currency)
        var at_a_glance_template = `
    {{#arr}}
    <div class="col-6 col-sm-6 col-md-3 col-lg-3 col-xl-2 count-block">

        <div class="tile-item {{bg}} eq-height {{#isRevenue}}revenue-card{{/isRevenue}}">

            {{#isRevenue}}
            <div class="card-top">

                <div class="dropdown currency-dropdown">
                    <button
                        class="dropdown-toggle"
                        type="button"
                        data-bs-toggle="dropdown"
                        aria-expanded="false"
                    >
                        {{selectedCurrency}}
                    </button>

                    <ul class="dropdown-menu">
                        {{#currencies}}
                        <li>
                            <a
                                class="dropdown-item {{#selected}}active{{/selected}}"
                                href="#"
                                data-currency="{{code}}"
                            >
                                {{code}}
                            </a>
                        </li>
                        {{/currencies}}
                    </ul>
                </div>

            </div>
            {{/isRevenue}}

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

    },
    orders: {
        renderPendingOrders: function(payload) {
            if ( payload.length > 0 ) {
                var orders_template = `
    {{#arr}}
    <tr>
        <td data-label="${clientexec.lang('Order ID')}">
            <a class="link2" href="index.php?fuse=clients&controller=orders&view=order&frmClientID={{{client_id}}}&id={{{id}}}">
                {{{id}}}
            </a>
        </td>
        <td data-label="${clientexec.lang('Date')}">{{{order_date}}}</td>
        <td data-label="${clientexec.lang('Client')}" class="text-center">
            <div class="d-inline-flex align-items-center gap-2">
                <span class="avatar">
                    <img src="{{{avatar}}}" class="img-fluid" />
                </span>
                <a class="link2" href="index.php?fuse=clients&controller=userprofile&view=profilecontact&frmClientID={{{client_id}}}">
                    {{{client_name}}}
                </a>
            </div>
        </td>
        <td data-label="${clientexec.lang('Status')}" class="text-center">
            <span class="status-btn {{{status_class}}}">
                {{{payment_status}}}
            </span>
        </td>
    </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 data-label="${clientexec.lang('Subject')}">
                    <a class="link2" href="index.php?fuse=support&view=ticket&controller=ticket&id={{{id}}}">#{{{id}}} - {{{subject}}}</a>
                </td>
                <td data-label="${clientexec.lang('Created By')}" class="text-center">
                    <a class="link2" href="index.php?fuse=clients&controller=userprofile&view=profilecontact&frmClientID={{{userid}}}">{{{submittedby}}}</a>
                </td>
                <td data-label="${clientexec.lang('Assigned To')}" class="text-center">{{{assignedtofull}}}</td>
                <td data-label="${clientexec.lang('Elapsed')}" class="text-center">{{{timeelapsed}}}</td>
                <td data-label="${clientexec.lang('Last Reply')}" class="text-center">{{{lastReply}}}</td>
                <td data-label="${clientexec.lang('Status')}" class="text-center">
                    <span class="status-btn {{{statusClass}}}">{{{statusname}}}</span>
                </td>
            </tr>
            {{/arr}}
        `;
                var output = Mustache.render(ticket_template, {arr: payload});
            } else {
                var output = `<tr><td colspan='6' class="text-center">${clientexec.lang('No Tickets Found')}</td></tr>`;
            }
            $('#tickets-table tbody').html(output);
        },
        getFavoriteTickets: function() {
            $.ajax({
                url: 'index.php?fuse=support&action=gettickets&controller=tickets&dir=asc&start=0&limit=15&filter=awaitingreply',
                dataType: 'json',
                success: function(response) {
                    response = clientexec.parseResponse(response);
                    dashboard.tickets.renderFavoriteTickets(response.data);
                }
            });

        }
    },
    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 data-label="${clientexec.lang('Service')}">{{{name}}}</td>
        <td data-label="${clientexec.lang('Last Run')}" class="text-center">{{last}}</td>
        <td data-label="${clientexec.lang('Next Run')}" class="text-center">{{next}}</td>
        <td data-label="${clientexec.lang('Execute')}" class="text-center">{{{status}}}</td>
    </tr>
    {{/arr}}
    {{^arr}}
    <tr>
        <td colspan="4" class="text-center">${clientexec.lang('There are no services enabled')}</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) {
                        if ( !output.data || output.data.length === 0 ) {
                            $('#upcoming-events-table').html(
                                '<table class="table display"><tbody><tr><td class="text-center">' +
                                clientexec.lang('No upcoming events found') +
                                '</td></tr></tbody></table>'
                            );
                            return;
                        }
                        var items = {
                            headers: output.headers,
                            data: output.data,
                            extract: function() {
                                returnString = '';
                                var keys = Object.keys(this);
                                $.each(this, function(key, o) {
                                    var index = keys.indexOf(key);
                                    var label = output.headers[index] ? output.headers[index] : '';
                                    var alignClass = index > 0 ? ' class="text-center"' : '';
                                    returnString += '<td data-label="' + clientexec.lang(label) + '"' + alignClass + '>' + 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.tickets.getFavoriteTickets();
    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(e) {
        e.preventDefault();
        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 });
    });

    $(document).on('click', '.currency-dropdown .dropdown-item', function(e) {

        e.preventDefault();

        const currency = $(this).data('currency');
        const card = $(this).closest('.revenue-card');

        $.ajax({
            url: 'index.php?fuse=home&controller=index&action=getrevenuedata',
            type: 'GET',
            dataType: 'json',
            data: {
                currency: currency
            },
            success: function(response) {

                response = clientexec.parseResponse(response);

                card.find('.value').html(response.today);
                card.find('.prev').html('Yesterday : ' + response.yesterday);

                card.find('.dropdown-toggle').html(`
                ${currency}
            `);

                card.find('.dropdown-item').removeClass('active');

                card.find('.dropdown-item[data-currency="' + currency + '"]')
                    .addClass('active');
            }
        });

    });
});

</script>