<?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.
 *
 *
 */

/** @var $this \Zend\View\Renderer\PhpRenderer */

/** @var $userSiteStatistic \App\Entity\Statistic\Site */

$this->headScript()
    ->appendFile('//cdnjs.cloudflare.com/ajax/libs/autosize.js/3.0.18/autosize.min.js')
    ->appendFile('/js/underscore-min.js')
    ->appendFile('/js/jquery.cookie.js')
    ->appendFile('/js/c3.min.js')
    ->appendFile('/js/d3.min.js')
    ->appendFile('/js/script-cabinet.js')
;

$this->headLink()
    ->appendStylesheet('/css/styles-cabinet.css')
    ->appendStylesheet('/css/styles-cabinet-550.css', 'all and (max-width: 550px)')
    ->appendStylesheet('/css/styles-cabinet-stats.css')
    ->appendStylesheet('/css/c3.css')
;



/** @var \App\Entity\IdentityInterface $identity */
$identity = $this->identity();
$gravatar = $this->gravatar($identity->getEmail());
$gravatar->setDefaultImg(\Zend\View\Helper\Gravatar::DEFAULT_IDENTICON);
$sxml = new SimpleXMLElement(substr($gravatar, 0, -1) . '/>');
$src = $sxml['src'];

$error = $this->error;
$summaryStats = $this->summaryStats;
$periodStats = $this->periodStats;
$summaryReport = $this->summaryReport;
$listDomains = $this->listDomains;
$dateRange = $this->dateRange;
$adminStats = $this->adminStats;
$accessSites = $this->accessSites;

switch ($currency['code']) {
case 'USD':
    $symb = '&#36;';
    break;
case 'UAH':
    $symb = '&#8372;';
    break;
case 'RUR':
    $symb = '&#8381;';
    break;
}
?>

<?php if ($adminStats):
    $this->headLink()
        ->appendStylesheet('/css/styles-support-index.css')
    ;
endif; ?>

<?php if (!$adminStats): ?>
<section class="b-content__title">
    <div class="wrapp">
        <!-- Вход произведен -->
        <picture>
            <img src="/img/bg-img-logo.svg" alt="No logo">
        </picture>
        <p class="lead"><?= $identity->getEmail() ?></p>
        <p class="b-content__title-settings">
            <a href="<?= $this->url('user.cabinet.profile', ['lang' => $this->lang]) ?>" title="" class="annotation"><?= _t("Настройки профиля") ?></a>
            <a href="<?= $this->url('logout', ['lang' => $this->lang]) ?>" title="" class="annotation"><?= _t("Выход") ?></a>
        </p>
    </div>
</section>
<?php endif; ?>


<?php if($error): ?>
<section class="b-content__work">
    <h1><?= $error?></h1>
</section>
<?php else: ?>

