<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "analytics".
 *
 * @property int $id
 * @property string $key1 ключ1
 * @property string $key2 ключ2
 * @property string $date Дата
 * @property int|null $vald Значение цифровое
 * @property int|null $valt Значение текстовое
 * @property string|null $ext другие значения
 */
class Analytics extends \yii\db\ActiveRecord
{

	/**
	 * @var string
	 */
	private $_token = "y0_AgAAAAABspRzAAKENgAAAADl049iHuuiZPWuSTOGV3NsbVUNsXCymlc";
	private $_Yid = 34950850;
	private $_login = 'amicru';
	/**
	 * @var array
	 */
	private $context = array();

	/**
	 * Constructor
	 *
	 * @param bool $use_only_cache
	 */
	function __construct()
	{
		$opts = array(
			'http'=>array(
				'method'=>"GET",
				'header'=>"Accept-language: ru\r\n" .
				'Authorization: OAuth '.$this->_token."\r\n".
				'Content-Type: application/x-yametrika+json'
			)
		);
		$this->context = stream_context_create($opts);
	}

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'analytics';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['key1', 'key2', 'date'], 'required'],
            [['date', 'ext'], 'safe'],
            [['vald', 'valt'], 'integer'],
            [['key1', 'key2'], 'string', 'max' => 64],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'key1' => 'ключ1',
            'key2' => 'ключ2',
            'date' => 'Дата',
            'vald' => 'Значение цифровое',
            'valt' => 'Значение текстовое',
            'ext' => 'другие значения',
        ];
    }

	public function YGetStat($start_date = NULL ,$now_date = NULL)
	{
		$id = $this->_Yid;
		$start_date = ( $start_date )?$start_date:date("Ym01");
		$now_date = ( $now_date )?$now_date:date("Ymd");
		$url = "https://api-metrika.yandex.ru/stat/v1/data?ids=" . $id . "&date1=" . $start_date . "&date2=" . $now_date . "&metrics=ym:s:visits,ym:s:pageviews,ym:s:users&direct_client_logins=".$this->_login."&oauth_token=" . $this->_token;
		$results_page = file_get_contents($url, false, $this->context);
		$Stat = json_decode($results_page);
		return array('ids'=>$Stat->query->ids[0],'visits'=>$Stat->totals[0],'pageviews'=>$Stat->totals[1],'users'=>$Stat->totals[2],'date1'=>$Stat->query->date1,'date2'=>$Stat->query->date2);
	}

	public function YGetFullStat($start_date = NULL ,$now_date = NULL)
	{
		$id = $this->_Yid;
		$start_date = ( $start_date )?$start_date:date("Ym01");
		$now_date = ( $now_date )?$now_date:date("Ymd");
		$url = "https://api-metrika.yandex.ru/stat/v1/data?ids=" . $id . "&date1=" . $start_date . "&date2=" . $now_date . "&metrics=ym:s:pageviews,ym:s:users,ym:s:newUsers,ym:s:bounceRate,ym:s:avgVisitDurationSeconds,ym:s:pageDepth&direct_client_logins=".$this->_login."&oauth_token=" . $this->_token;
		$results_page = file_get_contents($url, false, $this->context);
		$Stat = json_decode($results_page);
		return array('ids'=>$Stat->query->ids[0],'date1'=>$Stat->query->date1,'date2'=>$Stat->query->date2,'data'=>$Stat);
	}
	public function YGetSourceStat($start_date = NULL ,$now_date = NULL)
	{
		$id = $this->_Yid;
		$start_date = ( $start_date )?$start_date:date("Ym01");
		$now_date = ( $now_date )?$now_date:date("Ymd");
		$url = "https://api-metrika.yandex.ru/stat/v1/data?ids=" . $id . "&date1=" . $start_date . "&date2=" . $now_date . "&metrics=ym:s:users&dimensions=ym:s:lastTrafficSource&direct_client_logins=".$this->_login."&oauth_token=" . $this->_token;
		$results_page = file_get_contents($url, false, $this->context);
		$Stat = json_decode($results_page);
		return $Stat;
	}

	public function YGetRegionStat($start_date = NULL ,$now_date = NULL)
	{
		$id = $this->_Yid;
		$start_date = ( $start_date )?$start_date:date("Ym01");
		$now_date = ( $now_date )?$now_date:date("Ymd");
		$url = "https://api-metrika.yandex.ru/stat/v1/data?ids=" . $id . "&date1=" . $start_date . "&date2=" . $now_date . "&metrics=ym:s:users&filters=ym:s:regionAreaName=='Алтайский%20край'&direct_client_logins=".$this->_login."&oauth_token=" . $this->_token;
		$results_page = file_get_contents($url, false, $this->context);
		$Stat = json_decode($results_page);
		return $Stat;
	}

	public function YGetStatByDay($start_date = NULL ,$now_date = NULL)
	{
		$id = $this->_Yid;
		$start_date = ( $start_date )?$start_date:date("Ym01");
		$now_date = ( $now_date )?$now_date:date("Ymd");
		$url = "https://api-metrika.yandex.ru/stat/v1/data/bytime?ids=" . $id . "&date1=" . $start_date . "&date2=" . $now_date . "&group=day&metrics=ym:s:visits,ym:s:pageviews,ym:s:users&direct_client_logins=".$this->_login."&oauth_token=" . $this->_token;
		$results_page = file_get_contents($url, false, $this->context);
		$Stat = json_decode($results_page);
		$byDate = array();
		foreach ($Stat->time_intervals as $key=>$GetData) {
			$byDate[$key]['date'] = $GetData[0];
		}
		foreach ($Stat->data[0]->metrics[0] as $key=>$GetData) {
			$byDate[$key]['visits'] = $GetData;
		}
		foreach ($Stat->data[0]->metrics[1] as $key=>$GetData) {
			$byDate[$key]['pageviews'] = $GetData;
		}
		foreach ($Stat->data[0]->metrics[2] as $key=>$GetData) {
			$byDate[$key]['users'] = $GetData;
		}
		return array('ids'=>$Stat->query->ids[0],'visits'=>$Stat->totals[0][0],'pageviews'=>$Stat->totals[0][1],'users'=>$Stat->totals[0][2],'date1'=>$Stat->query->date1,'date2'=>$Stat->query->date2, 'data'=>$byDate);
	}

	public function YGetOrganic($start_date = NULL ,$now_date = NULL)
	{
		$id = $this->_Yid;
		$start_date = ( $start_date )?$start_date:date("Ym01");
		$now_date = ( $now_date )?$now_date:date("Ymd");
		$url = "https://api-metrika.yandex.ru/stat/v1/data?ids=" . $id . "&date1=" . $start_date . "&date2=" . $now_date . "&dimensions=ym:s:searchEngine&metrics=ym:s:users&filters=ym%3As%3AtrafficSource%3D%3D'organic'&direct_client_logins=".$this->_login."&oauth_token=" . $this->_token;
		$results_page = file_get_contents($url, false, $this->context);
		$Stat = json_decode($results_page);
		return array('ids'=>$Stat->query->ids[0],'users'=>$Stat->totals[0],'date1'=>$Stat->query->date1,'date2'=>$Stat->query->date2, 'data'=>$Stat->data);
		return $Stat;
	}

	public function YGetReferer($start_date = NULL ,$now_date = NULL)
	{
		$id = $this->_Yid;
		$start_date = ( $start_date )?$start_date:date("Ym01");
		$now_date = ( $now_date )?$now_date:date("Ymd");
		$url = "https://api-metrika.yandex.ru/stat/v1/data/bytime?ids=" . $id . "&date1=" . $start_date . "&date2=" . $now_date . "&group=month&top_keys=20&metrics=ym:s:users&dimensions=ym:s:refererDomain&sort=ym:s:users&limit=20&direct_client_logins=".$this->_login."&oauth_token=" . $this->_token;
		$results_page = file_get_contents($url, false, $this->context);
		$Stat = json_decode($results_page);
		return $Stat;
	}

	public function YGetRegions($start_date = NULL ,$now_date = NULL)
	{
		$id = $this->_Yid;
		$start_date = ( $start_date )?$start_date:date("Ym01");
		$now_date = ( $now_date )?$now_date:date("Ymd");
		$url = "https://api-metrika.yandex.ru/stat/v1/data/?ids=" . $id . "&date1=" . $start_date . "&date2=" . $now_date . "&group=month&preset=geo_country&filters=ym%3As%3AregionCountryName=='Россия'&metrics=ym%3As%3Ausers,ym:s:visits&sort=-ym%3As%3Ausers&limit=10&direct_client_logins=".$this->_login."&oauth_token=" . $this->_token;
		$results_page = file_get_contents($url, false, $this->context);
		$Stat = json_decode($results_page);
		return $Stat;
	}

	public function YGetByTime($params1)
	{
		$id = $this->_Yid;
		$url = 'https://api-metrika.yandex.ru/stat/v1/data/bytime';
		$params = array(
			'ids'         => $id,
			'direct_client_logins'	=>	$this->_login,
		);
		$params = array_merge($params,$params1);
        $sets = $url . '?' . http_build_query($params, '', '&');
		$results_page = @file_get_contents( $sets, false, $this->context );
		$Stat = json_decode($results_page);
		return $Stat;
	}
	public function GetLive($metrics, $type){
		$results_page = file_get_contents( urldecode($metrics).'&period=month&graph=csv', false);
		switch( $type ){
		case '2d':
			$liv_stat = $this->Live2js($results_page);
			break;
		case '3d':
			$liv_stat = $this->Live2js3d($results_page);
			break;
		}
		return $liv_stat;
	}

	public function Live2js( $str ){
		$m = array( "Янв","Фев","Мар","Апр","Май","Июн","Июл","Авг","Сен","Окт","Ноя","Дек");
		$a = explode( "\n", $str );
		$r = array();
		foreach( $a as $text ){
			$tmp = explode( ";", $text );
			if( isset($tmp[0]) ){
				if( preg_match_all("/\"(.+)\s(\d+)/", $tmp[0], $atmp, PREG_SET_ORDER) ){
					$x = array();
					$x[$atmp[0][2]+2000][array_search( $atmp[0][1], $m )+1]['count']=$tmp[1];
					$r[]=$x;
				}
			}
		}
//		print_r($r);
		return $r;
	}

	public function Live2js3d( $str ){
		$m = array( "Янв","Фев","Мар","Апр","Май","Июн","Июл","Авг","Сен","Окт","Ноя","Дек");
		$a = explode( "\n", $str );
		$title = explode( ";", $a[0] );
		$r = array();

		foreach( $a as $text ){
			$tmp = explode( ";", $text );

			if( isset($tmp[0]) ){
				if( preg_match_all("/\"(.+)\s(\d+)/", $tmp[0], $atmp, PREG_SET_ORDER) ){
					for( $i=1 ; $i < count($tmp); $i++){
						$mm = array_search( $atmp[0][1], $m )+1;
						$r[$atmp[0][2]+2000][$mm][$i]=$tmp[$i];
					}
				}
			}
		}
		return $r;
	}
	public function GetYglob( $sstart, $send ){
        $sweek = array();
        $params = array(
            'metrics'     => 'ym:s:pageviews,ym:s:users,ym:s:newUsers,ym:s:bounceRate,ym:s:avgVisitDurationSeconds,ym:s:pageDepth',
            'date1'       => $sstart,
            'date2'       => $send,
            'group'        => 'month',
            'top_keys'      => 12,
            'sort'      =>'-ym:s:users'
        );
		$sweek = $this->YGetByTime($params);
		return $sweek;
	}

	public function GetRegionsSite( $date = '' ){
		if( $date == '' )	$date=date("Y-m-01");
		$RegionsSite = Analytics::find()
			->where(['key1'=>'RegionsSite','key2'=>'', 'date'=>$date])
			->one();
		if( !$RegionsSite ){
			$aregm = [];
			$str = @file_get_contents('/home/admin/import/livereg.csv');
			$aregms = explode("\n", $str);
			foreach( $aregms as $item ){
				$a = explode(';', $item);
				$aregm[str_replace( '"', '', $a[0])] = $a;
			}
			if( count($aregm) ){
				$this->setAttributes( ['key1'=>'RegionsSite', 'key2'=>'', 'date'=>date("Y-m-01"), 'ext'=>json_encode($aregm)] );
				$this->save(false);
			}
		}else{
			$aregm = json_decode($RegionsSite['ext']);
		}
		return $aregm;
	}
}
