<?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 Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Zend\Diactoros\Response\HtmlResponse;
use Zend\Diactoros\Response\RedirectResponse;


/**
 * Class Cabinet
 * @package App\Action\User
 */
class Cabinet extends Common
{
    /**
     * @var Mailer
     */
    protected $mailer;

    /**
     * @param ServerRequestInterface $request
     * @param ResponseInterface $response
     * @param callable|null $next
     * @return HtmlResponse
     */
    function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null)
    {  
        try {
        
            /** @var UserService $auth */
            $auth = $this->container->get(UserService::class);
        
            /** @var Statistics $stats */
            $stats = $this->container->get(Statistics::class);
            
            /** @var Users $usersModel */
            $usersModel = $this->container->get(Users::class);
            
            $userId = $auth->getIdentity()->getId();
            $user = $usersModel->findById($userId);
            
            // Выводим стр. по фидам, если за пользователем закреплен фид:
            /** @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;
                }
            }         
            
            /** @var \App\Model\Feeds $statDaysModel */
            $statsDaysModel = $this->container->get(StatsDays::class);
            $stats = $statsDaysModel->findAll(['FeedID' => $feed_id_list])->toArray();
            
            $periodStats = array(
                'period' => [],
                'shows' => $stat_item['shows'],
                'clicks' => $stat_item['clicks'],
                'transactions' => $stat_item['transactions'],
                'salemoney' => $stat_item['salemoney'],
                'admoney' => $stat_item['admoney'],
                'type' => 'interval'
            );
            foreach($stats as $stat_item) {
                $periodStats['period'][] = $stat_item['eventdate'];
                $periodStats['shows'][] = $stat_item['shows'];
                $periodStats['clicks'][] = $stat_item['clicks'];
                $periodStats['transactions'][] = $stat_item['transactions'];
                $periodStats['salemoney'][] = $stat_item['salemoney'];
                $periodStats['admoney'][] = $stat_item['admoney'];
            }
            
            $dates = ['2018-10-09', '2018-11-09'];
            
            $data['feeds'] = $feeds;
            $data['periodStats'] = $periodStats;
            //$data['periodStats'] = $stats;
            $data['dates'] = $dates;
            
            /*
            $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', $data));
        return new HtmlResponse($this->template->render('app::user/cabinet-feed', $data));
    }
}