<?php
/**
 * Copyright (c) 2016 Serhii Borodai <clarifying@gmail.com>.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 *
 */

namespace App\Action\User;


use App\Action\Common;
use App\Authentication\UserService;
use App\Model\Users;
use App\Model\Statistics;
use App\Model\Providers;
use App\Model\Feeds\Feeds;
use App\Model\Feeds\StatsDays;
use App\Model\Feeds\Transactions;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Zend\Diactoros\Response\HtmlResponse;
use Zend\Diactoros\Response\JsonResponse;
use Zend\Diactoros\Response\RedirectResponse;


/**
 * Class Cabinet
 * @package App\Action\User
 */
class Cabinet extends Common
{
    const ACTION_STAT = 'stat';

    /**
     * @param ServerRequestInterface $request
     * @param ResponseInterface $response
     * @param callable|null $next
     * @return HtmlResponse
     */
    function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null)
    {  
        
        if($request->getMethod() == 'POST') {
            
            try {
                switch ($request->getAttribute('action')) {
                    case self::ACTION_STAT:
                        $response = $this->getStatData($request);
                        break;
                    default:
                }
            } catch(\Exception $e) {
                $data = [
                    'result' => false,
                    'msg' => $e->getMessage(),
                ];
                $response = new JsonResponse($data);
            }
            return $response;
            
        } else {

            try {

                /** @var UserService $auth */
                $auth = $this->container->get(UserService::class);
                $userId = $auth->getIdentity()->getId();

                /** @var \App\Model\Feeds $feedsModel */
                $feedsModel = $this->container->get(Feeds::class);
                $feeds = $feedsModel->findAll(['clientid' => $userId])->toArray();

                // Фиды пользователя:
                $feed_id_list = [];
                foreach($feeds as $feed_item) {
                    $feed_id = $feed_item['id'];
                    if (!in_array($feed_id, $feed_id_list)) {
                        $feed_id_list[] = $feed_id;
                    }
                }         

                $report_type = $request->getAttribute('report');

                // Текущий месяц:
                $current_period = 'current_month';
                $dates = [date('Y-m-01'), date('Y-m-d')];

                switch ($report_type) {
                    case 'common':
                        /** @var \App\Model\Feeds $statDaysModel */
                        $statsDaysModel = $this->container->get(StatsDays::class);
                        //$stats = $statsDaysModel->findAll(['FeedID' => $feed_id_list])->toArray();
                        $periodStats = $statsDaysModel->getStatsByDate($feed_id_list, $dates);
                        $companyStats = $statsDaysModel->getStatsByFeeds($feed_id_list, $dates);
                        $cats = ['shows','clicks','transactions','salemoney','admoney'];
                        break;
                    case 'transaction':
                        /** @var \App\Model\Feeds $transactionsModel */
                        $transactionsModel = $this->container->get(Transactions::class);
                        $periodStats = $transactionsModel->getStatsByDate($feed_id_list, $dates);
                        $companyStats = $transactionsModel->getStatsByFeeds($feed_id_list, $dates);
                        $cats = ['localmoney','usdollarmoney'];
                        break;
                    default:
                        $data['error'] = _t('Извините, тип отчета "'. $report_type .'" недоступен');
                        break;
                }
                
                if ($companyStats || count($companyStats['period'])>0) {
                    $feeds_names = [];
                    foreach($companyStats['period'] as $feed_id) {
                        $feed = $feedsModel->findById($feed_id);
                        $feeds_names[] = $feed->getTitle();
                    }
                    $companyStats['period'] = $feeds_names;
                }
                //return new JsonResponse($companyStats);
                
                $periodStats['type'] = 'interval';
                $periodStats['report'] = $report_type;

                $companyStats['type'] = 'interval';
                $companyStats['report'] = $report_type;

                $data['feeds'] = $feeds;
                $data['report'] = $report_type;
                $data['current_period'] = $current_period;
                $data['dates'] = $dates;
                $data['periodStats'] = $periodStats;
                $data['companyStats'] = $companyStats;
                $data['cats'] = $cats;

                /*
                $response =  new HtmlResponse($this->template->render('app::user/feeds', [
                    'lang' => $request->getAttribute('layoutInfo')->getLang(),
                    'feeds' => $feeds,
                    'stats' => $stats,
                ]));
                return $response;
                */

                /*
                $allDomains = $listDomains;

                $subdomains = true;
                $allStat = false;
                $group = false;

                $summaryReport = $stats->getSummuryReport($allDomains, $user->getCurrencyCode(), $subdomains, $allStat, $group);                                
                list($periodStats, $periodDates) = $stats->getPeriodReport(date('Y-m'), $allDomains, $user->getCurrencyCode(), $subdomains, $allStat, $group);

                $dateIterval = new \DateInterval('P1M');                
                $dateStart = \DateTime::createFromFormat('Y-m-d', $periodDates['min'] ?: date('Y-m-01'));
                $dateEnd = \DateTime::createFromFormat('Y-m-d', $periodDates['max'] ?: date('Y-m-01'));              

                $dateRange = array();
                if($dateStart != $dateEnd) {
                    $_dateRange = new \DatePeriod($dateStart, $dateIterval, $dateEnd);                         
                    foreach($_dateRange as $dt) {
                        $dateRange[] = $dt;
                    }         
                }
                $dateRange[] = $dateEnd;
                $dateRange = array_reverse($dateRange);

                $currencyModel = $this->container->get(\App\Model\Currencies::class);
                $currencies = array();
                foreach($currencyModel->findAll() as $currency) {
                    $currencies[$currency->getCode()] = $currency->getName();
                }
                $currentCurencyCode = $user->getCurrencyCode();

                $data['sites'] = $listSites;
                $data['accessSites'] = $listAccessSites;
                $data['summaryStats'] = $summaryStats;
                $data['periodStats'] = $periodStats;
                $data['summaryReport'] = $summaryReport;
                $data['listDomains'] = $listDomains;
                $data['dateRange'] = $dateRange;        
                $data['currencies'] = $currencies;
                $data['currency'] = ['code' => $currentCurencyCode, 'name' => $currencies[$currentCurencyCode]];
                $data['userId'] = $userId;

                */

            } catch(\Exception $e) {
                $data['error'] = _t('Извините, статистика временно не работает');
            }

            $data = array_merge($data, [
                'lang' => $request->getAttribute('layoutInfo')->getLang(),
                'layoutInfo' => $request->getAttribute('layoutInfo'),
            ]);     

            return new HtmlResponse($this->template->render('app::user/cabinet-feed', $data));

        }
    }
    
    private function getStatData(ServerRequestInterface $request) 
    {
        /** @var UserService $auth */
        $auth = $this->container->get(UserService::class);
        $userId = $auth->getIdentity()->getId();
        
        // Выводим стр. по фидам, если за пользователем закреплен фид:
        /** @var \App\Model\Feeds $feedsModel */
        $feedsModel = $this->container->get(Feeds::class);
        $feeds = $feedsModel->findAll(['clientid' => $userId])->toArray();
        
        // Фиды пользователя:
        $feed_id_list = [];
        foreach($feeds as $feed_item) {
            $feed_id = $feed_item['id'];
            if (!in_array($feed_id, $feed_id_list)) {
                $feed_id_list[] = $feed_id;
            }
        }         
        
        $report_type = $request->getAttribute('report');
        $data_request = $request->getParsedBody();
        $dates = $data_request['period'];
        
        switch ($report_type) {
            case 'common':
                /** @var \App\Model\Feeds $statDaysModel */
                $statsDaysModel = $this->container->get(StatsDays::class);
                $periodStats = $statsDaysModel->getStatsByDate($feed_id_list, $dates);
                $companyStats = $statsDaysModel->getStatsByFeeds($feed_id_list, $dates);
                break;
            case 'transaction':
                /** @var \App\Model\Feeds $transactionsModel */
                $transactionsModel = $this->container->get(Transactions::class);
                $periodStats = $transactionsModel->getStatsByDate($feed_id_list, $dates);
                $companyStats = $transactionsModel->getStatsByFeeds($feed_id_list, $dates);
                break;
            default:
                $periodStats = null;
                $companyStats = null;
                break;
        }
        
        $periodStats['type'] = 'interval';
        $periodStats['report'] = $report_type;

        $companyStats['type'] = 'interval';
        $companyStats['report'] = $report_type;
        
        if ($periodStats || $companyStats) {
            $data = array(
                'period' => $periodStats,
                'company' => $companyStats,
            );
        } else {
            $data = null;
        }
        return new JsonResponse($data);
    }
    
}