
	<!-- Page header -->
	{capture name="buttons"}
	{/capture}

	{capture name="breadcrumb"}
		<a href="{$adminUrl}/yandex" class="breadcrumb-item">Яндекс метрика</a>
	{/capture}

	{capture name="showBy"}
		<a href="{$adminUrl}/yandex?action=setting" class="breadcrumb-elements-item"><i class="icon-gear mr-2"></i> Настройка яндекс метрики</a>
	{/capture}

	{include file="components/page-header.tpl" buttons=$smarty.capture.buttons breadcrumb=$smarty.capture.breadcrumb showBy=$smarty.capture.showBy}
	<!-- /page header -->

	{if isset($action) && $action eq 'setting'}

		<div class="content">
			<form method="post" id="settings" autocomplete="off" class="form-content-wrapper">
			<div class="card border shadow-sm">
				<div class="card-header d-flex flex-wrap">
					<h6 class="mb-0">{general:card:general}</h6>
					<div class="d-inline-flex ms-auto">
						<a class="text-body" data-card-action="collapse"><i class="ph-caret-down"></i></a>
					</div>
				</div>
				<div class="collapse show">
					<div class="card-body">
						<fieldset class="">
		{*					{$yandex|print_r}*}
							<div class="form-group row">
									<label class="col-form-label col-lg-6">Идентификатор счетчика<br />
										<span class="p-0 font-size-sm font-italic text-muted">Взять идентификатор счетчика можно <a href="https://metrika.yandex.ru/list" target="_blank">здесь</a></span>
									</label>
									<div class="col-lg-6">
										<input class="form-control" type="text" name="yandex[counterId]" placeholder="xxxxxxxxxx" value="{$yandex.counterId|default:''}">
									</div>
								</div>
								<div class="form-group row">
									<label class="col-form-label col-lg-6">Токен<br />
										<span class="p-0 font-size-sm font-italic text-muted">
											Токен нужен для получение статистики(метрики)<br />
											для получения токена нужно <br />
											1 <a href="https://oauth.yandex.ru/client/new" target="_blank">создать приложение</a> и в приложение указать адрес, на который пользователь возвращается после того, как он разрешил или отказал приложению в доступе. Соответствует redirect_url протокола OAuth. <code>https://oauth.yandex.ru/verification_code</code><br />
											2 Запрос на токен <code>https://oauth.yandex.ru/authorize?response_type=token&client_id=ClientID</code>, ClientID - Это идентификатор вашего приложения. Используйте его в запросах для получения OAuth-токена<br />
										</span>
									</label>
									<div class="col-lg-6">
										<input type="text" class="form-control" id="token" name="yandex[token]" placeholder="xxxxxxxxxxxxxxxxxx"  value="{$yandex.token|default:''}" />
									</div>
								</div>
							<div class="form-group row">
								<label class="col-form-label col-lg-6">Код метрики<br />
									<span class="p-0 font-size-sm font-italic text-muted">
										При установке счетчика в HTML-код сайта, разместите код как можно ближе к началу страницы. <br />
										Например, в пределах тегов <code>head</code> или <code>body</code>.<br />
										Для вывода используется синтаксис smarty <code>{ }</code></span>
		<pre class="line-numbers mb-0 language-markup code-toolbar">
		&lt;!-- yandex_metrika_new --&gt;
		</pre>

								</label>
								<div class="col-lg-6">
									<textarea rows="5" cols="3" class="form-control" name="yandex[code]" >{$yandex.code|default:''}</textarea>
								</div>
							</div>
							</fieldset>

					</div>
				</div>
			</div>
			<div class="col-md-12 main main_buttons text-center">
				<button class="btn btn-sm btn-primary" type="submit" name="action" value="save" >&nbsp; {general:save} &nbsp;</button>
				<a class="btn btn-sm btn-light" href="{$adminUrl}/yandex">{general:cancel}</a>
			</div>
			</form>
		</div>

	{else}

	<div class="content">
	    <div class="row">
	        <div class="col-md-12">
	            {if isset($message.token_counter)}
		        <div class="alert bg-warning text-white alert-styled-left alert-dismissible">
			        <span class="font-weight-semibold">Предупреждение!</span>
			        Для просмотра статистики необходимо в <a href="{$adminUrl}/yandex?action=setting" class="alert-link">настройках</a> ввести "<span class="font-weight-semibold">Идентификатор счетчика</span>" и "<span class="font-weight-semibold">Токен</span>
		        </div>
	            {/if}

		        <div class="card">
			        {include file="views/stats/form/selectors.tpl" action="" select=''}
		        </div>

	            {if isset($visitors) && !empty($visitors)}
	            <div class="card border shadow-sm">
		            <div class="card-body">
			            <div class="chart-container">
		                    <div class="chart has-fixed-height" id="stats_users"></div>
			            </div>
		            </div>
	                <table class="table table-bordered table-xs table-striped table-actions">
	                    <thead>
	                        <tr>
	                            <th class="text-center">Итого и средние</th>
	                            <th class="text-center">Визиты</th>
	                            <th class="text-center">Просмотры</th>
	                            <th class="text-center">Посетители</th>
	                        </tr>
	                    </thead>
		                <tbody>
			                <tr class="">
				                <td class="text-nowrap">Итого и средние</td>
				                <td  class="text-left"><span>{$visitors.totals.visits}</span></td>
				                <td class="text-left"><span>{$visitors.totals.pageviews}</span></td>
				                <td class="text-left"><span>{$visitors.totals.users}</span></td>
			                </tr>
		                </tbody>
	                </table>
	            </div>
		        {/if}

		        <div class="card border shadow-sm">
			        <div class="card-header d-flex flex-wrap">
				        <h6 class="mb-0">Популярность страниц</h6>
				        <div class="d-inline-flex ms-auto">
					        <a class="text-body" data-card-action="collapse"><i class="ph-caret-down"></i></a>
				        </div>
			        </div>
			        <div class="collapse show">
				        <div class="">
					        <table class="table table-bordered table-xs table-striped table-actions">
						        <thead>
						        <tr>
							        <th class="text-left">Адрес страницы</th>
							        <th class="text-left">Просмотры</th>
						        </tr>
						        </thead>
			                    {if isset($viewedPages) && !empty($viewedPages)}
							        <tbody>
			                        {foreach item=visitor from=$viewedPages.data}
								        <tr class="">
									        <td class="text-nowrap"><a href="https://{$visitor.dimensions.URLPathFull.favicon}{$visitor.dimensions.URLPathFull.name}" target="_blank">{$visitor.dimensions.title.name}</a></td>
									        <td class="text-nowrap"><span>{$visitor.metrics.pageviews}</span></td>
								        </tr>
			                        {/foreach}
							        </tbody>
			                    {else}
							        <tbody><tr class="odd"><td class="data none" colspan="4" align="center">- {general:none} -</td></tr></tbody>
			                    {/if}

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

		        <div class="card border shadow-sm">
			        <div class="card-header d-flex flex-wrap">
				        <h6 class="mb-0">Последняя поисковая фраза</h6>
				        <div class="d-inline-flex ms-auto">
					        <a class="text-body" data-card-action="collapse"><i class="ph-caret-down"></i></a>
				        </div>
			        </div>
			        <div class="collapse show">
				        <div class="">
					        <table class="table table-togglable table-xs table-striped table-hover">
						        <thead>
						        <tr>
							        <th class="text-left">Последняя поисковая фраза</th>
							        <th class="text-left">Визиты</th>
							        <th class="text-left">Посетители</th>
						        </tr>
						        </thead>
						        {if isset($phrases) && !empty($phrases)}
							        <tbody>
			                        {foreach item=visitor from=$phrases.data}
								        <tr class="">
									        <td class="text-nowrap">{$visitor.dimensions.lastSignSearchPhrase.name}</td>
									        <td class=""><span>{$visitor.metrics.visits}</span></td>
									        <td class="text-left"><span>{$visitor.metrics.users}</span></td>
								        </tr>
			                        {/foreach}
							        </tbody>
			                    {else}
							        <tbody><tr class="odd"><td class="data none" colspan="4" align="center">- {general:none} -</td></tr></tbody>
			                    {/if}

					        </table>
				        </div>
			        </div>
		        </div>
	        </div>
	        {if isset($browsers) && !empty($browsers)}
		    <div class="col-md-6">
		        <div class="card border shadow-sm">
			        <div class="card-body">
				        <div class="chart-container"><div class="chart has-fixed-height" id="pie_browser"></div></div>
			        </div>
		        </div>
		    </div>
		    {/if}
	        {if isset($ages) && !empty($ages)}
		    <div class="col-md-6">
			    <div class="card border shadow-sm">
				    <div class="card-body">
					    <div class="chart-container"><div class="chart has-fixed-height" id="pie_age"></div></div>
				    </div>
			    </div>
		    </div>
	        {/if}
			<div class="col-md-12">
		        <div class="card border shadow-sm">
			        <div class="card-header d-flex flex-wrap">
				        <h6 class="mb-0">Пользователи по странам и регионам</h6>
				        <div class="d-inline-flex ms-auto">
					        <a class="text-body" data-card-action="collapse"><i class="ph-caret-down"></i></a>
				        </div>
			        </div>
			        <div class="collapse show">
				        <div class="">
					        <table class="table table-togglable table-xs table-striped table-hover">
						        <thead>
							        <tr>
								        <th class="text-center">Страна / регион</th>
								        <th class="text-center">Просмотры</th>
							        </tr>
						        </thead>
			                    {if isset($geoForPeriod) && !empty($geoForPeriod)}
							        <tbody>
			                        {foreach item=visitor from=$geoForPeriod.data}
								        <tr class="">
									        <td class="text-nowrap">{$visitor.dimensions.regionCountry.name} / {$visitor.dimensions.regionArea.name}</td>
									        <td class="text-nowrap"><span>{$visitor.metrics.visits}</span></td>
								        </tr>
			                        {/foreach}
							        </tbody>
			                    {else}
							        <tbody><tr class="odd"><td class="data none" colspan="4" align="center">- {general:none} -</td></tr></tbody>
			                    {/if}

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

		        <div class="card border shadow-sm">
			        <div class="card-header d-flex flex-wrap">
				        <h6 class="mb-0">Пользователи из поисковых систем</h6>
				        <div class="d-inline-flex ms-auto">
					        <a class="text-body" data-card-action="collapse"><i class="ph-caret-down"></i></a>
				        </div>
			        </div>
			        <div class="collapse show">
				        <div class="">
				            <table class="table table-togglable table-xs table-striped table-hover">
					        <thead>
					        <tr>
						        <th class="text-center">Поисковые системы</th>
						        <th class="text-center">Просмотры</th>
						        <th class="text-center">Посетители</th>
					        </tr>
					        </thead>
		                    {if isset($usersSearchEngine) && !empty($usersSearchEngine)}
						        <tbody>
		                        {foreach item=visitor from=$usersSearchEngine.data}
							        <tr class="">
								        <td class="text-nowrap">{$visitor.dimensions.searchEngine.name}</td>
								        <td class="text-nowrap"><span>{$visitor.metrics.visits}</span></td>
								        <td class="text-nowrap"><span>{$visitor.metrics.users}</span></td>
							        </tr>
		                        {/foreach}
						        </tbody>
		                    {else}
						        <tbody><tr class="odd"><td class="data none" colspan="4" align="center">- {general:none} -</td></tr></tbody>
		                    {/if}
				        </table>
				        </div>
			        </div>
		        </div>

	        </div>
	    </div>
	</div>
	<script src="{$adminUrl}/assets/js/vendor/visualization/echarts/echarts.min.js"></script>
	<script>
		{literal}
	    var EchartsPiesDonuts = function() {
	        var _piesDonutsExamples = function() {
	            if (typeof echarts == 'undefined') {
	                console.warn('Warning - echarts.min.js is not loaded.');
	                return;
	            }

	            // Define elements
	            var stats_users_element = document.getElementById('stats_users');
	            var pie_browser_element = document.getElementById('pie_browser');
	            var pie_age_element = document.getElementById('pie_age');

	            // Basic pie chart
	            if (pie_browser_element) {
	                {/literal} {if isset($browsers) && !empty($browsers)}{literal}
	                var pie_browser = echarts.init(pie_browser_element);
	                pie_browser.setOption({
	                    color: ['#2ec7c9','#b6a2de','#5ab1ef','#ffb980','#d87a80', '#8d98b3','#e5cf0d','#97b552','#95706d','#dc69aa',
	                        '#07a2a4','#9a7fd1','#588dd5','#f5994e','#c05050', '#59678c','#c9ab00','#7eb00a','#6f5553','#c14089'
	                    ],
	                    textStyle: { fontFamily: 'Roboto, Arial, Verdana, sans-serif', fontSize: 13 },
	                    title: { text: 'Популярные браузеры', subtext: 'Информация из яндекс метрики', left: 'center', textStyle: { fontSize: 17, fontWeight: 500 }, subtextStyle: { fontSize: 12 } },
	                    tooltip: { trigger: 'item', backgroundColor: 'rgba(0,0,0,0.75)', padding: [10, 15], textStyle: { fontSize: 13, fontFamily: 'Roboto, sans-serif' },
	                        formatter: "{a} <br/>{b}: {c} ({d}%)"
	                    },
	                    legend: {
	                        orient: 'vertical', top: 'center', left: 0,
	                        data: [{/literal}{foreach item=visitor from=$browsers.data name=browsers}"{$visitor.dimensions.browser.name|truncate:20}"{if !$smarty.foreach.browsers.last},{/if} {/foreach}{literal}],
	                        itemHeight: 8, itemWidth: 8
	                    },

	                    // Add series
	                    series: [{
	                        name: 'Браузер',
		                    type: 'pie',
		                    radius: '70%',
		                    center: ['50%', '57.5%'],
		                    itemStyle: { normal: { borderWidth: 1, borderColor: '#fff' } },
	                        data: [
	                            {/literal}{foreach item=visitor from=$browsers.data name=browsers}{if !$smarty.foreach.browsers.last},{/if} {literal}
	                            { value: {/literal}{$visitor.metrics.visits}{literal}, name: '{/literal}{$visitor.dimensions.browser.name|truncate:20}{literal}' }
	                            {/literal}{if !$smarty.foreach.browsers.last},{/if} {/foreach}{literal}
	                        ]
	                    }]
	                });
	                {/literal}{/if}{literal}
	            }


	            if (pie_age_element) {
	                {/literal} {if isset($ages) && !empty($ages)}{literal}
	                var pie_age = echarts.init(pie_age_element);

	                pie_age.setOption({

	                    color: [ '#80FFA5', '#37A2FF', '#FF0087', '#FFBF00',
		                    '#7eb00a', '#dc69aa', '#b6a2de',  '#9a7fd1',
	                        '#07a2a4', '#2ec7c9', '#5ab1ef', '#588dd5'
	                    ],

	                    textStyle: { fontFamily: 'Roboto, Arial, Verdana, sans-serif', fontSize: 13 },
	                    title: {
	                        text: 'Возраст',
		                    subtext: 'Информация по возрасту пользователей из яндекс метрики',
		                    left: 'center',
		                    textStyle: { fontSize: 17, fontWeight: 500 }, subtextStyle: { fontSize: 12 }
	                    },
	                    tooltip: {
	                        trigger: 'item',
		                    backgroundColor: 'rgba(0,0,0,0.75)',
		                    padding: [10, 15],
		                    textStyle: { fontSize: 13, fontFamily: 'Roboto, sans-serif' },
	                        formatter: "{b} &nbsp; {c} ({d}%)"
	                    },
	                    legend: {
	                        orient: 'vertical', top: 'bottom', left: 0,
	                        data: [{/literal}{foreach item=age from=$ages.data name=age}"{$age.dimensions.ageInterval.name}"{if !$smarty.foreach.ages.last},{/if} {/foreach}{literal}],
	                    },
	                    series: [{
	                        type: 'pie', radius: '70%', center: ['50%', '57.5%'], itemStyle: { normal: { borderWidth: 1, borderColor: '#fff' } },
	                        data: [
	                            {/literal}{foreach item=age from=$ages.data name=ages}{if !$smarty.foreach.ages.last},{/if} {literal}
	                            { value: {/literal}{$age.metrics.visits}{literal}, name: '{/literal}{$age.dimensions.ageInterval.name}{literal}' }
	                            {/literal}{if !$smarty.foreach.ages.last},{/if} {/foreach}{literal}
	                        ]
	                    }]
	                });
	                {/literal}{/if}{literal}
	            }

	            {/literal}{if isset($visitors)}{literal}

	            if (stats_users_element) {
	                var users_element = echarts.init(stats_users_element);
	                users_element.setOption({
	                    title: { text: 'Yandex статистика', subtext: 'Данные по посещаемости' },
	                    color: ['rgb(195, 176, 250)','rgb(232, 176, 250)','#5ab1ef','#ffb980','#d87a80'],
	                    textStyle: { fontFamily: 'Roboto, Arial, Verdana, sans-serif', fontSize: 13 },
	                    animationDuration: 750,
	                    grid: { left: 0, right: 60, top: 70, bottom: 0, containLabel: true },
	                    legend: {
	                        data: [ 'Визиты', 'Просмотры', 'Посетители' ],
	                        itemHeight: 8,
	                        itemGap: 20,
	                        textStyle: { padding: [0, 5] }
	                    },

	                    tooltip: { trigger: 'axis', backgroundColor: 'rgba(0,0,0,0.75)', padding: [10, 15], textStyle: { fontSize: 13, fontFamily: 'Roboto, sans-serif' } },

	                    xAxis: [{
		                    type: 'category',
	                        data: [{/literal}{foreach item=visitor from=$visitors.data name=visitors} '{$visitor.dimensions.date.name}'{if !$smarty.foreach.visitors.last},{/if} {/foreach}{literal}],
	                        axisLabel: { color: '#333' },
	                        axisLine: { lineStyle: { color: '#fff' } },
	                    }],

		                yAxis: [{ type: 'value', axisLabel: { color: '#333' }, axisLine: { lineStyle: { color: '#fff' } }, splitLine: { lineStyle: { color: ['#eee'] } } }],

			            series: [
		                    {
		                        name: 'Визиты', type: 'bar',
		                        data: [{/literal}{foreach item=visitor from=$visitors.data name=visitors} {$visitor.metrics.visits}{if !$smarty.foreach.visitors.last}, {/if}{/foreach}{literal}],
				            }, {
		                        name: 'Просмотры', type: 'bar',
				                data: [{/literal}{foreach item=visitor from=$visitors.data name=visitors} {$visitor.metrics.pageviews}{if !$smarty.foreach.visitors.last}, {/if}{/foreach}{literal}],
			                }, {
		                        name: 'Посетители', type: 'bar',
				                data: [{/literal}{foreach item=visitor from=$visitors.data name=visitors}{$visitor.metrics.users}{if !$smarty.foreach.visitors.last}, {/if}{/foreach}{literal}],
		                    }
				        ]
	                });
	            }

	            {/literal}{/if}{literal}


	            // Resize charts
	            var triggerChartResize = function() {
	                stats_users_element && users_element.resize();
	                pie_browser_element && pie_browser.resize();
	                pie_age_element && pie_age.resize();
	            };

	            $(document).on('click', '.sidebar-control', function() {
	                setTimeout(function () {
	                    triggerChartResize();
	                }, 0);
	            });

	            var resizeCharts;
	            window.onresize = function () {
	                clearTimeout(resizeCharts);
	                resizeCharts = setTimeout(function () {
	                    triggerChartResize();
	                }, 200);
	            };
	        };

	        return {
	            init: function() {
	                _piesDonutsExamples();
	            }
	        }
	    }();

	    document.addEventListener('DOMContentLoaded', function() {
	        EchartsPiesDonuts.init();
	    });
	    {/literal}

	</script>
	{/if}