<?php /* Выпадающие списки сайтов и валют */ ?>
<section class="b-content__site">
    <div class="wrapp row row-wrap">
        <div id="sites-dropdown" class="b-content__site-droplits droplist col sm-4 xs-12">
            <span class="droplist-current text bold tab-input"></span>
            <ul class="droplist-block">
                <li class="droplist-item text" data-id="all"><?= _t('Все') ?></li>
                <?php /** @var \App\Entity\Site $site */
                foreach ($listDomains as $main_domain) :?>
                <li class="droplist-item text" data-id="<?= $main_domain ?>" data-src-icon-site='http://<?= $main_domain ?>/favicon.ico'><?= $main_domain ?></li>
                <?php endforeach; ?>

                <?php /* Доступные сайты */ 
                foreach ($accessSites as $site) :?>
                <li class="droplist-item text" data-id="<?= $site->getDomain() ?>" data-src-icon-site='http://<?= $site->getDomain() ?>/favicon.ico'><?= $site->getDomain() ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
        <?php if (!$adminStats): ?>
        <div class="b-content__site-currency user">
            <span class="droplist-current text bold tab-input" data-symbol="<?=$symb ?>"><?= $currency['code'] ?> (<?= _t($currency['name']) ?>)</span>
            <?php /* ?>
            <form action="" class="b-content__form-set" name="setting" data-url="<?= $this->url('user.cabinet.profile', ['lang' => $this->lang]) ?>" data-url-success="<?= $this->url('user.cabinet', ['lang' => $this->lang]) ?>">            
                <div>
                    <span class="input input--akira currency">
                        <?php $currencies = $this->currencies; ?>
                        <input class="input__field input__field--akira" type="hidden" id="setting-money" name="currency" value="<?= $currency['code'] ?>"/>
                        <span class="droplist-current text bold tab-input" data-symbol="<?=$symb ?>"><?= $currency['code'] ?> (<?= _t($currency['name']) ?>)</span>
                        <ul class="droplist-block">
                            <?php foreach($currencies as $code => $name): ?>
                            <li class="droplist-item text" data-id="<?= $code?>"><?= $code?> (<?= $name?>)</li>
                            <?php endforeach ?>
                        </ul>
                    </span>
                </div>
            </form>
            <?php */ ?>
        </div>
        
        <span class="userid-current" data-userid="<?=$userId ?>"></span>
        <?php else: ?>
        <div class="b-content__site-currency state-admin">
            <?php if ($userId): ?>
            <span class="userid-current" data-userid="<?=$userId ?>"></span>
            <?php endif; ?>
            <span class="droplist-current text bold tab-input" data-symbol="<?=$symb ?>"><?= $currency['code'] ?> (<?= _t($currency['name']) ?>)</span>
        </div>
        <?php endif; ?>
        
    </div>
</section>

<textarea id="summary-report-stats" style="display: none;"><?= ($summaryStats ? json_encode($summaryStats) : '')?></textarea>
<textarea id="period-stats" style="display: none;"><?= ($periodStats ? json_encode($periodStats) : '')?></textarea>

