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

$this->headScript()
    ->appendFile('/js/c3.min.js')
    ->appendFile('/js/d3.min.js')
    ->appendFile('/js/datepicker.min.js')
    ->appendFile('/js/adm/amsystem-campaign.js')
;

$this->headLink()
    ->appendStylesheet('/css/c3.css')
    ->appendStylesheet('/css/datepicker.min.css')
    ->appendStylesheet('/css/styles-amsystem.css')
;

$lang = $this->lang;
$campaign = $this->campaign;
$countries = $this->countries;
$regions = $this->regions;
$cities = $this->cities;

$error = $this->error;

if (!$error) {

    $campaign_active = (bool)$campaign->getActive();
    $campaign_id = $campaign->getId();
    $campaign_title = $campaign->getTitle();
    $campaign_url = $campaign->getUrl();
    $campaign_date_begin = $campaign->getDateBegin();
    $campaign_date_end = $campaign->getDateEnd();
    $campaign_url = $campaign->getUrl();
    $campaign_buy_type = $campaign->getBuyType();
    $campaign_target_action = $campaign->getTargetAction();
    $campaign_price = $campaign->getPrice()/10;
    $campaign_visitor_limit = json_decode($campaign->getVisitorLimit(), true);
    $campaign_money_limit = json_decode($campaign->getMoneyLimit(), true);
    $campaign_max_speed = (bool)$campaign->getMaxSpeed();
    $campaign_tracking_pixels = json_decode($campaign->getTrackingPixels(), true);
    $campaign_geo = json_decode($campaign->getTargeting(), true)['geo'];
    
    $banners = $this->banners;
    $banners_stats = $this->banners_stats;
    $img_domain = $this->img_domain;
    
    $sites_stats = $this->sites_stats;
    $regions_stats = $this->regions_stats;
    
    $campaign_stat = $this->campaign_stat;
    $campaign_stat_total = $this->campaign_stat_total;
    $campaign_stat_cats = $this->campaign_stat_cats;
    
    
    $code_regions = [];
    foreach ($regions as $region_item) {
        foreach ($region_item['codes'] as $code) {
            $code_regions[$code] = str_replace(' область', '', $region_item['name']);
        }
    }
    
    $code_cities = [];
    foreach ($cities as $city_item) {
        foreach ($city_item['codes'] as $code) {
            $code_cities[$code] = str_replace(' область', '', $city_item['name']);
        }
    }
    
    $target_class = ($campaign_target_action == 'load') ? 'load-target' : '';

    $link_campaigns_list = $this->url('user.cabinet.amsystem', ['lang' => $lang]);
    $data_request_link = $this->url('user.cabinet.campaign', ['lang' => $lang]);
}

?>

<?= $this->partial('app::user/_format'); ?>

<?php if($error): ?>

    <section class="b-content__work error">
        <div class="wrapp">
            <h1><?= $error?></h1>
        </div>
    </section>

