<?php
$df = $tpl['option_arr']['o_date_format'];
$months = __('months', true);
ksort($months);
$short_days = __('short_days', true);
$current_year = (int) date('Y');
$active_from = $tpl['date_from'];
$active_to = $tpl['date_to'];
$context_year = (int) date('Y', strtotime($active_from));
$quarter_defs = array(
    'Q1' => array('01-01', '03-31'),
    'Q2' => array('04-01', '06-30'),
    'Q3' => array('07-01', '09-30'),
    'Q4' => array('10-01', '12-31'),
);
$js_periods = array();
for ($y = $current_year - 4; $y <= $current_year; $y++)
{
    $q_arr = array();
    foreach ($quarter_defs as $qlbl => $qr)
    {
        $from_db = $y . '-' . $qr[0];
        $to_db = $y . '-' . $qr[1];
        $q_arr[] = array(
            'label' => $qlbl . ' ' . $y,
            'value' => date($df, strtotime($from_db)) . '|' . date($df, strtotime($to_db)),
            'active' => $active_from === $from_db && $active_to === $to_db,
        );
    }
    $m_arr = array();
    foreach ($months as $m_num => $m_name)
    {
        $mp = str_pad($m_num, 2, '0', STR_PAD_LEFT);
        $ld = date('t', strtotime($y . '-' . $mp . '-01'));
        $from_db = $y . '-' . $mp . '-01';
        $to_db = $y . '-' . $mp . '-' . $ld;
        $m_arr[] = array(
            'label' => $m_name . ' ' . $y,
            'value' => date($df, strtotime($from_db)) . '|' . date($df, strtotime($to_db)),
            'active' => $active_from === $from_db && $active_to === $to_db,
        );
    }
    $js_periods[$y] = array(
        'from' => date($df, strtotime($y . '-01-01')),
        'to' => date($df, strtotime($y . '-12-31')),
        'quarters' => $q_arr,
        'months' => $m_arr,
    );
}

if (!function_exists('pjReportLabel'))
{
    function pjReportLabel($key, $fallback)
    {
        $label = __($key, true);
        return !empty($label) && $label !== $key ? $label : $fallback;
    }
}
?>

<div class="row wrapper border-bottom white-bg page-heading">
    <div class="col-sm-12">
        <h2><?php __('infoReportTitle', false, true); ?></h2>
        <p class="m-b-none">
            <i class="fa fa-info-circle"></i>
            <?php __('infoReportDesc', false, true); ?>
        </p>
    </div>
</div>

