<?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/jquery.cookie.js')
    ->appendFile('/js/c3.min.js')
    ->appendFile('/js/d3.min.js')
    ->appendFile('/js/datepicker.min.js')
    ->appendFile('/js/adm/amsystem-table-sort.js')
    ->appendFile('/js/adm/amsystem-table-filter.js')
    ->appendFile('/js/adm/amsystem-campaign-edit.js')
    ->appendFile('/js/adm/amsystem-campaign-stats.js')
;

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

$lang = $this->lang;
$error = $this->error;

if (!$error) {

    $campaign = $this->campaign;
    $countries = $this->countries;
    $regions = $this->regions;
    $cities = $this->cities;
    $group = $this->group;
    $user = $this->user;

    $campaign_active = (bool)$campaign->getActive();
    $campaign_archive = (bool)$campaign->getArchive();
    $campaign_id = $campaign->getId();
    $campaign_title = $campaign->getTitle();
    $campaign_url = $campaign->getUrl();
    $campaign_date_begin = $campaign->getDateBegin();
    $campaign_date_end = $campaign->getDateEnd();
    $campaign_buy_type = $group->getBuyType();
    $campaign_target_action = $group->getTargetAction();
    $campaign_price = ($campaign->getPrice()) ? $campaign->getPrice()/10 : null;
    $campaign_tracking_action = (bool)$campaign->getTrackingAction();
    $campaign_order_sum = ($campaign->getOrderSum()) ? $campaign->getOrderSum()/10 : null;
    $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;

    $group_price = ($group->getPrice()) ? $group->getPrice()/10 : null;
    $group_order_sum = ($group->getOrderSum()) ? $group->getOrderSum()/10 : null;
    $group_visitor_limit = json_decode($group->getVisitorLimit(), true);
    $group_money_limit = json_decode($group->getMoneyLimit(), true);
    $group_geo = json_decode($group->getTargeting(), true)['geo'];

    $sites_stats = $this->sites_stats;
    $regions_stats = $this->regions_stats;

    $campaign_stat = $this->campaign_stat;
    $campaign_stat_total = $this->campaign_stat_total;
    $stat_cats = $this->stat_cats;

    $banner_stat_cats = $stat_cats;
    unset($banner_stat_cats['reach']);

    $code_regions = $this->code_regions;
    $code_cities = $this->code_cities;

    $target_class = ($campaign_target_action == 'load') ? 'load-target' : '';

    $link_groups_list = $this->url('user.cabinet.amsystem', ['lang' => $lang]);
    $link_group = $this->url('user.cabinet.group', ['lang' => $lang, 'id' => $group->getId()]);
    $form_link = $this->url('user.cabinet.campaign', ['lang' => $lang, 'id' => $campaign_id]);
    $stat_link = $this->url('user.cabinet.campaigns.stat', ['lang' => $lang, 'id' => $campaign_id]);

    $today = date('Y-m-d');
    $img_domain = $this->img_domain;
    
    $regexp_money = '^\d+([\.|,]\d+)?$';
}

?>