<?php /* Список доменов-поддоменов и сводная таблица */ ?>
<section class="b-content__losses">
    <div class="wrapp row row-wrap">
        <div class="b-content__losses-left col sm-4 xs-5">
            <div class="b-content__losses-left-item">
                
                <?php if(count($listDomains)): ?>
                    <ul id="domains-list" class="b-subdomains-list main-list">
                    <a class="all-domains" href="#">все сайты &rarr;</a>
                    <?php foreach ($listDomains as $main_domain) :?>
                        <li>
                            <a class="main-domain" data-domain="<?= $main_domain ?>" data-id="<?= $main_domain?>" href="#">
                                <?= $main_domain ?>
                            </a>
                            <ul class="b-subdomains-list sub-list" style="display: none;"></ul>
                        </li>
                    <?php endforeach; ?>
                    </ul>
                <?php endif; ?>
                
            </div>            
        </div>
        <div class="b-content__losses-right col sm-8 xs-7">
            <div class="b-content__no-data">Данных по этому домену в системе нет</div>
            <div class="b-content__loading summary"></div>
            <?php
            $is_block_hits = false;
            $block_hits_class = 'short';
            foreach ($summaryReport as $range => $value) {
                if ($value['block_hits'] && $value['block_hits'] != 0)
                {
                    $is_block_hits = true;
                    $block_hits_class = 'full';
                    break;
                }
            }
            ?>
            <table id="summary-report-table" class="user <?=$block_hits_class ?>">
                <thead>
                <tr>
                    <th></th>
                    <th></th>
                    
                    <?php /* ?>
                    <th class="block-info"><?= _t('Показы блоков') ?></th>
                    <th class="block-info block_money"><?= _t('Сумма за блоки') ?></th>
                    <?php */ ?>
                    
                    <th><?= _t('Показы RTB') ?></th>
                    <th class="money"><?= _t('Доход RTB') ?></th>
                    
                    <th class="block-info total"><?= _t('Итого') ?></th>
                </tr>
                </thead>
                <tbody>
                <tr>
                    <td><span class="text"><?= _t('Сегодня') ?></span></td>
                    <td></td>
                    
                    <?php /* ?>
                    <td class="block-info"><span id="summary-today-block_hits"><?= number_format(intval($summaryReport['today']['block_hits'])) ?></span></td>
                    <td class="block-info block_money"><span id="summary-today-block_money"><?= number_format((float) -$summaryReport['today']['block_money'], 2) ?> <?=$symb ?></span></td>
                    <?php */ ?>
                    
                    <td><span id="summary-today-hits" class="data"><?= number_format(intval($summaryReport['today']['hits'])) ?></span></td>
                    <td class="money"><span id="summary-today-money" class="data"><?= number_format((float) $summaryReport['today']['money'], 2) ?> <?=$symb ?></span></td>
                    
                    <td class="block-info total"><span id="summary-today-total"><?= number_format((float) $summaryReport['today']['money'] /*- $summaryReport['today']['block_money']*/, 2) ?> <?=$symb ?></span></td>
                    
                </tr>
                <tr>
                    <td><span class="text"><?= _t('Вчера') ?></span></td>
                    <td></td>
                    
                    <?php /* ?>
                    <td class="block-info"><span id="summary-yesterday-block_hits"><?= number_format(intval($summaryReport['yesterday']['block_hits'])) ?></span></td>
                    <td class="block-info block_money"><span id="summary-yesterday-block_money"><?= number_format((float) -$summaryReport['yesterday']['block_money'], 2) ?> <?=$symb ?></span></td>
                    <?php */ ?>
                    
                    <td><span id="summary-yesterday-hits" class="data"><?= number_format(intval($summaryReport['yesterday']['hits'])) ?></span></td>
                    <td class="money"><span id="summary-yesterday-money" class="data"><?= number_format((float) $summaryReport['yesterday']['money'], 2) ?> <?=$symb ?></span></td>
                    
                    <td class="block-info total"><span id="summary-yesterday-total"><?= number_format((float) $summaryReport['yesterday']['money'] /*- $summaryReport['yesterday']['block_money']*/, 2) ?> <?=$symb ?></span></td>
                </tr>
                <tr>
                    <td><span class="text"><?= _t('30 дней') ?> </span></td>
                    <td></td>
                    
                    <?php /* ?>
                    <td class="block-info"><span id="summary-30days-block_hits"><?= number_format(intval($summaryReport['30days']['block_hits'])) ?></span></td>
                    <td class="block-info block_money"><span id="summary-30days-block_money"><?= number_format((float) -$summaryReport['30days']['block_money'], 2) ?> <?=$symb ?></span></td>
                    <?php */ ?>
                    
                    <td><span id="summary-30days-hits" class="data"><?= number_format(intval($summaryReport['30days']['hits'])) ?></span></td>
                    <td class="money"><span id="summary-30days-money" class="data"><?= number_format((float) $summaryReport['30days']['money'], 2) ?> <?=$symb ?></span></td>
                    
                    <td class="block-info total"><span id="summary-30days-total"><?= number_format((float) $summaryReport['30days']['money'] /*- $summaryReport['30days']['block_money']*/, 2) ?> <?=$symb ?></span></td>
                </tr>
                <tr>
                    <td><span class="text"><?= _t('Текущий меcяц') ?> </span></td>
                    <td></td>
                    
                    <?php /* ?>
                    <td class="block-info"><span id="summary-cur_month-block_hits"><?= number_format(intval($summaryReport['cur_month']['block_hits'])) ?></span></td>
                    <td class="block-info block_money"><span id="summary-cur_month-block_money"><?= number_format((float) -$summaryReport['cur_month']['block_money'], 2) ?> <?=$symb ?></span></td>
                    <?php */ ?>
                    
                    <td><span id="summary-cur_month-hits" class="data"><?= number_format(intval($summaryReport['cur_month']['hits'])) ?></span></td>
                    <td class="money"><span id="summary-cur_month-money" class="data"><?= number_format((float) $summaryReport['cur_month']['money'], 2) ?> <?=$symb ?></span></td>
                    
                    <td class="block-info total"><span id="summary-cur_month-total"><?= number_format((float) $summaryReport['cur_month']['money'] /*- $summaryReport['cur_month']['block_money']*/, 2) ?> <?=$symb ?></span></td>
                </tr>
                <tr>
                    <td><span class="text"><?= _t('Прошлый месяц') ?> </span></td>
                    <td></td>
                    
                    <?php /* ?>
                    <td class="block-info"><span id="summary-prev_month-block_hits"><?= number_format(intval($summaryReport['prev_month']['block_hits'])) ?></span></td>
                    <td class="block-info block_money"><span id="summary-prev_month-block_money"><?= number_format((float) -$summaryReport['prev_month']['block_money'], 2) ?> <?=$symb ?></span></td>
                    <?php */ ?>
                    
                    <td><span id="summary-prev_month-hits" class="data"><?= number_format(intval($summaryReport['prev_month']['hits'])) ?></span></td>
                    <td class="money"><span id="summary-prev_month-money" class="data"><?= number_format((float) $summaryReport['prev_month']['money'], 2) ?> <?=$symb ?></span></td>
                    
                    <td class="block-info total"><span id="summary-prev_month-total"><?= number_format((float) $summaryReport['prev_month']['money'] /*- $summaryReport['prev_month']['block_money']*/, 2) ?> <?=$symb ?></span></td>
                </tr>
                </tbody>
            </table>            
        </div>
    </div>
