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

/**
 * Class CabinetAmSystem
 * @package App\Action\User
 */
class CabinetAmSystem extends Common
{
    const ACTION_LIST = 'list';
    const ACTION_ITEM = 'item';
    
    const CAMPAIGN_STAT_CATS = [
        'views'         =>  ['title' => 'Показы',   'color' => '#2CA02C'],
        'clicks'        =>  ['title' => 'Клики',    'color' => '#D62728'],
        'reach'         =>  ['title' => 'Охват',    'color' => '#FF7F0E'],
        'ctr'           =>  ['title' => 'CTR',      'color' => '#9467BD'],
        'cpm'           =>  ['title' => 'eCPM',     'color' => '#33C7B6'],
        'cpc'           =>  ['title' => 'eCPC',     'color' => '#7CADE2'],
        'money'         =>  ['title' => 'Расход',   'color' => '#1F77B4'],
        'order_cnt'     =>  ['title' => 'Заказы',   'color' => '#A4BA00'],
        'order_money'   =>  ['title' => 'Доход',   'color' => '#BA3A9E'],
    ];
    const IMG_DOMAIN_DEV = 'https://addcpm.app.dev.rew.to';
    const IMG_DOMAIN_PROD = 'https://www.addcpm.com';

    /**
     * @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_ITEM:
                        $response = $this->getStatData($request);
                        break;
                    default:
                }
            } catch(\Exception $e) {
                $data = [
                    'result' => false,
                    'msg' => $e->getMessage(),
                ];
                $response = new JsonResponse($data);
            }
            return $response;
            
        }
        elseif($request->getAttribute('action') == self::ACTION_LIST)
        {
            
            try {

                /** @var UserService $auth */
                $auth = $this->container->get(UserService::class);
                $userId = $auth->getIdentity()->getId();
                
                /** @var \App\Model\AmSystem\Groups $groupsModel */
                $groupsModel = $this->container->get(\App\Model\AmSystem\Groups::class);
                $groups = $groupsModel->findAll(['user_id' => $userId])->toArray();
                
