<?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\Sites;
use App\Model\Statistics;
use App\Model\Providers;
use App\Model\Codes;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Zend\Diactoros\Response\HtmlResponse;


/**
 * Class Codestat
 * @package App\Action\User
 */
class Codestat extends Common
{
    
    /**
     * @param ServerRequestInterface $request
     * @param ResponseInterface $response
     * @param callable|null $next
     * @return HtmlResponse
     */
    function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null)
    {  
       
        $provider_name = $request->getAttribute('provider');
        
        try {
            /** @var Sites $sitesModel */
            $sitesModel = $this->container->get(Sites::class);        
        
            /** @var UserService $authUser */
            $authUser = $this->container->get(UserService::class);
            $userAuth = $authUser->getIdentity();
            
            /** @var Statistics $stats */
            $stats = $this->container->get(Statistics::class);
            
            /** @var Users $usersModel */
            $usersModel = $this->container->get(Users::class);
            
            /** @var \App\Model\Providers $providerModel */
            $providerModel = $this->container->get(Providers::class);
            $provider =  $providerModel->findOne(['name' => $provider_name]);
            
            // Проверяем наличие провайдера в системе:
            if ($provider) {
                $provider_id = $provider->getId();

                if ($userAuth) {
                    $data['adminStats'] = false;
                    
                    $user_id = $userAuth->getId();
                    $user = $usersModel->findById($user_id);
                    $userCodeProviderId = json_decode($user->getCodeProvider(), true);

                    // Проверяем наличие у данного юзера кода провайдера:
                    if (!in_array($provider_id, $userCodeProviderId)) {
                        $data['error'] = _t('У вас нет доступа к этой странице');
                    }
                    
                } else {
                    $data['adminStats'] = true;
                    $this->container->get('layout')->setTemplate('layout/support');
                }
                
            } else {
                if ($userAuth) {
                    $data['error'] = _t('У вас нет доступа к этой странице');
                } else {
                    $data['error'] = _t('Извините, провайдера: '. $provider_name .' нет в системе');
                }
            }
            
            
            if (!$data['error']) {
            
                /** @var \App\Model\Codes $codeModel */
                $codeModel = $this->container->get(Codes::class);
                $codes = $codeModel->findAll(['provider' => $provider_id])->toArray();
                if ($codes) {

                    $sites_id = [];
                    foreach ($codes as $code) {
                        $code_site_id = (int)$code['site_id'];
                        if (!in_array($code_site_id, $sites_id) && $code_site_id<59990) {
                            $sites_id[] = $code_site_id;
                        }
                    }

                    if (count($sites_id)) {
                    
                        $listSites = $sitesModel->findAll(['id' => $sites_id])->buffer();

                        $listDomains = [];
                        foreach($listSites as $site) {
                            $listDomains[$site->getId()] = $site->getDomain();
                        }
                        $listSites->rewind();
                        asort($listDomains);

                        /** @var \App\Model\Currencies $currencyModel */
                        $currencyModel = $this->container->get(\App\Model\Currencies::class);
                        $currentCurencyCode = 'USD';
                        $currencies = array();
                        foreach($currencyModel->findAll() as $currency) {
                            $currencies[$currency->getCode()] = $currency->getName();
                        }

                        $summaryReport = $stats->getCodestatGlobalReport($sites_id, [$provider_name]);
                        list($periodStats, $periodDates) = $stats->getCodestatReport(date('Y-m'), $sites_id, [$provider_name]);

                        $dateIterval = new \DateInterval('P1M');                
                        $dateStart = \DateTime::createFromFormat('Y-m-d', $periodDates['min'] ?: date('Y-m-01'));
                        $dateEnd = \DateTime::createFromFormat('Y-m-d', $periodDates['max'] ?: date('Y-m-01'));              

                        $dateRange = [];
                        if($dateStart != $dateEnd) {
                            $_dateRange = new \DatePeriod($dateStart, $dateIterval, $dateEnd);                         
                            foreach($_dateRange as $dt) {
                                $dateRange[] = $dt;
                            }         
                        }
                        $dateRange[] = $dateEnd;
                        $dateRange = array_reverse($dateRange);

                        //$data['sites'] = $listSites;
                        $data['listDomains'] = $listDomains;
                        $data['summaryReport'] = $summaryReport;
                        $data['periodStats'] = $periodStats;
                        $data['dateRange'] = $dateRange;
                        $data['codeProvider'] = $provider_name;
                        
                    } else {
                        if ($userAuth) {
                            $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::codestat', $data));
    }
}