<?php
/**
 * Ajax handler for Shop dashboard stats.
 * requires section & start/end date as params
 * returns JSON response.
 * Built to speed up admin dashboard.
 *
 * @author Martins Fridenbergs <martins.fridenbergs@mtcmedia.co.uk>
 * @version 2017-02-05
 */

use Carbon\Carbon;
use Mtc\Core\Response;
use Mtc\Shop\Sales;

$path = '../../';
require_once $path . 'core/includes/header.inc.php';

$html = '';
$action = filter_input(INPUT_GET, 'section');
$start_date = date('d/m/Y', time());
if (!in_array(filter_input(INPUT_GET, 'start_date'), ['false', null])) {
    $start_date = filter_input(INPUT_GET, 'start_date');
}
$end_date = date('d/m/Y', time());
if (!in_array(filter_input(INPUT_GET, 'end_date'), ['false', null])) {
    $end_date = filter_input(INPUT_GET, 'end_date');
}

$options = [
    'start_date' => date_convert_dmy_to_db($start_date, '00:00:00'),
    'end_date' => date_convert_dmy_to_db($end_date, '23:59:59')
];
$startDate = Carbon::createFromFormat('d/m/Y', $start_date);
$endDate = Carbon::createFromFormat('d/m/Y H:i:s', $end_date . ' 23:59:59' );

$sales = new Sales($startDate, $endDate);
$sales->getTotalSalesRevenuePerDay();

switch ($action) {
    case 'sales_numbers':
        $revenue = $sales->getTotalSalesRevenue();
        $refundAmount = $sales->getRefundAmount();
        $html = $twig->render('shop/admin/dashboard/sales.twig', [
            'order_value' => $revenue,
            'average_order_value' => $sales->getAverageOrderValue(),
            'refunds_total' => $refundAmount,
            'sale_value' => $revenue - $refundAmount,
            'average_sales_value' => $sales->getTotalSalesRevenuePerDay(),
        ]);
        $response = [
            'html' => $html
        ];
        break;
    case 'order_numbers':
        $order_count = $sales->getNumberOfOrders();
        $item_count = $sales->getNumberOfItemsSold();
        $items_returned = $sales->getNumberOfItemsRefunded();

        $html = $twig->render('shop/admin/dashboard/orders.twig', [
            'order_count' => $sales->getNumberOfOrders(),
            'item_count' => $item_count,
            'items_returned' => $items_returned,
            'return_percentage' => $item_count > 0 ? $items_returned / $item_count * 100 : 0,
            'avg_items_per_order' => $order_count > 0 ?
                $item_count / $order_count:
                0,
            'avg_orders_per_day' => $sales->getNumberOfOrdersPerDay(),
        ]);

        $response = [
            'html' => $html
        ];
        break;
    case 'weekly_sales':

        $html = [
            ['Day', 'Sales (GBP)', '1 Year Ago']
        ];

        for ($i = 7; $i > 0; $i--) {
            $startDate = Carbon::now()->startOfDay()->subDays($i);
            $endDate = Carbon::now()->endOfDay()->subDays($i);
            $sales = new Sales($startDate, $endDate);
            $row = [
                $startDate->format('M jS'),
                $sales->getTotalSalesRevenue()
            ];
            $startDate->subYear();
            $endDate->subYear();
            $sales = new Sales($startDate, $endDate);
            $row[] = $sales->getTotalSalesRevenue();
            $html[] = $row;
        }

        $response = [
            'data' => $html
        ];
        break;
    case 'monthly_sales':

        $html = [
            ['Month', 'Sales (GBP)', '1 Year Ago']
        ];

        for ($i = 6; $i >= 1; $i--) {
            $startDate = Carbon::now()->startOfMonth()->subMonths($i);
            $endDate = Carbon::now()->startOfMonth()->subMonths($i)->endOfMonth();
            $sales = new Sales($startDate, $endDate);

            $row = [
                $startDate->format('M'),
                $sales->getTotalSalesRevenue()
            ];
            $startDate->subYear();
            $endDate->subYear();
            $sales = new Sales($startDate, $endDate);
            $row[] = $sales->getTotalSalesRevenue();
            $html[] = $row;
        }

        $response = [
            'data' => $html
        ];
        break;
}

if (!empty($response)) {
    Response::outputJson('ok', $response);
    exit();
}
http_response_code(400);