<?= $this->partial('app::user/amsystem/_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">

        <div class="panel panel-info">

            <!-- Header -->
            <div class="panel-heading">
                <h1>
                    <a href="<?=$link_groups_list ?>">Кампании</a> / <a href="<?=$link_group ?>"><?= $group->getTitle() ?></a> /
                    <span class="form-group title" data-type="title">
                        <label class="title-field">Назавние</label>
                        <span class="value-show"><?= $campaign_title ?></span>
                        <span class="value-edit">
                            <input class="form-control campaign-title" type="text" data-field="campaign-title" value="<?= $campaign_title ?>">
                        </span>
                    </span>
                </h1>
            </div>

            <div class="panel-body">

                <!-- Переключатель вкладок -->
                <div class="switch-data" action="<?= $stat_link ?>">
                    <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">
                    <form id="campaign-create-form" method="post" action="<?= $form_link ?>">
                        <fieldset disabled="disabled">

                            <!-- Активность -->
                            <div class="form-group active">
                                <input type="checkbox" id="campaign-active" name="campaign-active" <?php if ($campaign_active): ?>checked<?php endif; ?> <?php if($campaign_archive): ?>disabled<?php endif; ?>>
                                <label class="title-field" for="campaign-active">Кампания активна</label>

                                <?php if(!$campaign_date_end || $today <= $campaign_date_end): ?>
                                    <a class="btn btn-danger action-archive send <?php if($campaign_archive): ?>hidden<?php endif; ?>" href="<?= $form_link ?>"><?= _t('Отправить в архив')?></a>
                                    <a class="btn btn-primary action-archive remove <?php if(!$campaign_archive): ?>hidden<?php endif; ?>" href="<?= $form_link ?>"><?= _t('Извлечь из архива')?></a>
                                <?php endif; ?>
                            </div>

                            <!-- Пользователь -->
                            <div class="form-group">
                                <label class="title-field"><?= _t('Пользователь')?></label>
                                <span><?= $user->getFullname() ?></span>
                            </div>

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

                            <!-- Ссылка -->
                            <div class="form-group url"  data-type="url">
                                <label class="title-field" for="campaign-url"><?= _t('Ссылка')?></label>
                                <div class="value-show">
                                    <a href="<?= $campaign_url ?>" target="_blank"><?= $campaign_url ?></a>
                                </div>
                                <div class="value-edit">
                                    <input type="text" class="form-control" id="campaign-url" name="url" value="<?= $campaign_url ?>" placeholder="<?= _t('ссылка') ?>">
                                </div>
                            </div>

                        </fieldset>
                        
                            <div class="b-left">
                                
                                <fieldset disabled="disabled">
                                
                                    <!-- Тип кампании -->
                                    <div class="form-group">
                                        <label class="title-field"><?= _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; ?>>
                                        <label class="select-item disabled" for="campaign-buy-type-garantee">Гарантия</label>
                                    </div>

                                    <!-- Целевое действие -->
                                    <div class="form-group">
                                        <label class="title-field"><?= _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 price">
                                        <label  class="title-field" for="campaign-price"><?= _t('Стоимость')?></label>
                                        <input id="campaign-price" class="form-control price" name="price" value="<?= $campaign_price ?>" placeholder="<?= $group_price ?>" group-value="<?= $group_price ?>" pattern="<?= $regexp_money ?>" />
                                        грн. за <span class="price-title-mark">1000 показов</span>
                                        <?php if($group_price): ?>
                                            <div class="value-notice">значение для всей группы кампаний</div>
                                        <?php endif; ?>
                                    </div>

                                    <!-- Ограничения на посетителя -->
                                    <div class="form-group campaign-visitor-limit__wrap" data-type="visitor-limit">
                                        <label class="title-field"><?= _t('Ограничения на посетителя')?></label>
                                        <br />
                                        <div class="value-show campaign-value"></div>
                                        <?php if($group_visitor_limit): ?>
                                            <div class="value-show-group">
                                                <?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 ($group_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 class="notice">ограничения для группы</div>
                                            </div>
                                        <?php endif; ?>

                                        <div class="value-edit">
                                            <div class="campaign-visitor-limit view" data-name="view">
                                                <input type="number" min="0" id="campaign-visitor-limit-view-page" class="form-control limit" name="page" data-desc="на странице" value="<?= $campaign_visitor_limit['view']['page'] ?>" /> показов на странице <br />
                                                <input type="number" min="0" id="campaign-visitor-limit-view-hour" class="form-control limit" name="hour" data-desc="в час" value="<?= $campaign_visitor_limit['view']['hour'] ?>" /> показов в час <br />
                                                <input type="number" min="0" id="campaign-visitor-limit-view-day" class="form-control limit" name="day" data-desc="в сутки" value="<?= $campaign_visitor_limit['view']['day'] ?>" /> показов в сутки <br />
                                                <input type="number" min="0" id="campaign-visitor-limit-view-week" class="form-control limit" name="week" data-desc="в неделю" value="<?= $campaign_visitor_limit['view']['week'] ?>" /> показов в неделю <br />
                                                <input type="number" min="0" id="campaign-visitor-limit-view-month" class="form-control limit" name="month" data-desc="в месяц" value="<?= $campaign_visitor_limit['view']['month'] ?>" /> показов в месяц
                                            </div>
                                            <div class="campaign-visitor-limit click" data-name="click">
                                                <input type="number" min="0" id="campaign-visitor-limit-click-page" class="form-control limit" name="page" data-desc="на странице" value="<?= $campaign_visitor_limit['click']['page'] ?>" /> кликов на странице <br />
                                                <input type="number" min="0" id="campaign-visitor-limit-click-hour" class="form-control limit" name="hour" data-desc="в час" value="<?= $campaign_visitor_limit['click']['hour'] ?>" /> кликов в час <br />
                                                <input type="number" min="0" id="campaign-visitor-limit-click-day" class="form-control limit" name="day" data-desc="в сутки" value="<?= $campaign_visitor_limit['click']['day'] ?>" /> кликов в сутки <br />
                                                <input type="number" min="0" id="campaign-visitor-limit-click-week" class="form-control limit" name="week" data-desc="в неделю" value="<?= $campaign_visitor_limit['click']['week'] ?>" /> кликов в неделю <br />
                                                <input type="number" min="0" id="campaign-visitor-limit-click-month" class="form-control limit" name="month" data-desc="в месяц" value="<?= $campaign_visitor_limit['click']['month'] ?>" /> кликов в месяц
                                            </div>
                                        </div>
                                        <div class="b-clear"></div>
                                    </div>

                                    <!-- Бюджет -->
                                    <div class="form-group campaign-money-limit" data-type="money-limit">
                                        <label class="title-field"><?= _t('Бюджет')?></label>
                                        <br />
                                        <div class="value-show campaign-value"></div>
                                        <?php if($group_money_limit): ?>
                                            <div class="value-show-group">
                                                <?php 
                                                foreach ($group_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 class="notice">ограничения для группы</div>
                                            </div>
                                        <?php endif; ?>
                                        <div class="value-edit">
                                            <div class="campaign-money-limit-values">
                                                <input id="campaign-money-limit-total" class="form-control limit" name="total" data-desc="всего" value="<?= $campaign_money_limit['total'] ?>" pattern="<?= $regexp_money ?>" /> грн. всего <br />
                                                <input id="campaign-money-limit-day" class="form-control limit" name="day" data-desc="в сутки" value="<?= $campaign_money_limit['day'] ?>" pattern="<?= $regexp_money ?>" /> грн. в сутки <br />
                                                <input id="campaign-money-limit-week" class="form-control limit" name="week" data-desc="в неделю" value="<?= $campaign_money_limit['week'] ?>" pattern="<?= $regexp_money ?>" /> грн. в неделю <br />
                                                <input id="campaign-money-limit-month" class="form-control limit" name="month" data-desc="в месяц" value="<?= $campaign_money_limit['month'] ?>" pattern="<?= $regexp_money ?>" /> грн. в месяц
                                            </div>
                                        </div>
                                        <div class="b-clear"></div>
                                    </div>

                                    <!-- Скорость открута -->
                                    <div class="form-group">
                                        <label class="title-field"><?= _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 ($group_geo): ?>group-geo<?php endif; ?>" data-type="geo">
                                        <label class="title-field"><?= _t('Гео (таргетинг)')?></label>
                                        <div class="value-show"></div>

                                        <?php if ($group_geo): ?>
                                            <div class="value-show-group geo">
                                                <textarea id="group-targeting-value" style="display: none"><?= $group->getTargeting() ?></textarea>
                                                <?php if ($group_geo['country']): ?>
                                                    <?php
                                                    $title_values = $countries[$group_geo['country']['values'][0]];
                                                    if ($group_geo['special']) {
                                                        $title_special = '<b>(исключить неподконтрольные территории)</b>';
                                                    }
                                                    ?>
                                                    <span><?= 'Страна' ?>: <b><?= $title_values ?></b> <?= $title_special ?></span><br />
                                                <?php endif; ?>
                                                <?php if ($group_geo['region']['values']): ?>
                                                    <?php
                                                    $title_mark = ($group_geo['region']['exclude']) ? 'кроме': 'только';
                                                    $title_values = [];
                                                    foreach ($group_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 ($group_geo['city']['values']): ?>
                                                    <?php
                                                    $title_mark = ($group_geo['city']['exclude']) ? 'кроме': 'только';
                                                    $title_values = [];
                                                    foreach ($group_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 class="geo-notice">значение для всей группы кампаний</div>
                                            </div>
                                        <?php endif; ?>

                                        <?php
                                            if (!$campaign_geo) {
                                                $campaign_geo = $group_geo;
                                            }
                                        ?>

                                        <div class="value-edit">
                                            <div class="targeting_geo">
                                                <!-- country -->
                                                <div class="geo_country">
                                                    Страна:
                                                    <select class="form-control" id="targeting_geo_country" name="targeting_geo_country" disabled>
                                                        <?php foreach($countries as $code=>$title): ?>
                                                            <option value="<?= $code ?>" <?php if ($campaign_geo['country']['values'] && in_array($code, $campaign_geo['country']['values'])): ?>selected<?php endif; ?>><?= _t($title) ?></option>
                                                        <?php endforeach ?>
                                                    </select>
                                                    <span class="b-exclude">
                                                        <input type="checkbox" id="country-exclude" name="country-exclude" <?php if ($campaign_geo['special']['exclude'] || !$campaign_geo): ?>checked<?php endif; ?>>
                                                        <label for="country-exclude"><?= _t('исключить неподконтрольные территории')?></label>
                                                    </span>
                                                </div>

                                                <div class="geo_region-city">
                                                    <!-- region -->
                                                    <div class="geo_region-wrap">
                                                        <div class="geo_region">
                                                            <div class="form-group">
                                                                <label for="region-list"><?= _t('Области')?></label>
                                                                <div class="b-exclude">
                                                                    <input type="checkbox" id="region-exclude" name="region-exclude" <?php if ((bool)$campaign_geo['region']['exclude']): ?>checked<?php endif; ?>>
                                                                    <label for="region-exclude"><?= _t('исключить')?></label>
                                                                </div>
                                                                <div>
                                                                    <div class="filters-select">
                                                                        <div class="region-val-geo">
                                                                            <input type="text" class="form-control filter" id="region-filter" name="region-filter" value="" placeholder="фильтр">
                                                                        </div>
                                                                        <div class="list-filters-wrap">
                                                                            <ul class="list-filter">
                                                                                <?php foreach($regions as $id=>$data): ?>
                                                                                    <li>
                                                                                        <input type="checkbox" id="region-id-<?= $id ?>" data-id="<?= $id ?>" data-text="<?= $data['name'] ?>" <?php if ($campaign_geo['region']['values'] && in_array($id, $campaign_geo['region']['values'])): ?>checked<?php endif; ?>>
                                                                                        <label for="region-id-<?= $id ?>"><?= $data['name'] ?></label>
                                                                                    </li>
                                                                                <?php endforeach ?>
                                                                            </ul>
                                                                        </div>
                                                                    </div>
                                                                    <div class="filters-values">
                                                                        <ul class="values-string-list">
                                                                            <?php if($campaign_geo['region']['values']): ?>
                                                                                <?php foreach($campaign_geo['region']['values'] as $id): ?>
                                                                                    <li>
                                                                                        <input type="checkbox" checked id="l-region-id-<?= $id ?>" data-id="<?= $id ?>" data-text="<?= $regions[$id]['name'] ?>">
                                                                                        <label for="l-region-id-<?= $id ?>"><?= $regions[$id]['name'] ?></label>
                                                                                    </li>
                                                                                <?php endforeach ?>
                                                                            <?php endif; ?>
                                                                        </ul>    
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <!-- city -->
                                                    <div class="geo_city-wrap">
                                                        <div class="geo_city">
                                                            <div class="form-group">
                                                                <label for="city-list"><?= _t('Города')?></label>
                                                                <div class="b-exclude">
                                                                    <input type="checkbox" id="city-exclude" name="city-exclude" <?php if ((bool)$campaign_geo['city']['exclude']): ?>checked<?php endif; ?>>
                                                                    <label for="city-exclude"><?= _t('исключить')?></label>
                                                                </div>
                                                                <div>
                                                                    <div class="filters-select">
                                                                        <input type="text" class="form-control filter" id="city-filter" name="city-filter" value="" placeholder="фильтр">
                                                                        <div class="list-filters-wrap">
                                                                            <ul class="list-filter">
                                                                                <?php foreach($cities as $id=>$data): ?>
                                                                                    <li>
                                                                                        <input type="checkbox" id="city-id-<?= $id ?>" data-id="<?= $id ?>" data-text="<?= $data['name'] ?>" <?php if ($campaign_geo['city']['values'] && in_array($id, $campaign_geo['city']['values'])): ?>checked<?php endif; ?>>
                                                                                        <label for="city-id-<?= $id ?>"><?= $data['name'] ?></label>
                                                                                    </li>
                                                                                <?php endforeach ?>
                                                                            </ul>    
                                                                        </div>
                                                                    </div>
                                                                    <div class="filters-values">
                                                                        <ul class="values-string-list">
                                                                            <?php if($campaign_geo['city']['values']): ?>
                                                                            <?php foreach($campaign_geo['city']['values'] as $id): ?>
                                                                                <li>
                                                                                    <input type="checkbox" checked id="l-city-id-<?= $id ?>" data-id="<?= $id ?>" data-text="<?= $cities[$id]['name'] ?>">
                                                                                    <label for="l-region-id-<?= $id ?>"><?= $cities[$id]['name'] ?></label>
                                                                                </li>
                                                                            <?php endforeach ?>
                                                                            <?php endif; ?>
                                                                        </ul>    
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>

                                            </div>
                                        </div>
                                    </div>

                                    <!-- Трекинг -->
                                    <div class="form-group tracking_pixels" data-type="tracking-pixels" data-value="">
                                        <label class="title-field"><?= _t('Трекинг')?></label>
                                        <div class="value-show"></div>
                                        <div class="value-edit">
                                            <?php
                                                $items = [
                                                    'load' => 'Показ',
                                                    'view' => 'Реальный показ',
                                                    'click' => 'Клик'
                                                ]
                                            ?>
                                            <?php foreach( $items as $item => $title): ?>
                                                <div class="form-group tracking_pixels_item <?= $item ?>" data-name="<?= $item ?>" data-value="[]">
                                                    <label><?= $title ?></label>
                                                    <div class="tracking_pixels_urls">
                                                        <?php if($campaign_tracking_pixels[$item]): ?>
                                                            <?php foreach ($campaign_tracking_pixels[$item] as $url) : ?>
                                                                <div class="url-item">
                                                                    <input type="text" class="form-control" value="<?= $url ?>" placeholder="url">
                                                                    <div class="delete-item">×</div>
                                                                </div>
                                                            <?php endforeach; ?>
                                                        <?php endif; ?>
                                                    </div>
                                                    <div class="add-row">+ Добавить</div>
                                                </div>
                                            <?php endforeach ?>
                                        </div>

                                    </div>

                                </fieldset>
                                
                            </div>

                            <div class="b-right">

                                <!-- Баннеры -->
                                <div class="form-group banners">

                                    <label class="title-field"><?= _t('Баннеры')?></label>
                                    <select class="form-control banners-status">
                                        <option value="all"><?= _t('все') ?></option>
                                        <option value="active"><?= _t('активные') ?></option>
                                        <option value="not-active"><?= _t('не активные') ?></option>
                                    </select>
                                    <div>
                                        <table class="table campaign-banners">
                                            <thead>
                                                <tr>                        
                                                    <th></th>
                                                    <th>Размер</th>
                                                    <th>Превью</span></th>
                                                    <?php foreach ($banner_stat_cats as $cat => $cat_data) : ?>
                                                        <th class="stat"><span class="sort" data-sort="<?= $cat ?>" data-sortasc="1"><?= $cat_data['title'] ?></span></th>
                                                    <?php endforeach; ?>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if($banners): ?>
                                                    <?php foreach($banners as $banner): ?>
                                                        <?php
                                                        $stat = $banners_stats[$banner['id']];
                                                        $tr_class = '';
                                                        if ((bool)$banner['active']) {
                                                            $tr_class.= 'active';
                                                        } else {
                                                            $tr_class.= 'not-active';
                                                        }
                                                        ?>
                                                        <tr data-id="<?= $banner['id'] ?>" class="banner-item <?= $tr_class ?>">
                                                            <td class="check"><input type="checkbox" <?php if ((bool)$banner['active']): ?>checked<?php endif; ?>></td>
                                                            <td><span class="banner-size"><?= $banner['width'] ?>x<?= $banner['height'] ?></span></td>
                                                            <td><span class="banner-preview" src="<?= $img_domain ?><?= $banner['img'] ?>" style="background-image: url(<?= $img_domain ?><?= $banner['img'] ?>)"></span></td>
                                                            <?php foreach ($banner_stat_cats as $cat => $cat_data) : ?>
                                                                <?php
                                                                $target_class_item = (in_array($cat, ['views', 'money'])) ? $target_class : '';
                                                                ?>
                                                                <td class="stat <?= $cat ?> <?= $target_class_item ?>" data-cat="<?= $cat ?>" data-value="<?= $stat[$cat] ?>"><?= formatField($stat[$cat], $cat) ?></td>
                                                            <?php endforeach; ?>
                                                        </tr>
                                                    <?php endforeach ?>
                                                <?php endif ?>
                                            </tbody>
                                            <tfoot>
                                                <tr class="total">
                                                    <td colspan="3">Суммарно</td>
                                                    <?php foreach ($banner_stat_cats as $cat => $cat_data) : ?>
                                                        <?php
                                                        $target_class_item = (in_array($cat, ['views', 'money'])) ? $target_class : '';
                                                        ?>
                                                        <td class="stat <?= $cat ?> <?= $target_class_item ?>"></td>
                                                    <?php endforeach; ?>
                                                </tr>
                                            </tfoot>
                                        </table>
                                    </div>    
                                </div>

                            </div>

                            <div class="b-clear"></div>
                            
                            <!-- Трекинг действий -->
                            <fieldset disabled="disabled">
                            <div class="form-group tracking-action"  data-type="tracking-action" >
                                <input type="checkbox" id="group-tracking-action" name="group-tracking-action" <?php if ($campaign_tracking_action): ?>checked<?php endif; ?>>
                                <label class="title-field" for="group-active">Трекинг действий</label>
                                <div class="tracking-action_content">
                                    <div class="tracking-action_link">
                                        http://order.azbne.net/b/order?&campaign_id={CAMPAIGN_ID}&click_id={CLICK_ID}&order_sum={ORDER_SUM}&order_id={ORDER_ID}
                                    </div>
                                    <!-- Цена действия по-умолчанию -->
                                    <div class="form-group order-sum"  data-type="order-sum">
                                        <label for="group-order-sum"><?= _t('Цена действия по-умолчанию')?></label>
                                        <input id="campaign-order-sum" class="form-control order-sum" name="order_sum" value="<?= $campaign_order_sum ?>" placeholder="<?= $group_order_sum ?>" pattern="<?= $regexp_money ?>" />
                                        грн.
                                        <?php if($group_order_sum): ?>
                                            <div class="value-notice">значение для всей группы кампаний</div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                            </fieldset>

                    </form>
                </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"><?= ($stat_cats ? json_encode($stat_cats) : '')?></textarea>

                        <!-- Дата -->
                        <div class="form-group">
                            <label for="campaign-date-begin"><?= _t('Дата')?></label>
                            c:
                            <input type='text' id="campaign-date-begin-common" class="campaign-date-begin form-control date-value" name="date_begin" value="<?= $campaign_date_begin ?>" autocomplete="off" />
                            по:
                            <input type='text' id="campaign-date-end-common" class="campaign-date-end form-control date-value" name="date_end" value="<?= $campaign_date_end ?>" autocomplete="off" />
                        </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 sortable" data-type="common-stat">
                                <thead class="sortable">
                                    <tr>
                                        <th class="period" data-id="period">
                                            <b class="sort" id="period">Дата</b>
                                        </th>
                                        <?php foreach($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="sort" 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-sites" class="campaign-date-begin form-control date-value" name="date_begin" value="<?= $campaign_date_begin ?>" autocomplete="off" />
                        по:
                        <input type='text' id="campaign-date-end-sites" class="campaign-date-end form-control date-value" name="date_end" value="<?= $campaign_date_end ?>" autocomplete="off" />
                    </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 sortable" data-type="sites-stat">
                                <thead class="sortable">
                                    <tr>
                                        <th class="period" data-id="period">
                                            <b>Сайт</b>
                                        </th>
                                        <?php foreach($stat_cats as $name => $cat): ?>
                                        <th class="<?= $name ?>" data-id="<?= $name ?>">
                                            <b class="sort" 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-regions" class="campaign-date-begin form-control date-value" name="date_begin" value="<?= $campaign_date_begin ?>" autocomplete="off" />
                        по:
                        <input type='text' id="campaign-date-end-regions" class="campaign-date-end form-control date-value" name="date_end" value="<?= $campaign_date_end ?>" autocomplete="off" />
                    </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 sortable" data-type="regions-stat">
                                <thead class="sortable">
                                    <tr>
                                        <th class="period" data-id="period">
                                            <b>Регион</b>
                                        </th>
                                        <?php foreach($stat_cats as $name => $cat): ?>
                                        <th class="<?= $name ?>" data-id="<?= $name ?>">
                                            <b class="sort" id="<?= $name ?>"><?= $cat['title'] ?></b>
                                        </th>
                                        <?php endforeach; ?>
                                    </tr>
                                </thead>
                                <tbody>
                                </tbody>
                            </table>
                        </div>

                    </div>

                </div>

            </div>

        </div>
        
    </section>

<?php endif; ?>