<?php else: ?>

    <section class="b-content__work inner">

        <form id="campaign-create-form" method="post" action="<?= $data_request_link ?>">
            
            <div class="panel panel-info">

                <!-- Header -->
                <div class="panel-heading">
                    <h1>
                        <a href="<?=$link_campaigns_list ?>">Кампании</a>/<?= $campaign_title ?>
                    </h1>
                </div>

                <div class="panel-body">

                    <div class="switch-data">
                        <span class="switch-item" data-type="settings">Настройки кампании</span>
                        <span class="switch-item" data-type="stat-common">Общая статистика</span>
                        <span class="switch-item" data-type="stat-sites">По сайтам</span>
                        <span class="switch-item" data-type="stat-regions">По регионам</span>
                    </div>

                    <!-- Настройки кампании -->
                    <div class="form-group-data settings" data-type="settings">
                        <fieldset disabled="disabled">

                            <!-- Статус кампании -->
                            <div class="form-group active <?php if ($campaign_active): ?>enabled<?php endif; ?>">
                                <label class="campaign-active">Статус:</label><span><?php if ($campaign_active): ?>активна<?php else: ?>остановлена<?php endif; ?></span>
                            </div>

                            <!-- Даты проведения -->
                            <div class="form-group">
                                <label for="campaign-date-begin"><?= _t('Даты проведения')?></label>
                                c:
                                <input type='text' id="campaign-date-begin" class="form-control date-value" name="date_begin" value="<?= $campaign_date_begin ?>" />
                                по:
                                <input type='text' id="campaign-date-end" class="form-control date-value" name="date_end" value="<?= $campaign_date_end ?>" />
                            </div>

                            <!-- Ссылка -->
                            <div class="form-group url">
                                <label for="campaign-url"><?= _t('Ссылка')?></label>
                                <div class="value-show">
                                    <?= $campaign_url ?>
                                </div>
                            </div>

                            <div class="b-left">

                                <!-- Тип кампании -->
                                <div class="form-group">
                                    <label><?= _t('Тип кампании')?></label>
                                    <input type="radio" id="campaign-buy-type-auction" name="buy_type" value="auction" <?php if ($campaign_buy_type == 'auction'): ?>checked<?php endif; ?>>
                                    <label class="select-item" for="campaign-buy-type-auction">Аукцион</label>
                                    <input type="radio" id="campaign-buy-type-garantee" name="buy_type" value="garantee" <?php if ($campaign_buy_type == 'garantee'): ?>checked<?php endif; ?> disabled>
                                    <label class="select-item disabled" for="campaign-buy-type-garantee">Гарантия</label>
                                </div>

                                <!-- Целевое действие -->
                                <div class="form-group">
                                    <label><?= _t('Целевое действие')?></label>
                                    <input type="radio" id="campaign-view-load" name="target_action" value="load" <?php if ($campaign_target_action == 'load'): ?>checked<?php endif; ?>>
                                    <label class="select-item" for="campaign-view-load">Показ</label>
                                    <input type="radio" id="campaign-view-view" name="target_action" value="view" <?php if ($campaign_target_action == 'view'): ?>checked<?php endif; ?>>
                                    <label class="select-item" for="campaign-view-view">Реальный показ</label>
                                    <input type="radio" id="campaign-view-click" name="target_action" value="click" <?php if ($campaign_target_action == 'click'): ?>checked<?php endif; ?>>
                                    <label class="select-item" for="campaign-view-click">Клик</label>
                                </div>

                                <!-- Стоимость -->
                                <div class="form-group">
                                    <?php
                                        switch ($campaign_target_action) {
                                            case 'load':    $title_mark = '1000 показов';           break;
                                            case 'view':    $title_mark = '1000 реальных показов';  break;
                                            case 'click':   $title_mark = 'клик';                   break;
                                        }
                                    ?>
                                    <label for="campaign-price"><?= _t('Стоимость')?></label>
                                    <input type="number" min="0" step="0.1" id="campaign-price" class="form-control price" name="price" value="<?= $campaign_price ?>" />
                                    грн. за <span class="price-title-mark"><?= $title_mark ?></span>
                                </div>

                                <!-- Ограничения на посетителя -->
                                <div class="form-group campaign-visitor-limit__wrap">
                                    <label><?= _t('Ограничения на посетителя')?></label><br />
                                    <div class="value-show">
                                        <?php 

                                        function declOfNum($number, $titles)
                                        {
                                            $cases = array (2, 0, 1, 1, 1, 2);
                                            $format = $titles[ ($number%100 > 4 && $number %100 < 20) ? 2 : $cases[min($number%10, 5)] ];
                                            return sprintf($format, $number);
                                        }

                                        foreach ($campaign_visitor_limit as $action => $data) {
                                            if ($action == 'view') $titles = ['показ', 'показа', 'показов'];
                                            if ($action == 'click') $titles = ['клик', 'клика', 'кликов'];

                                            foreach ($data as $period => $value) {
                                                switch ($period) {
                                                    case 'page':    $title_mark = 'на странице';    break;
                                                    case 'hour':    $title_mark = 'в час';          break;
                                                    case 'day':     $title_mark = 'в сутки';        break;
                                                    case 'week':    $title_mark = 'в неделю';       break;
                                                    case 'month':   $title_mark = 'в месяц';        break;
                                                }
                                                if ($value) {
                                        ?>
                                                    <span><b><?= $value ?></b> <i><?= declOfNum($value, $titles) ?></i> <?= $title_mark ?></span><br />
                                        <?php
                                        }   }   }
                                        ?>
                                    </div>
                                </div>

                                <!-- Бюджет -->
                                <div class="form-group campaign-money-limit">
                                    <label><?= _t('Бюджет')?></label><br />
                                    <div class="value-show">
                                        <?php 

                                        foreach ($campaign_money_limit as $period => $value) {
                                            switch ($period) {
                                                case 'total':   $title_mark = 'грн. всего';     break;
                                                case 'day':     $title_mark = 'грн. в сутки';   break;
                                                case 'week':    $title_mark = 'грн. в неделю';  break;
                                                case 'month':   $title_mark = 'грн. в месяц';   break;
                                            }
                                            if ($value) {
                                        ?>
                                                <span><b><?= $value ?></b> <?= $title_mark ?></span><br />
                                        <?php
                                        }   }
                                        ?>
                                    </div>
                                </div>

                                <!-- Скорость открута -->
                                <div class="form-group">
                                    <label><?= _t('Скорость открута')?></label>
                                    <input type="radio" id="campaign-max-speed-true" name="max_speed" value="1" <?php if ($campaign_max_speed): ?>checked<?php endif; ?>>
                                    <label class="select-item" for="campaign-max-speed-true">Максимальная</label>
                                    <input type="radio" id="campaign-max-speed-false" name="max_speed" value="0" <?php if (!$campaign_max_speed): ?>checked<?php endif; ?>>
                                    <label class="select-item" for="campaign-max-speed-false">Равномерная</label>
                                </div>

                                <!-- Гео -->
                                <div class="form-group geo">
                                    <?php if ($campaign_geo): ?>
                                        <label><?= _t('Гео (таргетинг)')?></label>
                                        <div class="value-show">
                                            <?php if ($campaign_geo['country']): ?>
                                                <?php
                                                $title_values = $countries[$campaign_geo['country']['values'][0]];
                                                if ($campaign_geo['special']) {
                                                    $title_special = '<b>(исключить неподконтрольные территории)</b>';
                                                }
                                                ?>
                                                <span><?= 'Страна' ?>: <b><?= $title_values ?></b> <?= $title_special ?></span><br />
                                            <?php endif; ?>
                                            <?php if ($campaign_geo['region']['values']): ?>
                                                <?php
                                                $title_mark = ($campaign_geo['region']['exclude']) ? 'кроме': 'только';
                                                $title_values = [];
                                                foreach ($campaign_geo['region']['values'] as $code) {
                                                    $title_values[] = str_replace(' область', '', $regions[$code]['name']);
                                                }
                                                $title_values = implode(", ", $title_values);
                                                ?>
                                                <span><?= 'Области' ?> <i><?= $title_mark ?></i>: <b><?= $title_values ?></b></span><br />
                                            <?php endif; ?>
                                            <?php if ($campaign_geo['city']['values']): ?>
                                                <?php
                                                $title_mark = ($campaign_geo['city']['exclude']) ? 'кроме': 'только';
                                                $title_values = [];
                                                foreach ($campaign_geo['city']['values'] as $code) {
                                                    $title_values[] = $cities[$code]['name'];
                                                }
                                                $title_values = implode(", ", $title_values);
                                                ?>
                                                <span><?= 'Города' ?> <i><?= $title_mark ?></i>: <b><?= $title_values ?></b></span><br />
                                            <?php endif; ?>
                                        </div>
                                    <?php endif; ?>
                                </div>

                                <!-- Трекинг -->
                                <div class="form-group tracking_pixels">
                                    <?php if ($campaign_tracking_pixels): ?>
                                    <label><?= _t('Трекинг')?></label>
                                    <div class="value-show">
                                        <?php 
                                        foreach ($campaign_tracking_pixels as $item => $values) {
                                            switch ($item) {
                                                case 'load':    $title_mark = 'Показ';          break;
                                                case 'view':    $title_mark = 'Реальный показ'; break;
                                                case 'click':   $title_mark = 'Клик';           break;
                                            }
                                            if ($values) {
                                        ?>
                                                <div><?= $title_mark ?></div>
                                        <?php
                                                foreach ($values as $value_item) {
                                        ?>
                                                <div class="url"><?= $value_item ?></div>
                                        <?php
                                        }   }   }
                                        ?>
                                    </div>
                                    <?php endif; ?>
                                </div>

                            </div>

                            <div class="b-right">

                                <!-- Баннеры -->
                                <div class="form-group banners">
                                    <label><?= _t('Баннеры')?></label>
                                    <div>
                                        <table class="table table-striped campaign-banners">
                                            <thead>
                                                <tr>                        
                                                    <th></th>
                                                    <th><span class="sort">Размер</span></th>
                                                    <th><span class="sort">Превью</span></th>
                                                    <th><span class="sort">Показы</span></th>
                                                    <th><span class="sort">Клики</span></th>
                                                    <th><span class="sort">CTR</span></th>
                                                    <th><span class="sort">Расход</span></th>
                                                    <th><span class="sort">eCPM</span></th>
                                                    <th><span class="sort">eCPC</span></th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if($banners): ?>
                                                    <?php foreach($banners as $banner): ?>
                                                        <?php $stat = $banners_stats[$banner['id']]; ?>
                                                        <tr data-id="<?= $banner['id'] ?>">
                                                            <td class="check"><input type="checkbox" <?php if ((bool)$banner['active']): ?>checked<?php endif; ?>></td>
                                                            <td class="stat"><span class="banner-size"><?= $banner['width'] ?>x<?= $banner['height'] ?></span></td>
                                                            <td class="stat"><span class="banner-preview" src="<?= $img_domain ?><?= $banner['img'] ?>" style="background-image: url(<?= $img_domain ?><?= $banner['img'] ?>)"></span></td>
                                                            <td class="stat <?= $target_class ?>"><?= $stat['views'] ?></td>
                                                            <td class="stat"><?= $stat['clicks'] ?></td>
                                                            <td class="stat"><?= $stat['ctr'] ?></td>
                                                            <td class="stat <?= $target_class ?>"><?= formatMoney($stat['money']) ?></td>
                                                            <td class="stat"><?= $stat['cpm'] ?> &#8372;</td>
                                                            <td class="stat"><?= $stat['cpc'] ?> &#8372;</td>
                                                        </tr>
                                                    <?php endforeach ?>
                                                <?php endif ?>
                                            </tbody>
                                        </table>
                                    </div>    
                                </div>

                            </div>

                        </fieldset>
                    </div>
                    
                    <!-- Общая статистика -->
                    <div class="form-group-data stat-common" data-type="stat-common">
                        <div class="b-content__loading"></div>

                        <div class="campaign-stat">

                            <textarea id="campaign-stat"><?= ($campaign_stat ? json_encode($campaign_stat) : '')?></textarea>
                            <textarea id="campaign-stat-total"><?= ($campaign_stat_total ? json_encode($campaign_stat_total) : '')?></textarea>
                            <textarea id="campaign-stat-cats"><?= ($campaign_stat_cats ? json_encode($campaign_stat_cats) : '')?></textarea>
                            
                            <!-- Дата -->
                            <div class="form-group">
                                <label for="campaign-date-begin"><?= _t('Дата')?></label>
                                c:
                                <input type='text' id="campaign-date-begin" class="campaign-date-begin form-control date-value" name="date_begin" value="<?= $campaign_date_begin ?>" />
                                по:
                                <input type='text' id="campaign-date-end" class="campaign-date-end form-control date-value" name="date_end" value="<?= $campaign_date_end ?>" />
                            </div>

                            <div class="chart-graph-stat-info">
                                <h2>По заданным параметрам статистика отсутствует</h2>
                            </div>
                            <div class="chart-graph-stat-error">
                                <h2>Ошибка в статистике</h2>
                                <div class="message"></div>
                            </div>

                            <!-- График -->
                            <div id="chart-graph-stat" data-colors=<?= ($colors_active_lines ? json_encode($colors_active_lines) : '')?>></div>

                            <!-- Таблица -->
                            <div id="table-stat" class="b-table_wrapp">
                                <table id="table-line-common" class="table table-striped common-stat">
                                    <thead class="sortable">
                                        <tr>
                                            <th class="period" data-id="period">
                                                <b class="main-cat selected" data-cat="date">Дата</b>
                                            </th>
                                            <?php foreach($campaign_stat_cats as $name => $cat): ?>
                                            <th class="<?= $name ?>" data-id="<?= $name ?>">
                                                <span style="border-color: <?= $cat['color'] ?>;">
                                                    <input type="checkbox" data-field="<?= $name ?>" checked />
                                                </span>
                                                <b class="cat" id="<?= $name ?>"><?= $cat['title'] ?></b>
                                            </th>
                                            <?php endforeach; ?>
                                        </tr>
                                    </thead>
                                    <tbody>
                                    </tbody>
                                </table>
                            </div>

                        </div>
                    </div>
                    
                    <!-- По сайтам -->
                    <div class="form-group-data stat-sites" data-type="stat-sites">
                        <div class="b-content__loading"></div>
                        <!-- Дата -->
                        <div class="form-group">
                            <label for="campaign-date-begin"><?= _t('Дата')?></label>
                            c:
                            <input type='text' id="campaign-date-begin" class="campaign-date-begin form-control date-value" name="date_begin" value="<?= $campaign_date_begin ?>" />
                            по:
                            <input type='text' id="campaign-date-end" class="campaign-date-end form-control date-value" name="date_end" value="<?= $campaign_date_end ?>" />
                        </div>
                        
                        <div class="sites-stats">
                            <textarea id="campaign-sites-stat"><?= ($sites_stats ? json_encode($sites_stats) : '')?></textarea>
                            
                            <div class="sites-stats-info">
                                <h2>По заданным параметрам статистика отсутствует</h2>
                            </div>
                            
                            <div class="sites-stats-error">
                                <h2>Ошибка в статистике</h2>
                                <div class="message"></div>
                            </div>
                            
                            <div class="b-table_wrapp">
                                <table id="table-line-sites" class="table table-striped table-by-cats">
                                    <thead class="sortable">
                                        <tr>
                                            <th class="period" data-id="period">
                                                <b class="main-cat selected" data-cat="date">Сайт</b>
                                            </th>
                                            <?php foreach($campaign_stat_cats as $name => $cat): ?>
                                            <th class="<?= $name ?>" data-id="<?= $name ?>">
                                                <b class="cat" id="<?= $name ?>"><?= $cat['title'] ?></b>
                                            </th>
                                            <?php endforeach; ?>
                                        </tr>
                                    </thead>
                                    <tbody>
                                    </tbody>
                                </table>
                            </div>
                            
                            
                        </div>
                    </div>
                    
                    <!-- По регионам -->
                    <div class="form-group-data stat-regions" data-type="stat-regions">
                        <div class="b-content__loading"></div>
                        <!-- Дата -->
                        <div class="form-group">
                            <label for="campaign-date-begin"><?= _t('Дата')?></label>
                            c:
                            <input type='text' id="campaign-date-begin" class="campaign-date-begin form-control date-value" name="date_begin" value="<?= $campaign_date_begin ?>" />
                            по:
                            <input type='text' id="campaign-date-end" class="campaign-date-end form-control date-value" name="date_end" value="<?= $campaign_date_end ?>" />
                        </div>
                        
                        <div class="regions-stats">
                            <textarea id="campaign-regions-stat"><?= ($regions_stats ? json_encode($regions_stats) : '')?></textarea>
                            <textarea id="regions-codes"><?= ($code_regions ? json_encode($code_regions) : '')?></textarea>
                            <textarea id="cities-codes"><?= ($code_cities ? json_encode($code_cities) : '')?></textarea>
                            
                            <div class="regions-stats-info">
                                <h2>По заданным параметрам статистика отсутствует</h2>
                            </div>
                            
                            <div class="regions-stats-error">
                                <h2>Ошибка в статистике</h2>
                                <div class="message"></div>
                            </div>
                            
                            <div class="b-table_wrapp">
                                <table id="table-line-regions" class="table table-striped table-by-cats">
                                    <thead class="sortable">
                                        <tr>
                                            <th class="period" data-id="period">
                                                <b class="main-cat selected" data-cat="date">Регион</b>
                                            </th>
                                            <?php foreach($campaign_stat_cats as $name => $cat): ?>
                                            <th class="<?= $name ?>" data-id="<?= $name ?>">
                                                <b class="cat" id="<?= $name ?>"><?= $cat['title'] ?></b>
                                            </th>
                                            <?php endforeach; ?>
                                        </tr>
                                    </thead>
                                    <tbody>
                                    </tbody>
                                </table>
                            </div>
                            
                        </div>
                        
                    </div>
                        
                </div>

            </div>
                
            
        </form>

    </section>

<?php endif; ?>