<?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)
    {  
        
        /** @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 {

            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);
                        $periodStats = $stats->getStatData($report_type, $feed_id_list, $dates);
                        
                        $cats = [
                            'Views' => 'Показы',
                            'Clicks' => 'Клики',
                            'Orders' => 'Заказы',
                            'OrderSum' => 'Сумма по заказам',
                            'AdMoney' => 'Стоимость рекламы'
                        ];
                        
                        /*
                        $cats = [
                            'shows' => 'Показы',
                            'clicks' => 'Клики',
                            'transactions' => 'Транзакции',
                            'salemoney' => 'salemoney',
                            'admoney' => 'admoney'
                        ];

                        $campaignStats = $statsDaysModel->getStatsByFeeds($feed_id_list, $dates);
                        if ($campaignStats || count($campaignStats['period'])>0) {
                            $feeds_names = [];
                            foreach($campaignStats['period'] as $feed_id) {
                                $feed = $feedsModel->findById($feed_id);
                                $feeds_names[] = $feed->getTitle();
                            }
                            $campaignStats['period'] = $feeds_names;
                        }
                        */
                        
                        break;
                    /*
                    case 'transaction':
                        // @var \App\Model\Feeds $transactionsModel
                        $transactionsModel = $this->container->get(Transactions::class);
                        $transactionStats = $transactionsModel->getStatsByTransactions($feed_id_list, $dates);
                        $cats = [
                            'localmoney' => 'localmoney',
                            'usdollarmoney' => 'usdollarmoney'
                        ];
                        
                        if ($transactionStats || count($transactionStats['period'])>0) {
                            $transactions_names = [];
                            foreach($transactionStats['period'] as $transaction_id) {
                                $transactions_names[] = 'транзакция #'.$transaction_id;
                            }
                            $transactionStats['period'] = $transactions_names;
                        }
                        $periodStats = $transactionStats;
                        
                        break;
                    */
                    default:
                        $data['error'] = _t('Извините, тип отчета "'. $report_type .'" недоступен');
                        break;
                }

                /*
                $periodStats['type'] = 'interval';
                $periodStats['report'] = $report_type;
                
                $campaignStats['type'] = 'interval';
                $campaignStats['report'] = $report_type;
                $data['campaignStats'] = $campaignStats;
                */

                $data['feeds'] = $feeds;
                $data['report'] = $report_type;
                $data['current_period'] = $current_period;
                $data['dates'] = $dates;
                $data['periodStats'] = $periodStats;
                $data['cats'] = $cats;
                $data['periods_list'] = $this->container->get('config')['feed_conf']['periods_list'];
                $data['colors_active_lines'] = $this->container->get('config')['feed_conf']['colors_active_lines'];

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

            } 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\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'];
        
        switch ($report_type) {
            case 'common':
                /** @var \App\Model\Feeds $statDaysModel */
                //$statsDaysModel = $this->container->get(StatsDays::class);
                //$periodStats = $statsDaysModel->getStatsByDate($feed_id_list, $dates);
                $periodStats = $stats->getStatData($report_type, $feed_id_list, $dates);
                /*
                $campaignStats = $statsDaysModel->getStatsByFeeds($feed_id_list, $dates);
                
                if ($campaignStats || count($campaignStats['period'])>0) {
                    $feeds_names = [];
                    foreach($campaignStats['period'] as $feed_id) {
                        $feed = $feedsModel->findById($feed_id);
                        $feeds_names[] = $feed->getTitle();
                    }
                    $campaignStats['period'] = $feeds_names;
                }
                */
                break;
            case 'transaction':
                /** @var \App\Model\Feeds $transactionsModel */
                $transactionsModel = $this->container->get(Transactions::class);
                $transactionStats = $transactionsModel->getStatsByTransactions($feed_id_list, $dates);
                
                if ($transactionStats || count($transactionStats['period'])>0) {
                    $transactions_names = [];
                    foreach($transactionStats['period'] as $transaction_id) {
                        $transactions_names[] = 'транзакция #'.$transaction_id;
                    }
                    $transactionStats['period'] = $transactions_names;
                }
                $periodStats = $transactionStats;
                
                break;
            default:
                $periodStats = null;
                $campaignStats = null;
                break;
        }
        
        if (!$periodStats) {
            return new JsonResponse(null);
        }
        
        /*
        $periodStats['type'] = 'interval';
        $periodStats['report'] = $report_type;

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