<?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/adm/amsystem-campaign.js')
    
;

$this->headLink()
    ->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_user_id = $campaign->getUserId();
    $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;
    $campaign_stat = $this->campaign_stat;

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

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

?>

<?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="">
            <fieldset disabled="disabled">
            <div class="panel panel-info">

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

                <div class="panel-body">

                    <!-- Активность и Название -->
                    <div class="form-group title">
                        <input type="checkbox" id="campaign-active" name="campaign-active" <?php if ($campaign_active): ?>checked<?php endif; ?>>
                        <label class="campaign-title"><?= $campaign_title ?></label>
                    </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">
                            <label><?= _t('Гео (таргетинг)')?></label>
                            <div class="value-show">
                                <?php if ($campaign_geo): ?>
                                    <?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; ?>
                                <?php endif; ?>
                            </div>
                        </div>

                        <!-- Трекинг -->
                        <div class="form-group 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>
                        </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="<?= $banner['img'] ?>" style="background-image: url(<?= $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 ?>"><?= $stat['money'] ?></td>
                                                    <td class="stat"><?= $stat['cpm'] ?></td>
                                                    <td class="stat"><?= $stat['cpc'] ?></td>
                                                </tr>
                                            <?php endforeach ?>
                                        <?php endif ?>
                                    </tbody>
                                </table>
                            </div>    
                        </div>

                    </div>
                    
                    <div class="b-clear"></div>
                    
                    <div class="campaign-stat">
                        <textarea id="campaign-stat"><?= ($campaign_stat ? json_encode($campaign_stat) : '')?></textarea>

                        <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"></div>
                        
                        <div id="table-stat"></div>
                        
                    </div>

                </div>
                
                

            </div>
                
            </fieldset>
        </form>

    </section>

<?php endif; ?>