<?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'],
        'money'     =>  ['title' => 'Расход, грн.',  'color' => '#1F77B4'],
        'reach'     =>  ['title' => 'Охват',         'color' => '#FF7F0E'],
        'ctr'       =>  ['title' => 'CTR',           'color' => '#9467BD'],
        'cpm'       =>  ['title' => 'eCPM',          'color' => '#33C7B6'],
        'cpc'       =>  ['title' => 'eCPC',          'color' => '#7CADE2']
    ];
    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_STAT:
                        $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\Campaigns $campaignsModel */
                $campaignsModel = $this->container->get(\App\Model\AmSystem\Campaigns::class);
                $campaigns = $campaignsModel->findAll(['user_id' => $userId])->toArray();
                
                if ($campaigns) {
                    
                    /** @var \App\Model\Statistics $stats */
                    $stats = $this->container->get(\App\Model\Statistics::class);
                    $campaigns_stat = [];
                    
                    foreach ($campaigns as $campaign_item) {
                        $campaign_id = $campaign_item['id'];
                        $campaigns_stat[$campaign_id] = $stats->getCampaignsStat([$campaign_id], $campaign_item['target_action'], null);
                    }
                    
                    $data['campaigns'] = $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\Campaigns $campaignsModel */
            $campaignsModel = $this->container->get(\App\Model\AmSystem\Campaigns::class);
            $campaign_item = $campaignsModel->findById($campaign_id);
            
            if ($campaign_item) {

                if ($campaign_item->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]);

                    /** @var \App\Model\Statistics $stats */
                    $stats = $this->container->get(\App\Model\Statistics::class);
                    $date_begin = $campaign->getDateBegin();
                    $date_end = $campaign->getDateEnd() ? : date("Y-m-d");
                    // последние 90 дней, если кампания долго идет
                    $dates = [$date_begin, $date_end];
                    $campaign_stat = $stats->getCampaignsStat([(int)$campaign_id], $campaign->getTargetAction(), $dates);
                    $campaign_stat_total = $stats->getCampaignsStat([(int)$campaign_id], $campaign->getTargetAction(), null);
                    
                    $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], 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)*100, 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);
                    
                            
                    $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));
            
            
        }
        
    }
    
    
}