<?php

namespace app\controllers;

use  Yii;
use app\models\base\Tags;
use app\models\News;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\db\Expression;

class TagsController extends Controller
{

    //public $viewTheme = "dark";
    //public $viewPath = "@app/views/news";

    public function actionIndex($topic=NULL)
    {
		throw new NotFoundHttpException("Раздел не найден");
    }


    private function findModel($id)
    {
        return Tags::find()->andWhere(['id'=>$id])->one();
    }

    public function actionTopic($topic){
        $this->viewPath = "@app/views/news";
       $topic = Tags::findOne(['url'=>$topic]);
        if(!$topic instanceof Tags){

            $topic = new \stdClass();
            $topic->id = NULL;
			throw new NotFoundHttpException("Раздел не найден");
        }
        if( $topic->id ){
			$news_query = \app\models\front\News::find()
			->from(new Expression("news FORCE INDEX (top) , tags_relation t FORCE index(news_id)"))
			->andWhere(new Expression('t.news_id=id'))
            ->andWhere(['t.topic_id'=>$topic->id]);			//joinWith('topics t')->andFilterWhere(['t.id'=>$topic->id]);
//			print_r($news_query->createCommand()->rawSQL);exit;
		}else{
			$news_query = \app\models\front\News::find();	// optimized
		}

		$cnt = \Yii::$app->cache->getOrSet('tags_cnt_'.$topic->id, function () use ($news_query){
			return $news_query->count();
		},7200);

		$pages = new \yii\data\Pagination(['totalCount' => $cnt, 'pageSize'=>20]);

		$dateRange = \Yii::$app->request->get('daterange',NULL);
        if(!is_null($dateRange) && $dateRange!=""){
            $dateRange = explode(" — ",$dateRange);
            $dateRange[0] = date("Y-m-d 00:00:01",strtotime($dateRange[0]));
            $dateRange[1] = isset($dateRange[1])?date("Y-m-d 23:59:59",strtotime($dateRange[1])):date("Y-m-d 23:59:59",strtotime($dateRange[0]));
            $news_query->andWhere(["BETWEEN","dt_pub",$dateRange[0],$dateRange[1]]);
        }
        return $this->render("index",["topic"=>$topic,"daterange"=>$dateRange,"news_query"=>$news_query,"pages"=>$pages]);
    }

    public function actionSearch()
    {
		if (Yii::$app->request->isGet && $get = Yii::$app->request->get('query')){
			$model = new Tags();
			$gets = mb_strlen( $get ) < 6?$get.'*':$get;
			$items = $model->search($gets, 10);
			$res = array();
			$json = '{}';
			$resj = json_decode($json);
			$resj->query = $get;
			if( $items && is_array( $items ) ){
				foreach( $items as $item ){
					$res[] = array( 'data'=>$item['id']*1, 'value'=>$item['title'] );
				}
				$resj->suggestions = $res;
				return json_encode( $resj );
			}
		}
		$json = '{}';
		$resj = json_decode($json);
		$resj->query = $get;
		$resj->suggestions = [];
        return json_encode( $resj );
    }
}