</section>

<?php
$is_block_hits = false;
$block_hits_class = 'short';
$block_switch_full_style = 'style="display: none;"';
$block_switch_short_style = 'style="display: flex;"';
//if ($periodStats['block_hits'])
if (false)
{
    foreach ($periodStats['block_hits'] as $value) {
        if ($value != 0)
        {
            $is_block_hits = true;
            $block_hits_class = 'full';
            $block_switch_full_style = 'style="display: flex;"';
            $block_switch_short_style = 'style="display: none;"';
            break;
        }
    }
}
?>

<?php /* График */ ?>
<section id="b-content__traffic-chart" class="b-content__traffic">
    <div class="b-content__loading chart"></div>
    <div class="wrapp">
        <div class="b-content__traffic-filter">
            <div id="daterange-dropdown" class="b-add-car__form-item droplist chart-dates">
                <span class="droplist-current text bold tab-input"></span>
                <ul class="droplist-block">                    
                    <?php foreach($dateRange as $date): ?>
                    <li class="droplist-item text" data-date-value="<?= $date->format('Y-m')?>"><?= _t($date->format('F')) .', ' . $date->format('Y')  ?></li> 
                    <?php endforeach ?>
                </ul>
            </div>
            <?php if(true): ?>
            <div class="b-filter__switch display full <?php if ($is_block_hits): ?>current<?php endif; ?>" <?=$block_switch_full_style ?>>
                <?php /* ?>
                <span class="b-filter__switch-item text" data-filter-category="block_hits"><?= _t('Показы блоков')?></span>
                <span class="b-filter__switch-item text" data-filter-category="block_money"><?= _t('Сумма за блоки')?></span>
                <?php */ ?>
                <span class="b-filter__switch-item text" data-filter-category="hits"><?= _t('Показы RTB')?></span>                
                <span class="b-filter__switch-item text" data-filter-category="money"><?= _t('Доход RTB')?></span>
                <span class="b-filter__switch-item text" data-filter-category="total"><?= _t('Итого')?></span>                
            </div>
            <?php else : ?>
            <div class="b-filter__switch display full <?php if ($is_block_hits): ?>current<?php endif; ?>" <?=$block_switch_full_style ?>>
                <span class="b-filter__switch-item text" data-filter-category="common_hits"><?= _t('Показы')?></span>
                <span class="b-filter__switch-item text" data-filter-category="common_money"><?= _t('Деньги')?></span>
                <span class="b-filter__switch-item text" data-filter-category="total"><?= _t('Итого')?></span>                
            </div>
            <?php endif; ?>
            <div class="b-filter__switch display short <?php if (!$is_block_hits): ?>current<?php endif; ?>" <?=$block_switch_short_style ?>>
                <span class="b-filter__switch-item text" data-filter-category="hits"><?= _t('Показы RTB')?></span>                
                <span class="b-filter__switch-item text" data-filter-category="money"><?= _t('Доход RTB')?></span>
            </div>
        </div>
        <div id="chart-graph" style="height: 370px"></div>
    </div>