                if ($groups) {
                    
                    /** @var \App\Model\AmSystem\Campaigns $campaignsModel */
                    $campaignsModel = $this->container->get(\App\Model\AmSystem\Campaigns::class);
                    
                    /** @var \App\Model\Statistics $stats */
                    $stats = $this->container->get(\App\Model\Statistics::class);
                    $campaigns_stat = [];
                    
                    $groups_campaigns = [];
                    foreach($groups as $group) {
                        $campaigns = $campaignsModel->findAll(['group_id' => $group['id']])->toArray();
                        $groups_campaigns[$group['id']] = $campaigns;
                    
                        foreach ($campaigns as $campaign_item) {
                            $campaign_id = $campaign_item['id'];
                            $campaigns_stat[$campaign_id] = $stats->getCampaignsStat([$campaign_id], $campaign_item['target_action'], null, false);
                        }
                    }
                    
                    $data['groups'] = $groups;
                    $data['campaigns'] = $campaigns;
                    $data['groups_campaigns'] = $groups_campaigns;
                    $data['stats'] = $campaigns_stat;
                    
                } 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/campaigns_list', $data));
        }
        elseif($request->getAttribute('action') == self::ACTION_ITEM)
        {
            $campaign_id = $request->getAttribute('id');
            
            /** @var UserService $auth */
            $auth = $this->container->get(UserService::class);
            $userId = $auth->getIdentity()->getId();
            
            /** @var \App\Model\AmSystem\Groups $groupsModel */
            $groupsModel = $this->container->get(\App\Model\AmSystem\Groups::class);
            
            /** @var \App\Model\AmSystem\Campaigns $campaignsModel */
            $campaignsModel = $this->container->get(\App\Model\AmSystem\Campaigns::class);
            $campaign_item = $campaignsModel->findById($campaign_id);
            
            if ($campaign_item) {

                $group_id = $campaign_item->getGroupId();
                $group = $groupsModel->findOne(['id' => $group_id]);
                
                if ($group->getUserId() == $userId){
                    
                    $countries = $this->container->get('config')['amsystem_conf']['country'];
                    $regions = $this->container->get('config')['amsystem_conf']['region'];
                    $cities = $this->container->get('config')['amsystem_conf']['city'];

                    /** @var \App\Model\AmSystem\Campaigns $campaignsModel */
                    //$campaignsModel = $this->container->get(\App\Model\AmSystem\Campaigns::class);
                    //$campaign = $campaignsModel->findOne(['id' => $campaign_id]);
                    $campaign = $campaign_item;

                    /** @var \App\Model\Statistics $stats */
                    $stats = $this->container->get(\App\Model\Statistics::class);
                    $date_begin = $campaign->getDateBegin();
                    $date_end_common = $campaign->getDateEnd() ? : null;
                    $date_end = $campaign->getDateEnd() ? : date("Y-m-d");
                    $dates_common = [$date_begin, $date_end_common];
                    $dates = [$date_begin, $date_end];
                    $campaign_stat = $stats->getCampaignsStat([(int)$campaign_id], $campaign->getTargetAction(), $dates_common, true);
                    $campaign_stat_total = $stats->getCampaignsStat([(int)$campaign_id], $campaign->getTargetAction(), $dates_common, false);
                    
                    $active_line = 'views';
                    
                    $campaign_banners_id = $campaign->getBanners();
                    if ($campaign_banners_id) {
                        $banners_id = json_decode($campaign_banners_id);

                        /** @var \App\Model\AmSystem\Banners $bannersModel */
                        $bannersModel = $this->container->get(\App\Model\AmSystem\Banners::class);
                        $banners = $bannersModel->findAll(['id' => $banners_id])->toArray();

                        /** @var \App\Model\Statistics $stats */
                        $stats = $this->container->get(\App\Model\Statistics::class);
                        
                        $banners_stats = [];
                        foreach ($banners as $banner_item) {
                            $banner_id = $banner_item['id'];
                            $banners_stats[$banner_id] = $stats->getBannersStat([$banner_id], $campaign->getTargetAction(), null);
                            /*
                            $banners_stats[$banner_id] = $stats->getBannersStat([$banner_id], null);
                            if ($campaign->getTargetAction() == 'load') {
                                $banners_stats[$banner_id]['views'] = $banners_stats[$banner_id]['loads'];
                            } else {
                            }

                            $views = $banners_stats[$banner_id]['views'];
                            $money = $banners_stats[$banner_id]['money'];
                            $clicks = $banners_stats[$banner_id]['clicks'];

                            $banners_stats[$banner_id]['ctr'] = ($views != 0) ? round(($clicks/$views)*100, 2) : 0;
                            $banners_stats[$banner_id]['cpm'] = ($views != 0) ? round(($money/$views)*1000, 3) : 0;
                            $banners_stats[$banner_id]['cpc'] = ($clicks != 0) ? round(($money/$clicks), 1) : 0;

                            $banners_stats[$banner_id]['money'] = round($banners_stats[$banner_id]['money'], 2);
                            */
                        }

                    }
                    
                    $sites_stats = $stats->getCampaignsSitesStat((int)$campaign_id, $campaign->getTargetAction(), $dates);
                    $regions_stats = $stats->getCampaignsRegionsStat((int)$campaign_id, $campaign->getTargetAction(), $dates);
                    
                    // Добавляем размер зоны в данные по сайтам:
                    /** @var \App\Model\Zones $zonesModel */
                    $zonesModel = $this->container->get(\App\Model\Zones::class);
                    
                    foreach ($sites_stats as $site_name => $site_data) {
                        if ($site_data['sub']) {
                            foreach ($site_data['sub'] as $zone_id => $zone_data) {
                                $zone = $zonesModel->findById($zone_id);
                                if ($zone) {
                                    $zone_width = $zone->getWidth();
                                    $zone_height = $zone->getHeight();
                                    $zone_size = $zone_width.'x'.$zone_height;
                                } else {
                                    $zone_size = null;
                                }
                                $sites_stats[$site_name]['sub'][$zone_id]['size'] = $zone_size;
                            }
                        }
                    }
                            
                    $data['campaign'] = $campaign;
                    $data['countries'] = $countries;
                    $data['regions'] = $regions;
                    $data['cities'] = $cities;
                    $data['banners'] = $banners;
                    $data['banners_stats'] = $banners_stats;
                    $data['sites_stats'] = $sites_stats;
                    $data['regions_stats'] = $regions_stats;
                    $data['campaign_stat'] = $campaign_stat;
                    $data['campaign_stat_total'] = $campaign_stat_total;
                    $data['campaign_stat_cats'] = self::CAMPAIGN_STAT_CATS;
                    $data['active_line'] = $active_line;
                    $data['img_domain'] = (getenv('DEVELOPMENT')) ? self::IMG_DOMAIN_DEV : self::IMG_DOMAIN_PROD;

                } else {
                    $data['error'] = _t('Извините, данная кампания закреплена за другим пользователем');
                }

            } else {
                $data['error'] = _t('Извините, кампания не найдена');
            }
            
            $data = array_merge($data, [
                'lang' => $request->getAttribute('layoutInfo')->getLang(),
                'layoutInfo' => $request->getAttribute('layoutInfo'),
            ]);     

            return new HtmlResponse($this->template->render('app::user/campaign_item', $data));
            
            
        }
        
    }
    
    private function getStatData(ServerRequestInterface $request) 
    {
        /** @var UserService $auth */
        $auth = $this->container->get(UserService::class);
        $userId = $auth->getIdentity()->getId();
        
        $campaign_id = $request->getAttribute('id');
        
        /** @var \App\Model\AmSystem\Groups $groupsModel */
        $groupsModel = $this->container->get(\App\Model\AmSystem\Groups::class);
        
        /** @var \App\Model\AmSystem\Campaigns $campaignsModel */
        $campaignsModel = $this->container->get(\App\Model\AmSystem\Campaigns::class);
        $campaign = $campaignsModel->findById($campaign_id);
        
        if ($campaign) {
            
            $group_id = $campaign->getGroupId();
            $group = $groupsModel->findOne(['id' => $group_id]);

            if ($group->getUserId() == $userId) {
                
                /** @var \App\Model\Statistics $stats */
                $stats = $this->container->get(\App\Model\Statistics::class);
                
                $data_request = $request->getParsedBody();
                
                if ($data_request['type'] == 'stat-common') {
                    $data_stat = [
                        'stat' => $stats->getCampaignsStat([(int)$campaign_id], $campaign->getTargetAction(), $data_request['period'], true),
                        'total' => $stats->getCampaignsStat([(int)$campaign_id], $campaign->getTargetAction(), $data_request['period'], false)
                    ];
                }
                
                if ($data_request['type'] == 'stat-sites') {
                    $data_stat = $stats->getCampaignsSitesStat((int)$campaign_id, $campaign->getTargetAction(), $data_request['period']);
                }
                
                if ($data_request['type'] == 'stat-regions') {
                    $data_stat = $stats->getCampaignsRegionsStat((int)$campaign_id, $campaign->getTargetAction(), $data_request['period']);
                }
                
                return new JsonResponse([
                    'type' => $data_request['type'],
                    'data' => $data_stat
                ]);
            }
        }
        
        return new JsonResponse(null);
    }
    
    
}