<div class="wrapper wrapper-content animated fadeInRight rpt-page">
    <div class="row">
        <div class="col-lg-12">
            <div class="ibox float-e-margins">
                <div class="ibox-content">
                    <form action="" method="get" id="frmReport" autocomplete="off">
                        <input type="hidden" name="controller" value="pjAdminReports" />
                        <input type="hidden" name="action" id="actionField" value="pjActionIndex" />

                        <div id="datePickerOptions" style="display:none;"
                             data-wstart="<?php echo (int) $tpl['option_arr']['o_week_start']; ?>"
                             data-format="<?php echo pjUtil::toBootstrapDate($df); ?>"
                             data-months="<?php echo implode('_', $months); ?>"
                             data-days="<?php echo implode('_', $short_days); ?>"></div>

                        <div class="rpt-filter">
                            <select id="quickYear" class="form-control" title="<?php echo htmlspecialchars(pjReportLabel('lblYear', 'Year'), ENT_QUOTES); ?>">
                                <?php for ($y = $current_year; $y >= $current_year - 4; $y--): ?>
                                    <option value="<?php echo $y; ?>"<?php echo $y == $context_year ? ' selected' : NULL; ?>><?php echo $y; ?></option>
                                <?php endfor; ?>
                            </select>

                            <select id="quickQuarter" class="form-control" title="<?php echo htmlspecialchars(pjReportLabel('lblQuarter', 'Quarter'), ENT_QUOTES); ?>">
                                <option value=""><?php echo htmlspecialchars(pjReportLabel('lblQuarter', 'Quarter'), ENT_QUOTES); ?></option>
                            </select>

                            <select id="quickMonth" class="form-control" title="<?php echo htmlspecialchars(pjReportLabel('lblMonth', 'Month'), ENT_QUOTES); ?>">
                                <option value=""><?php echo htmlspecialchars(pjReportLabel('lblMonth', 'Month'), ENT_QUOTES); ?></option>
                            </select>

                            <div class="rpt-date">
                                <div class="input-group">
                                    <span class="input-group-addon" title="<?php echo htmlspecialchars(pjReportLabel('lblFrom', 'From'), ENT_QUOTES); ?>"><i class="fa fa-calendar"></i></span>
                                    <input type="text" name="date_from" id="date_from" value="<?php echo date($df, strtotime($tpl['date_from'])); ?>" class="form-control" readonly>
                                    <span class="input-group-addon rpt-tm"><?php __('lblTo'); ?></span>
                                    <span class="input-group-addon" title="<?php echo htmlspecialchars(pjReportLabel('lblTo', 'To'), ENT_QUOTES); ?>"><i class="fa fa-calendar"></i></span>
                                    <input type="text" name="date_to" id="date_to" value="<?php echo date($df, strtotime($tpl['date_to'])); ?>" class="form-control" readonly>
                                </div>
                            </div>

                            <div class="rpt-btns">
                                <button type="submit" id="btnReport" class="btn"><i class="fa fa-bar-chart"></i> <?php __('btnReport'); ?></button>
                            </div>
                        </div>
                    </form>

                    <script>
                        var periodData = <?php echo json_encode($js_periods, JSON_HEX_TAG | JSON_HEX_APOS); ?>;
                        var actionInput = document.getElementById('actionField');
                        var yearSelect = document.getElementById('quickYear');
                        var quarterSelect = document.getElementById('quickQuarter');
                        var monthSelect = document.getElementById('quickMonth');

                        function populateDropdowns(year) {
                            var data = periodData[year];
                            if (!data) {
                                return;
                            }
                            quarterSelect.innerHTML = '<option value=""><?php echo pjSanitize::html(pjReportLabel('lblQuarter', 'Quarter')); ?></option>';
                            data.quarters.forEach(function (q) {
                                var opt = document.createElement('option');
                                opt.value = q.value;
                                opt.textContent = q.label;
                                if (q.active) {
                                    opt.selected = true;
                                }
                                quarterSelect.appendChild(opt);
                            });
                            monthSelect.innerHTML = '<option value=""><?php echo pjSanitize::html(pjReportLabel('lblMonth', 'Month')); ?></option>';
                            data.months.forEach(function (m) {
                                var opt = document.createElement('option');
                                opt.value = m.value;
                                opt.textContent = m.label;
                                if (m.active) {
                                    opt.selected = true;
                                }
                                monthSelect.appendChild(opt);
                            });
                        }

                        populateDropdowns(yearSelect.value);
                        yearSelect.addEventListener('change', function () {
                            var data = periodData[this.value];
                            if (!data) {
                                return;
                            }
                            populateDropdowns(this.value);
                            document.getElementById('date_from').value = data.from;
                            document.getElementById('date_to').value = data.to;
                            actionInput.value = 'pjActionIndex';
                            document.getElementById('frmReport').submit();
                        });

                        function handlePeriodChange() {
                            if (!this.value) {
                                return;
                            }
                            var parts = this.value.split('|');
                            document.getElementById('date_from').value = parts[0];
                            document.getElementById('date_to').value = parts[1];
                            actionInput.value = 'pjActionIndex';
                            document.getElementById('frmReport').submit();
                        }
                        quarterSelect.addEventListener('change', handlePeriodChange);
                        monthSelect.addEventListener('change', handlePeriodChange);
                    </script>

                    <div class="rpt-section-title"><?php echo htmlspecialchars(pjReportLabel('lblKeyMetrics', 'Key metrics'), ENT_QUOTES); ?></div>

                    <div class="rpt-kpi-grid">
                        <div class="rpt-kpi-card">
                            <div class="rpt-kpi-label"><?php __('lblUpTotalOrders'); ?></div>
                            <div class="rpt-kpi-value">
                                <?php if ($tpl['total_orders'] > 0 && pjAuth::factory('pjAdminOrders', 'pjActionIndex')->hasAccess()): ?>
                                    <a href="<?php echo $_SERVER['PHP_SELF']; ?>?controller=pjAdminOrders&amp;action=pjActionIndex&amp;status=completed&amp;date_from=<?php echo date($df, strtotime($tpl['date_from'])); ?>&amp;date_to=<?php echo date($df, strtotime($tpl['date_to'])); ?>"><?php echo (int) $tpl['total_orders']; ?></a>
                                <?php else: ?>
                                    <?php echo (int) $tpl['total_orders']; ?>
                                <?php endif; ?>
                            </div>
                        </div>

                        <div class="rpt-kpi-card">
                            <div class="rpt-kpi-label"><?php __('lblTotalAmount'); ?></div>
                            <div class="rpt-kpi-value"><?php echo pjCurrency::formatPrice($tpl['total_amount']); ?></div>
                        </div>

                        <div class="rpt-kpi-card rpt-kpi-accent">
                            <div class="rpt-kpi-label"><?php __('lblUniqueClients'); ?></div>
                            <div class="rpt-kpi-value">
                                <?php if ($tpl['unique_clients'] > 0 && pjAuth::factory('pjAdminClients', 'pjActionIndex')->hasAccess()): ?>
                                    <a href="<?php echo $_SERVER['PHP_SELF']; ?>?controller=pjAdminClients&amp;action=pjActionIndex&amp;client_ids=<?php echo $tpl['unique_client_ids']; ?>"><?php echo (int) $tpl['unique_clients']; ?></a>
                                <?php else: ?>
                                    <?php echo (int) $tpl['unique_clients']; ?>
                                <?php endif; ?>
                            </div>
                        </div>

                        <div class="rpt-kpi-card rpt-kpi-accent">
                            <div class="rpt-kpi-label"><?php __('lblFirstTimeClients'); ?></div>
                            <div class="rpt-kpi-value">
                                <?php if ($tpl['first_time_clients'] > 0 && pjAuth::factory('pjAdminClients', 'pjActionIndex')->hasAccess()): ?>
                                    <a href="<?php echo $_SERVER['PHP_SELF']; ?>?controller=pjAdminClients&amp;action=pjActionIndex&amp;client_ids=<?php echo $tpl['first_time_client_ids']; ?>"><?php echo (int) $tpl['first_time_clients']; ?></a>
                                <?php else: ?>
                                    <?php echo (int) $tpl['first_time_clients']; ?>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>

                    <div class="rpt-subsection-title"><?php echo htmlspecialchars(pjReportLabel('lblOrderAmounts', 'Order amounts'), ENT_QUOTES); ?></div>
                    <div class="rpt-stat-grid">
                        <div class="rpt-stat-card">
                            <div class="rpt-stat-label"><?php __('lblAvgOrderAmount'); ?></div>
                            <div class="rpt-stat-value"><?php echo pjCurrency::formatPrice($tpl['avg_amount']); ?></div>
                        </div>
                        <div class="rpt-stat-card">
                            <div class="rpt-stat-label"><?php __('lblMinOrderAmount'); ?></div>
                            <div class="rpt-stat-value"><?php echo pjCurrency::formatPrice($tpl['min_amount']); ?></div>
                        </div>
                        <div class="rpt-stat-card">
                            <div class="rpt-stat-label"><?php __('lblMaxOrderAmount'); ?></div>
                            <div class="rpt-stat-value"><?php echo pjCurrency::formatPrice($tpl['max_amount']); ?></div>
                        </div>
                    </div>

                    <div class="rpt-subsection-title"><?php echo htmlspecialchars(pjReportLabel('lblProductsPerOrder', 'Products per order'), ENT_QUOTES); ?></div>
                    <div class="rpt-stat-grid">
                        <div class="rpt-stat-card">
                            <div class="rpt-stat-label"><?php __('lblAverageProductsPerOrder'); ?></div>
                            <div class="rpt-stat-value"><?php echo number_format($tpl['avg_product'], 2, '.', ' '); ?></div>
                        </div>
                        <div class="rpt-stat-card">
                            <div class="rpt-stat-label"><?php __('lblMinProductsPerOrder'); ?></div>
                            <div class="rpt-stat-value"><?php echo (int) $tpl['min_product']; ?></div>
                        </div>
                        <div class="rpt-stat-card">
                            <div class="rpt-stat-label"><?php __('lblMaxProductsPerOrder'); ?></div>
                            <div class="rpt-stat-value"><?php echo (int) $tpl['max_product']; ?></div>
                        </div>
                        <div class="rpt-stat-card">
                            <div class="rpt-stat-label"><?php __('lblMostPopularProduct'); ?></div>
                            <div class="rpt-stat-value rpt-stat-value-sm">
                                <?php
                                if (!empty($tpl['popular_arr']['name']))
                                {
                                    if (pjAuth::factory('pjAdminProducts', 'pjActionUpdate')->hasAccess())
                                    {
                                        ?><a href="<?php echo $_SERVER['PHP_SELF']; ?>?controller=pjAdminProducts&amp;action=pjActionUpdate&amp;id=<?php echo $tpl['popular_arr']['id']; ?>"><?php echo pjSanitize::html($tpl['popular_arr']['name']); ?></a><?php
                                    } else {
                                        echo pjSanitize::html($tpl['popular_arr']['name']);
                                    }
                                    echo '<span class="rpt-muted"> / ' . str_replace('{NUM}', $tpl['times'], __('lblSoldTimes', true)) . '</span>';
                                } else {
                                    ?><span class="rpt-muted"><?php echo htmlspecialchars(pjReportLabel('lblNoRecordsFound', 'No records found'), ENT_QUOTES); ?></span><?php
                                }
                                ?>
                            </div>
                        </div>
                    </div>

                    <div class="rpt-section-title"><?php echo htmlspecialchars(pjReportLabel('lblBreakdown', 'Breakdown'), ENT_QUOTES); ?></div>
                    <div class="rpt-vat-table-wrap">
                        <table class="rpt-vat-table">
                            <thead>
                                <tr>
                                    <th><?php __('lblProductsPrice'); ?></th>
                                    <th><?php __('order_discount'); ?></th>
                                    <th><?php __('order_insurance'); ?></th>
                                    <th><?php __('order_shipping'); ?></th>
                                    <th><?php __('order_tax'); ?></th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td><?php echo pjCurrency::formatPrice($tpl['sub_arr']['price']); ?></td>
                                    <td><?php echo pjCurrency::formatPrice($tpl['sub_arr']['discount']); ?></td>
                                    <td><?php echo pjCurrency::formatPrice($tpl['sub_arr']['insurance']); ?></td>
                                    <td><?php echo pjCurrency::formatPrice($tpl['sub_arr']['shipping']); ?></td>
                                    <td><?php echo pjCurrency::formatPrice($tpl['sub_arr']['tax']); ?></td>
                                </tr>
                            </tbody>
                            <tfoot>
                                <tr>
                                    <td colspan="4"><?php __('lblTotalAmount'); ?></td>
                                    <td><?php echo pjCurrency::formatPrice($tpl['total_amount']); ?></td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
