<?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 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 ViewId
 * @package App\Action\User
 */
class ViewId extends Common
{
    const ACTION_STAT = 'stat';
    const STAT_CATS = array(
        'StartTime' => 'StartTime',
        'EndTime' => 'EndTime',
        'IP' => 'IP',
        'Basket' => 'Состав корзины',
        'Pages' => 'Pages',
        //'TransactionID' => 'TransactionID',
        'ForeignID' => 'ForeignID',
        'OrderSum' => 'OrderSum',
    );

    /**
     * @param ServerRequestInterface $request
     * @param ResponseInterface $response
     * @param callable|null $next
     * @return HtmlResponse
     */
    function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null)
    {  
        
        /** @var \App\Model\Statistics $stats */
        $stats = $this->container->get(Statistics::class);
        
        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 {

            /*
            $feed_id = $request->getAttribute('feedid');
            $view_id = $request->getAttribute('id');
            
            $viewIdStats = $stats->getViewIdStatData($feed_id, $view_id);
            return new JsonResponse($viewIdStats);    
            */
            
            try {
                
                $feed_id = $request->getAttribute('feedid');
                $view_id = $request->getAttribute('id');
                
                /** @var UserService $auth */
                $auth = $this->container->get(UserService::class);
                $userId = $auth->getIdentity()->getId();

                /** @var \App\Model\Feeds $feedsModel */
                $feedsModel = $this->container->get(Feeds::class);
                $feed_item = $feedsModel->findById($feed_id);
                
                if ($feed_item) {
                    
                    if ($feed_item->getClientid() == $userId){
                        
                        // Статистика-история по клику:
                        $viewIdStats = $stats->getViewIdStatData($feed_id, $view_id);
                        $data['viewIdStats'] = $viewIdStats;
                        $data['cats'] = self::STAT_CATS;
                        
                    } else {
                        $data['error'] = _t('Извините, данный фид закреплен за другим пользователем');
                    }
                    
                } else {
                    $data['error'] = _t('Извините, фид не найден');
                }
                
            } 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-click-history', $data));
        }
    }
    
    private function getStatData(ServerRequestInterface $request) 
    {
        /** @var UserService $auth */
        $auth = $this->container->get(UserService::class);
        $userId = $auth->getIdentity()->getId();
        
        /** @var \App\Model\Statistics $stats */
        $stats = $this->container->get(Statistics::class);
        
        // Выводим стр. по фидам, если за пользователем закреплен фид:
        /** @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'];
        
        $report_conf = $this->container->get('config')['feed_conf']['reports'][$report_type];
        
        switch ($report_type) {
            case 'common':
                $periodStats = $stats->getFeedStatData($report_type, $feed_id_list, $dates, $report_conf);
                //$campaignStats = $statsDaysModel->getStatsByFeeds($feed_id_list, $dates);
                break;
            case 'transaction':
                $periodStats = $stats->getFeedStatData($report_type, $feed_id_list, $dates, $report_conf);
                break;
            default:
                $periodStats = null;
                $campaignStats = null;
                break;
        }
        
        if (!$periodStats) {
            return new JsonResponse(null);
        }
        
        /*
        if ($periodStats || $companyStats) {
            $data = array(
                'period' => $periodStats,
                'campaign' => $campaignStats,
            );
        } else {
            $data = null;
        }
        */
        
        $data = $periodStats;
        
        return new JsonResponse($data);
    }
    
}