<?php

	if ($this->beginCache("dashestats", ['duration' => 60*2])) {

	$this->title="Статистика";
	$this->params['breadcrumbs'][] = ['label' => 'Статистика', 'url' => ['index']];
	$this->params['breadcrumbs'][] = $this->title;

		$y = date("Y")*1;
		$m = date("m");

//	$d = cal_days_in_month(CAL_GREGORIAN, $m, $y);
	$d = date("d");
	$m = $m<10?"0$m":$m;
	$d = $d<10?"0$d":$d;
	$b_date = date("Y-".$m."-01 00:00:00");
	$e_date = date("Y-".$m."-".$d."  H:i:59");
	//$newsonmath


	$cmd = Yii::$app->db->createCommand("select count(id) as c, DATE_FORMAT(dt_pub, '%d') as day from news where `dt_pub` BETWEEN '".$b_date."' AND '".$e_date."' and active = 'Y' group by day")->queryAll();
	$newsonday = '';
	$mathday = '';
	$min = 100000;
	$max = 0;
	$i = 0;
	$maxd = '';
	$mind = '';
	$sum = 0;
	$a= [];
	foreach( $cmd as $item ){
		$i++;
		$sum += $item['c']*1;
		$newsonday .= $item['c'].',';
		$mathday .= '"'.$item['day'].'"'.',';
		$max = ( $item['c'] > $max )?$item['c']:$max;
		$maxd = ( $item['c'] > $max )?$item['d']:$maxd;
		if( date("d") != $item['day']  ) $min = ( $item['c'] < $min )?$item['c']:$min;
		if( date("d") != $item['day']  ) $mind = ( $item['c'] < $min )?$item['d']:$mind;
		$a[] = $item['c'];
	}
	sort($a);
	$count = sizeof($a);   // cache the count
	$index = floor($count/2);  // cache the index
	if (!$count) {
		$mid = ($max+$min)/2;
	} elseif ($count & 1) {    // count is odd
		$mid = $a[$index];
	} else {                   // count is even
		$mid = ($a[$index-1] + $a[$index]) / 2;
	}


	$authors = Yii::$app->db->createCommand("select e, count(e) as c from (SELECT SUBSTRING_INDEX(`editors`,',',1) as e FROM `news` WHERE `dt_pub` BETWEEN '".$b_date."' AND '".$e_date."' and active = 'Y') t where 1 group by e order by e")->queryAll();
	$old_author_name = ['kondakov' => 'Вячеслав Кондаков*','bers'=>'Евгений Берсенёв','kuznecov' =>'Артём Кузнецов*', 'katya'=>'Екатерина Смолихина*', 'elena'=>'Елена Лепезина*', 'cherdanceva'=>'Александра Черданцева*'];

// рубрики заполнены
	$rubric = Yii::$app->db->createCommand("select count(tr.topic_id) as c, nt.title as t from news as n, news_topic_relation as tr, news_topic as nt where `dt_pub` BETWEEN '".$b_date."' AND '".$e_date."' and n.active = 'Y' and n.id = tr.news_id and tr.topic_id = nt.id and nt.`active`=1 and nt.`show`='Y' group by tr.topic_id")->queryAll();
// количество рубрик
	$crubric = Yii::$app->db->createCommand("select count(id) as c from news_topic where `active`=1 and `show`='Y'")->queryOne();
	$sumr = $crubric['c'];

	$cnews = Yii::$app->db->createCommand("select count(id) as c  from news where `dt_pub` BETWEEN '".$b_date."' AND '".$e_date."' and active = 'Y'")->queryOne();
	$cntnews = $cnews['c'];

	$cnewsp = Yii::$app->db->createCommand("select count(id) as c  from news where `dt_pub` BETWEEN DATE_SUB('".$b_date."',  INTERVAL 1 MONTH) AND DATE_SUB('".$e_date."',  INTERVAL 1 MONTH) and active = 'Y'")->queryOne();
	$cntnewsp = $cnewsp['c'];

	$cnewsy = Yii::$app->db->createCommand("select count(id) as c  from news where `dt_pub` BETWEEN '".$y."-01-01 00:00:00' AND '".$e_date."' and active = 'Y'")->queryOne();
	$cntnewsy = $cnewsy['c'];

	$cnewsyy = Yii::$app->db->createCommand("select count(id) as c  from news where `dt_pub` BETWEEN DATE_SUB('".$b_date."',  INTERVAL 1 YEAR) AND '".$e_date."' and active = 'Y'")->queryOne();
	$cntnewsyy = $cnewsyy['c'];


	$now = time();
	$ndate = strtotime( $y."-01-01");
	$datediff = $now - $ndate;
    $daysp =  round($datediff / (60 * 60 * 24));

	$edate = strtotime( $y."-12-31");
	$datediff = $now - $edate;
    $dayso =  -round($datediff / (60 * 60 * 24));

	$newsinterpolite = round($cntnewsy*$dayso/$daysp);

	$rate = Yii::$app->db->createCommand("select counter from reaction_button limit ".$cntnews)->queryAll();
	$cnt = [0,0,0,0,0,0];
	$sumrb = 0;
	foreach( $rate as $item ){
		$a = json_decode( $item['counter'] );
		$cnt[0] += $a[0];
		$cnt[1] += $a[1];
		$cnt[2] += $a[2];
		$cnt[3] += $a[3];
		$cnt[4] += $a[4];
		$cnt[5] += $a[5];
		$sumrb += array_sum( $a );
	}

	$cntcomment = Yii::$app->db->createCommand("select count(id) as c  from comments where `created_at` BETWEEN '".$b_date."' AND '".$e_date."' and visible = 'Y'")->queryOne();
	$cnt_comment = $cntcomment['c'];

	$cntcomment = Yii::$app->db->createCommand("select count(id) as c  from comments where `created_at` BETWEEN '".$b_date."' AND '".$e_date."' and visible = 'N'")->queryOne();
	$cnt_commenth = $cntcomment['c'];

?>
<section class="content dark-mode">
<div class="container-fluid">

<div class="row">
<div class="col-12 col-sm-6 col-md-3">
<div class="info-box">
<span class="info-box-icon bg-info elevation-1"><i class="fas fa-cog"></i></span>
<div class="info-box-content">
<span class="info-box-text">CPU нагрузка</span>
<span class="info-box-number">
<?
$str="LANGUAGE=en_US.UTF-8 sar 1 2 | grep \"Average\" | sed 's/^.* //'";
$out = [];
exec($str, $out);
echo 100-$out[0]*1;
?>
<small>%</small>
</span>
</div>

</div>

</div>

<div class="col-12 col-sm-6 col-md-3">
<div class="info-box mb-3">
<span class="info-box-icon bg-warning elevation-1"><i class="fas fa-users"></i></span>
<div class="info-box-content">
<span class="info-box-text">Запросов в секунду</span>
<span class="info-box-number">
<?
$str = "wget -q -O - http://localhost/nginx_status |grep 'Active connections:'";
$out = [];
exec($str, $out);
$s = explode(':',$out[0]);
?>
<?=$s[1]?></span>
</div>

</div>

</div>


<div class="clearfix hidden-md-up"></div>
<div class="col-12 col-sm-6 col-md-3">
<div class="info-box mb-3">
<span class="info-box-icon bg-success elevation-1"><i class="fas fa-thumbs-up"></i></span>
<div class="info-box-content">
<span class="info-box-text">Наибольшее число новостей</span>
<span class="info-box-number"><?=$max?></span>
</div>

</div>

</div>

<div class="col-12 col-sm-6 col-md-3">
<div class="info-box mb-3">
<span class="info-box-icon bg-danger elevation-1"><i class="fas fa-thumbs-down"></i></span>
<div class="info-box-content">
<span class="info-box-text">Минимум новостей</span>
<span class="info-box-number"><?=$min?></span>
</div>

</div>

</div>

</div>

<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5 class="card-title">Выпуск новостей по месяцу</h5>
<div class="card-tools">
<button type="button" class="btn btn-tool" data-card-widget="collapse">
<i class="fas fa-minus"></i>
</button>
<div class="btn-group">

</div>
<button type="button" class="btn btn-tool" data-card-widget="remove">
<i class="fas fa-times"></i>
</button>
</div>
</div>

<div class="card-body">
<div class="row">
<div class="col-md-8">
<p class="text-center">
<strong>выпуски с <?=$b_date?> по <?=$e_date?></strong>
</p>
<div class="chart">

<canvas id="salesChart" height="180" style="height: 180px;"></canvas>
</div>

</div>

<div class="col-md-4">
<p class="text-center">
<strong>Дни</strong>
</p>
<div class="progress-group">
Лучший день
<span class="float-right"><b><?=$max?></b>/<?=$max?></span>
<div class="progress progress-sm">
<div class="progress-bar bg-primary" style="width: 100%"></div>
</div>
</div>

<div class="progress-group">
Худший день
<span class="float-right"><b><?=$min?></b>/<?=$max?></span>
<div class="progress progress-sm">
<div class="progress-bar bg-danger" style="width: <?=$min*100/$max?>%"></div>
</div>
</div>

<div class="progress-group">
<span class="progress-text">среднее число новостей</span>
<span class="float-right"><b><?=round($sum/count($cmd))?></b>/<?=$max?></span>
<div class="progress progress-sm">
<div class="progress-bar bg-success" style="width: <?=round($sum/count($cmd)*100/$max)?>%"></div>
</div>
</div>

<div class="progress-group">
Медианное значение
<span class="float-right"><b><?=$mid?></b>/<?=$max?></span>
<div class="progress progress-sm">
<div class="progress-bar bg-warning" style="width: <?=round($mid*100/$max)?>%"></div>
</div>
</div>

</div>

</div>

<div class="card-footer">
<div class="row">
<div class="col-sm-3 col-6">
<div class="description-block border-right">
<span class="description-percentage <?=$cntnews-$cntnewsp>0?'text-success':'text-danger'?>" title="От предыдущего месяца <?=$cntnewsp?>"><i class="fas <?=$cntnews-$cntnewsp>0?'fa-caret-up':'fa-caret-down'?>"></i><?=round(($cntnews-$cntnewsp)*100/$cntnewsp, 1)?>%</span>
<h5 class="description-header"><?=$cntnews?></h5>
<span class="description-text">Всего новостей за месяц</span>
</div>

</div>

<div class="col-sm-3 col-6">
<div class="description-block border-right">
<span class="description-percentage <?=$cntnewsy-$cntnewsyy>0?'text-success':'text-danger'?>" title="До конца года <?=$cntnewsyy?>"><i class="fas <?=$cntnewsy-$cntnewsyy>0?'fa-caret-up':'fa-caret-down'?>"></i><?=round(($cntnewsy-$cntnewsyy)*100/$cntnewsyy, 1)?>%</span>
<h5 class="description-header"><?=$cntnewsy?></h5>
<span class="description-text">Новостей сначала года</span>
</div>

</div>

<div class="col-sm-3 col-6">
<div class="description-block border-right">
<span class="description-percentage text-success"><i class="fas fa-caret-up"></i> 0%</span>
<h5 class="description-header"><?=$cntnewsyy?></h5>
<span class="description-text">За 365 дней</span>
</div>

</div>

<div class="col-sm-3 col-6">
<div class="description-block">
<span class="description-percentage text-danger" title="От прошлого года"><i class="fas <?=($newsinterpolite+$cntnewsy)-$cntnewsyy>0?'text-success':'text-danger'?>"></i><i class="fas <?=($newsinterpolite+$cntnewsy)-$cntnewsyy>0?'fa-caret-up':'fa-caret-down'?>"></i><?=round((($newsinterpolite+$cntnewsy)-$cntnewsyy)*100/$cntnewsyy, 1)?>%</span>
<h5 class="description-header"><?=$newsinterpolite+$cntnewsy?></h5>
<span class="description-text">Будет новостей за этот год</span>
</div>

</div>
</div>

</div>

</div>

</div>

</div>

</div>


<div class="row">

<div class="col-md-8">


<div class="row">
<div class="col-md-6">

<div class="card">
<div class="card-header">
<h3 class="card-title">Активность авторов<a href="/manager/stats/authors"></h3><div class="card-tools"><span class="badge badge-primary">Статистика по месяцам</span></a></div>
</div>

<div class="card-body">
<table class="table table-bordered">
<thead>
<tr>
<th style="width: 10px">#</th>
<th>Автор</th>
<th>Progress</th>
<th style="width: 40px">Label</th>
<th style="width: 40px">количество</th>
</tr>
</thead>
<tbody>
<?
$i = 0;
foreach( $authors as $author ){
	$i++;
	$aname = $author['e'];
	$aname = isset($old_author_name[$aname])?$old_author_name[$aname]:$aname;
?>
<tr>
<td><?=$i?></td>
<td><?=$aname?></td>
<td>
<div class="progress progress-xs">
<div class="progress-bar progress-bar-danger" style="width: <?=round( $author['c']*100/$sum,1)?>%"></div>
</div>
</td>
<td><span class="badge bg-danger"><?=round( $author['c']*100/$sum,1)?>%</span></td>
<td><span class="badge bg-warning"><?=$author['c']?></span></td>
</tr>
<?}?>
</tbody>
</table>
</div>

<div class="card-footer clearfix">
* переопубликованые материалы
</div>
</div>
</div>

<div class="col-md-6">

<div class="card">
<div class="card-header">
<h3 class="card-title">Активность рубрик</h3>
</div>

<div class="card-body">
<table class="table table-bordered">
<thead>
<tr>
<th style="width: 10px">#</th>
<th>Рубрика</th>
<th>Progress</th>
<th style="width: 40px">Label</th>
<th style="width: 40px">количество</th>
</tr>
</thead>
<tbody>
<?
$i = 0;
$srub = '';
$srubc = '';
$bgc = '';
foreach( $rubric as $item ){
	$i++;
	$srub .= "'".$item['t']."'".',';
	$srubc .= $item['c'].',';
	$bgc .= "'#".dechex(rand(10,255)).dechex(rand(10,255)).dechex(rand(1,255))."',";
?>
<tr>
<td><?=$i?></td>
<td><?=$item['t']?></td>
<td>
<div class="progress progress-xs">
<div class="progress-bar progress-bar-danger" style="width: <?=round( $item['c']*100/$sum,1)?>%"></div>
</div>
</td>
<td><span class="badge bg-danger"><?=round( $item['c']*100/$sum,1)?>%</span></td>
<td><span class="badge bg-warning"><?=$item['c']?></span></td>
</tr>
<?}?>
</tbody>
</table>
</div>

<div class="card-footer clearfix">

</div>
</div>

</div>
</div>


</div>
<div class="col-md-4">
<div class="card">
<div class="card-header">
<h3 class="card-title">Рубрики</h3>
<div class="card-tools">
<button type="button" class="btn btn-tool" data-card-widget="collapse">
<i class="fas fa-minus"></i>
</button>
<button type="button" class="btn btn-tool" data-card-widget="remove">
<i class="fas fa-times"></i>
</button>
</div>
</div>
<div class="card-body">
<canvas id="pieChart"></canvas>
</div>

</div>


<div class="card">
<div class="card-header">
<h3 class="card-title">Реакция посетителей на статьи</h3>
<div class="card-tools">
<button type="button" class="btn btn-tool" data-card-widget="collapse">
<i class="fas fa-minus"></i>
</button>
<button type="button" class="btn btn-tool" data-card-widget="remove">
<i class="fas fa-times"></i>
</button>
</div>
</div>

<div class="card-body p-0">
<ul class="products-list product-list-in-card pl-2 pr-2">
<?
$i = 1;
$c = ['bg-danger','bg-warning', 'bg-primary', 'bg-success'];
foreach( $cnt as $item ){
	$cc = $c[round($item*100/$sumrb/25)];
?>
<li class="item">
<div class="product-img">
<img src="/img/reactionbutton/<?=$i?>.svg" alt="Product Image" class="img-size-50">
</div>
<div class="product-info mt-3">
	<h3><span class="badge <?=$cc?> float-right"><?=$item?></span></h3>
	<div class="progress progress-sm  mr-5">
		<div class="progress-bar <?=$cc?>" style="width: <?=round($item*100/$sumrb)?>%"></div>
	</div>
</div>
</li>
<?
$i++;
}
?>
</ul>
</div>

<div class="card-footer text-center">
реакции
</div>

</div>


<div class="small-box bg-succes">
	<div class="inner">
		<h3><?=$cnt_comment+$cnt_commenth?></h3>
		<p>Всего комментариев</p>
	</div>
	<div class="icon">
		<i class="fas fa-chart-pie"></i>
	</div>
	<a href="/manager/comments/index" class="small-box-footer">
		More info <i class="fas fa-arrow-circle-right"></i>
	</a>
</div>

<div class="small-box bg-succes">
	<div class="inner">
		<h3><?=$cnt_comment?></h3>
		<p>Опубликованных комментариев</p>
	</div>
	<div class="icon">
		<i class="fas fa-chart-pie"></i>
	</div>
	<a href="/manager/comments/index" class="small-box-footer">
		More info <i class="fas fa-arrow-circle-right"></i>
	</a>
</div>

<div class="small-box bg-danger">
	<div class="inner">
		<h3><?=$cnt_commenth?></h3>
		<p>Заблоченных комментариев</p>
	</div>
	<div class="icon">
		<i class="fas fa-chart-pie"></i>
	</div>
	<a href="/manager/comments/index" class="small-box-footer">
		More info <i class="fas fa-arrow-circle-right"></i>
	</a>
</div>


</div>

</div>

</div>
</section>

</div>
<aside class="control-sidebar control-sidebar-dark">

</aside>

<?

//#f56954

?>

<script>

$(function(){
//var salesChartCanvas=$('#salesChart').get(0).getContext('2d')
var salesChartCanvas = document.getElementById('salesChart');
var salesChartData={labels:[<?=$mathday?>],datasets:[{label:'Goods Day',backgroundColor:'rgba(60,141,188,0.9)',borderColor:'rgba(60,141,188,0.8)',pointRadius:true,pointColor:'#3b8bba',pointStrokeColor:'rgba(60,141,188,1)',pointHighlightFill:'#fff',pointHighlightStroke:'rgba(60,141,188,1)',data:[<?=$newsonday?>]}]}
var salesChartOptions={maintainAspectRatio:false,responsive:true,legend:{display:false},scales:{xAxes:[{gridLines:{display:true}}],yAxes:[{gridLines:{display:false}}]}}
var salesChart=new Chart(salesChartCanvas,{type:'line',data:salesChartData,options:salesChartOptions})

var donutData        = {
      labels: [<?=$srub?>],
      datasets: [
        {
          data: [<?=$srubc?>],
          backgroundColor : [<?=$bgc?>],
        }
      ]
    }

var pieChartCanvas = $('#pieChart').get(0).getContext('2d')

    var pieData        = donutData;
    var pieOptions     = {
      maintainAspectRatio : true,
      responsive : true,
	  legend: false,
	}
    new Chart(pieChartCanvas, {
      type: 'doughnut',
      data: pieData,
      options: pieOptions
    })

});
	<?=$this->render('chartjs');?>
	$('body').addClass('dark-mode');
</script>
<?
	$this->endCache();
}