</section>

<?php /* Основная таблица */ ?>
<section id="b-content__traffic-table" class="b-content__traffic">
    <div class="b-content__loading table"></div>
    <div class="wrapp">
        <table id="table-line" class="table table-striped user <?=$block_hits_class ?>">
            <thead>
                <tr>
                    <th><?= _t('Дата')?></th>
                    
                    <?php /* ?>
                    <th class="block-info"><?= _t('Показы блоков')?></th>
                    <th class="block-info block_money"><?= _t('Сумма за блоки')?></th>
                    <?php */ ?>
                    
                    <th><?= _t('Показы RTB')?></th>
                    <th class="money"><?= _t('Доход RTB')?></th>                    
                    
                    <th class="block-info total"><?= _t('Итого') ?></th>
                </tr>
            </thead>            
            <tbody>   
                <?php
                    $summ_views = 0;
                    $summ_income = 0;
                    $summ_block_hits = 0;
                    $summ_block_money = 0;
                    $summ_total = 0;
                ?>
                <?php if($periodStats): ?>
                <?php
                    $periodStats = array_map(function($v){
                        $v = array_reverse($v);
                        return $v;                        
                    }, $periodStats);
                ?>
                <?php foreach($periodStats['period'] as $i => $date) : ?>
                <?php
                    $summ_views += $periodStats['hits'][$i];
                    $summ_income += $periodStats['money'][$i];
                    $summ_block_hits += $periodStats['block_hits'][$i];
                    $summ_block_money += $periodStats['block_money'][$i];
                    $summ_total += $periodStats['money'][$i] - $periodStats['block_money'][$i];
                ?>
                <tr>
                    <td><?= $date?></td>
                    
                    <?php /* ?>
                    <td class="block-info"><?= number_format(intval($periodStats['block_hits'][$i]))?></td>
                    <td class="block-info block_money"><?= number_format((float) -$periodStats['block_money'][$i], 2)?> <?=$symb ?></td>
                    <?php */ ?>
                    
                    <td><?= number_format(intval($periodStats['hits'][$i]))?></td>
                    <td class="money"><?= number_format((float) $periodStats['money'][$i], 2)?> <?=$symb ?></td>
                    
                    <td class="block-info total"><?= number_format((float) $periodStats['money'][$i] - $periodStats['block_money'][$i], 2) ?> <?=$symb ?></td>
                </tr>
                <?php endforeach; ?>               
                <?php endif ?>
            </tbody>
            <tfoot>
                <?php if($periodStats): ?>
                <tr>
                    <td><?= _t('Сумма') ?></td>
                    
                    <?php /* ?>
                    <td class="block-info summ-block_hits"><?= number_format($summ_block_hits) ?></td>
                    <td class="block-info summ-block_money block_money"><?= number_format(-$summ_block_money, 2) ?> <?=$symb ?></td>
                    <?php */ ?>
                    
                    <td class="summ-views"><?= number_format($summ_views) ?></td>
                    <td class="summ-income money"><?= number_format((float) $summ_income, 2) ?> <?=$symb ?></td>
                    
                    <td class="block-info summ-total total"><?= number_format($summ_total, 2) ?> <?=$symb ?></td>
                </tr>
                <?php endif ?>
            </tfoot>
        </table>
    </div>
</section>
<?php endif ?>