<?php
/**
 *
 * User: Artur Pilch <artur.pi@modulesgarden.com>
 * Date: 2018-08-07
 * Time: 12:00
 */

namespace ModulesGarden\HostingQuotaNotifications\App\Helper\Home;

use ModulesGarden\HostingQuotaNotifications\App\Helper\Lang\Lang;
use ModulesGarden\HostingQuotaNotifications\App\Helper\Logger\ModuleAction;
use ModulesGarden\HostingQuotaNotifications\App\Helper\Logger\OpenTicket;
use ModulesGarden\HostingQuotaNotifications\Core\Models\Logger\Model as LoggerModel;

/**
 * Class Sort
 *
 * @author Artur Pilch <artur.pi@modulesgarden.com>
 */
class Sort
{
    CONST TODAY = 'today';
    CONST WEEK  = 'week';
    CONST MONTH = 'month';

    public static function getData()
    {
        return self::sort(self::getSortedByGlobalTypes());
    }

    public static function getSortedByGlobalTypes()
    {
        return [
            SELF::TODAY => LoggerModel::whereRaw('DATE_FORMAT(date, "%Y-%m-%d") = CURDATE()')->get(),
            SELF::WEEK  => LoggerModel::whereRaw('DATE_FORMAT(date, "%Y-%m-%d") BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND CURDATE()')->get(),
            SELF::MONTH => LoggerModel::whereRaw('MONTH(date) = MONTH(CURRENT_DATE())')
                ->whereRaw('YEAR(date) = YEAR(CURRENT_DATE())')
                ->get(),
        ];
    }

    public static function sort($data)
    {
        $out = [];
        foreach ($data as $key => $logs)
        {
            $out[Lang::getAbsoulteLang('home', $key)] = self::countByMessageName($logs);
        }
        return $out;
    }

    public static function countByMessageName($logs)
    {
        $skip = Data::getMessagesType();
        $out  = Data::setOut();
        foreach ($logs as $log)
        {
            $log->response = json_decode($log->response);
            $log->response->message_base = self::replaceMessageName($log->response->message_base);
            if (!in_array($log->response->message_base, $skip))
            {
                continue;
            }
            $out[$log->response->message_base][$log->type] += 1;
        }
        return $out;
    }

    public static function replaceMessageName($message)
    {
        $toReplace = [
            OpenTicket::NO_LANG => OpenTicket::OPEN_TICKET
        ];

        if(isset($toReplace[$message]))
        {
            return $toReplace[$message];
        }
        return $message;
    }


}