<?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\Admin;


use App\Action\Admin\Common;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Zend\Diactoros\Response\HtmlResponse;
use Zend\Expressive\Template\TemplateRendererInterface;

use App\Model\Statistics;
use App\Model\Users;
use App\Model\Sites;
/*
use App\Model\Teasers\Offers;
use App\Model\Teasers\Adds;
use App\Model\Teasers\Partners;
*/
use App\Authentication\SupportService;

/**
 * Class Index
 * @package App\Action\Admin
 */
class Index extends Common
{

    function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null)
    {
        
        /** @var Sites $sitesModel */
        $sitesModel = $this->container->get(Sites::class);
        
        /** @var Statistics $stats */
        $stats = $this->container->get(Statistics::class);
        
        /** @var Users $usersModel */
        $usersModel = $this->container->get(Users::class);
        
        /** @var \App\Model\Supports $supportModel */
        $supportModel = $this->container->get(\App\Model\Supports::class);
        
        /** @var \App\Model\Countries $countryModel */
        $countryModel = $this->container->get(\App\Model\Countries::class);
        $countries = array();
        foreach($countryModel->findAll() as $country) {
            $countries[$country->getCode()] = $country->getName();
        }
       	

        /** @var SupportService $auth */
        $auth = $this->container->get(SupportService::class);
        $role = $auth->getIdentity()->getRoleId();
        
        if (in_array($role, ['admin'])) {
            // Список сайтов админа
            $adminSites = $sitesModel->findAllSites();
        } else {
            // Список сайтов менеджера
            $manager_id = $auth->getIdentity()->getId();
            $manager_users = $usersModel->findBySupportId($manager_id);
            $managerSites = $sitesModel->findByUserId($manager_users)->buffer();
            
            $listDomains = array();
            foreach($managerSites as $site) {
                if (!in_array($site->getDomain(), $listDomains)) {
                    $listDomains[] = $site->getDomain();
                }
            }

            $adminSites = $listDomains;
        }

        
        $listSites = array();
        $listDomains = array();
        foreach($adminSites as $site) {
            $listSites[$site] = [$site];
            $listDomains[] = $site;
        }
        $subDomains = $listSites;
        
        if (in_array($role, ['admin'])) {
            $allDomains = [];
        } else {
            $allDomains = $listDomains;
        }
        
        // Список актуальных стран, сегментов и менеджеров
        $listCountries = array();
        $listSegments = array();
        $listManagers = array();
        
        $allUsers = $usersModel->findAll();
        
        foreach($allUsers as $userItem) {
            $userCountryCode = $userItem->getCountryCode();
            $userSegment = $userItem->getSegment();
            $userManagerId = $userItem->getSupportId();
            
            if ($userCountryCode != '' && !$listCountries[$userCountryCode]) {
                $countryItem = $countryModel->findByCode($userCountryCode);
                foreach($countryItem as $c) {
                    $listCountries[$c->getCode()] = $c->getName();
                }
            }
            if ($userSegment != '' && !in_array($userSegment, $listSegments)) {
                $listSegments[] = $userSegment;
            }
            if ($userManagerId != '' && !$listManagers[$userManagerId]) {
                $support = $supportModel->findById($userManagerId);
                if ($support) {
                    $listManagers[$support->getId()] =  $support->getFullname();
                }
            }
        }
        asort($listCountries);
        asort($listSegments);
        


        // Определяем списки сайтов с фильтрами (сегмент/страна):
        $listDomainsFilters = array();
        foreach($listDomains as $site) {
            
            $sitesItem = $sitesModel->findByDomain($site);
            
            $siteUserId = [];
            foreach($sitesItem as $siteItem) {
                $siteUserId[] = $siteItem->getUsersId();
            }
            
            if (count($siteUserId) == 0) {
                $siteSegment = '';
                $siteCountry = '';
                $siteManager = '';
            } else {
                $user = $usersModel->findById($siteUserId[0]);
                $country = $user->getCountryCode();
                $segment = $user->getSegment();
                $manager = $user->getSupportId();
                
                $siteSegment = $segment;
                $siteCountry = $country;
                $siteManager = $manager;
            }
            
            $listDomainsFilters[] = array(
                'site' => $site,
                'segment' => $siteSegment,
                'country' => $siteCountry,
                'manager' => $siteManager,
            );
        }
        
        $listSitesFilters = array();
        foreach($listSites as $site => $value) {
            
            $sitesItem = $sitesModel->findByDomain($site);
            
            $siteUserId = [];
            foreach($sitesItem as $siteItem) {
                $siteUserId[] = $siteItem->getUsersId();
            }
            
            if (count($siteUserId) == 0) {
                $siteSegment = '';
                $siteCountry = '';
                $siteManager = '';
            } else {
                $user = $usersModel->findById($siteUserId[0]);
                $country = $user->getCountryCode();
                $segment = $user->getSegment();
                $manager = $user->getSupportId();
                
                $siteSegment = $segment;
                $siteCountry = $country;
                $siteManager = $manager;
            }
            
            $listSitesFilters[] = array(
                'site' => $site,
                'segment' => $siteSegment,
                'country' => $siteCountry,
                'manager' => $siteManager,
            );
        }
                
        
        $currencyAdmin = (isset($_COOKIE["adminCurrency"])) ? $_COOKIE["adminCurrency"] : 'USD';
        $subdomains = true;
        $allStat = true;
        $group = (in_array($role, ['admin'])) ? 'all' : false;
        
        $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 = array();
        if($dateStart != $dateEnd) {
            $_dateRange = new \DatePeriod($dateStart, $dateIterval, $dateEnd);                         
            foreach($_dateRange as $dt) {
                $dateRange[] = $dt;
            }         
        }
        $dateRange[] = $dateEnd;
        $dateRange = array_reverse($dateRange);
        
        $currencyModel = $this->container->get(\App\Model\Currencies::class);
        $currencies = array();
        foreach($currencyModel->findAll() as $currency) {
            $currencies[$currency->getCode()] = $currency->getName();
        }
        
        $data = [
            'sitesFilters' => $listSitesFilters,
            'periodStats' => $periodStats,
            'sitesStats' => $sitesStats,
            'summaryReport' => $summaryReport,
            'subDomains' => $subDomains,
            'listDomainsFilters' => $listDomainsFilters,
            'dateRange' => $dateRange,
            'segments' => $listSegments,
            'countries' => $listCountries,
            'managers' => $listManagers,
            'currencies' => $currencies,
            'currency' => ['code' => $currencyAdmin, 'name' => $currencies[$currencyAdmin]],
            'lang' => $request->getAttribute('layoutInfo')->getLang(),
            'role' => $role,
        ];
        
        return new HtmlResponse($this->template->render('adm::index', $data));
    }
}