<?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\AmSystem\Campaigns;
//use App\Entity\AmSystem\Campaign;

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;

/*
use App\Entity\User;
use App\Entity\AmSystem\Banner;
use App\Model\Statistics;
*/



/**
 * Class CabinetAmSystem
 * @package App\Action\User
 */
class CabinetAmSystem extends Common
{
    const ACTION_LIST = 'list';

    /**
     * @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], null);
                        if ($campaign_item['target_action'] == 'load') {
                            $campaigns_stat[$campaign_id]['views'] = $campaigns_stat[$campaign_id]['loads'];
                            $campaigns_stat[$campaign_id]['reach'] = $campaigns_stat[$campaign_id]['reach_load'];
                        } else {
                            $campaigns_stat[$campaign_id]['reach'] = $campaigns_stat[$campaign_id]['reach_view'];
                        }

                        $views = $campaigns_stat[$campaign_id]['views'];
                        $money = $campaigns_stat[$campaign_id]['money'];
                        $clicks = $campaigns_stat[$campaign_id]['clicks'];

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

                        $campaigns_stat[$campaign_id]['money'] = round($campaigns_stat[$campaign_id]['money'], 2);
                    }
                    
                    
                    $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));
        }
        
    }
    
    
}