<?php
/**
 * @var $topic NewsTopic | NULL
 * @var $this \yii\web\View
 * @var $news_query \yii\db\ActiveQuery
 */

use app\models\base\NewsTopic;
use yii\web\View;
use app\models\base\Story;
use app\models\base\Tags;

$this->registerJsFile(
   '@web/js/autocomplete/jquery.autocomplete.min.js',
    ['position'=>View::POS_END, 'defer' => 'defer'],
    'autocomplete'
);

$this->params['breadcrumbs'] = [
    [
        "text"=>"НОВОСТИ",
        "url"=>"/news"
    ]
];
if($topic instanceof NewsTopic){
    $this->params['breadcrumbs'][] =
        [
            "text"=>$topic->title,
            "url"=>$topic->url
        ];
}

$dateRange = \Yii::$app->request->get('daterange');
$ssearch = \Yii::$app->request->get('q');
$tag = \Yii::$app->request->get('tag',null);
$story = \Yii::$app->request->get('story',null);

if( !is_null($story) ){
	$storys = Story::findOne(['id'=>$story]);
}
if( !is_null($tag) ){
	$tags = Tags::findOne(['id'=>$tag]);
}

$sstring = !isset($tags)?'':'по тэгу:'.$tags->title;
$sstring .= !isset($storys)?'':' по сюжету:'.$storys->title;
$sstring .= ' '.$ssearch;

if(!is_null($dateRange) && $dateRange!=""){
	$dateRange = explode(" — ",$dateRange);
    $dtb = date("Y-m-d",strtotime($dateRange[0]));
	$dte = isset($dateRange[1])?date("Y-m-d",strtotime($dateRange[1])):date("Y-m-d",strtotime($dateRange[0]));
}
$page = \Yii::$app->request->get('page');
$addtpage = $page?". Страница ($page)":'';

Yii::$app->og->title = "Страница поиска".$addtpage.' - '.$sstring;
Yii::$app->og->description = "Поиск статей по сайту amic.ru".$addtpage.' - '.$sstring;
Yii::$app->og->noindex = 'Y';

?>
<div class="archive">
    <div class="row">
        <div class="col-md-12">
            <div class="search-header">
                <form action="/search" method="get" class="search_form">
                    <h6>Поиск по запросу: </h6>
                    <input type="hidden" value="<?=Yii::$app->request->get("index")?>" name="index">
                    <input type="text" class="search_input" name="q" value="<?=Yii::$app->request->get("q")?>">
                    <button>Найти</button>
                </form>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-md-3">
            <div class="topics-list">
                <div class="topics-continer">
                    <?php
                        echo Yii::$app->cache->getOrSet("search_rubrics-{$topic->id}",function () use($topic){
                            return \yii\widgets\ListView::widget([
                                "dataProvider" => new \yii\data\ActiveDataProvider([
                                    "query"=>NewsTopic::find()->andWhere(["show"=>"Y","active"=>1,"topic_id"=>null])->orderBy(["order"=>SORT_ASC]), //"topic_id"=>$topic->id next lavel maybe
                                    "pagination" =>[
                                        "pageSize"=>0
                                    ],
                                ]),
                                'options' => [
                                    'tag' => "ul",
                                    'class' => 'list-wrapper',
                                    'id' => 'list-wrapper',
                                ],
                                "itemOptions"=>[
                                    "tag"=>"li"
                                ],
                                "itemView" => function($model) use($topic) {return \yii\helpers\Html::a($model->title,["news/{$model->url}"],['class'=>$model->id==$topic->id?"active":""]);},
                                "layout" => "{items}"
                            ]);
                        },600);
                    ?>
                </div>
            </div>
        </div>
        <div class="col-md-9">
            <div class="news-list">
                <?=$this->render("archive/filters")?>
                <div class="row align-items-center">
					<div class="col-auto">
						<select class="custom-select" aria-label="Даты" onchange="doSelect(this,document);">
							<option value="0">За всё время</option>
							<option value="1">За неделю</option>
							<option value="2">За месяц</option>
							<option value="3">За Год</option>
							<option value="4" onclick="toggleFiltersModal();return  false;" <?=!is_null($dateRange)?'selected':''?>><?=($dateRange)?$dtb.'-'.$dte:'Выбрать даты'?></option>
						</select>
					</div>
					<div class="col-auto"><input type="text" class="form-control" name="tag" value="<?=!isset($tags)?'':$tags->title?>" placeholder="Тэг" id="tag"></div>
					<div class="col-auto"><input type="text" class="form-control" name="story" value="<?=!isset($storys)?'':$storys->title?>" placeholder="Сюжет" id="story"></div>
                </div>
                <?php
                if( !is_null($news_query) ){
					$cnt = $news_query->count();
					if( $cnt > 500*30 ) $cnt = 500*30;
					echo \yii\widgets\ListView::widget([
                        "dataProvider" => new \yii\data\ActiveDataProvider([
                            "query"=>$news_query,
                            "totalCount"=>$cnt,
                            "pagination" =>[
                                "pageSize"=>30

                            ],
                        ]),
                        'options' => [
                            'tag' => "ul",
                            'class' => 'list-wrapper',
                            'id' => 'list-wrapper',
                        ],
                        "itemOptions"=>[
                            "tag"=>"li"
                        ],
                        "itemView" => "archive/_archive_item",
                        "layout" => "{items}{pager}"
                    ]);
				}
                ?>
            </div>
        </div>
    </div>
</div>

<?
$Js = <<< 'JS'
jQuery(function () {
$('#tag').autocomplete({
    serviceUrl: '/tags/search',
	minChars:3,
	noCache:true,
	deferRequestBy:3,
	triggerSelectOnValidInput:false,
    onSelect: function (suggestion) {
		window.location.href = window.location.href.split('?')[0]+'?tag='+suggestion.data;
    }
});
$('#story').autocomplete({
    serviceUrl: '/story/search',
	minChars:3,
	noCache:true,
	triggerSelectOnValidInput:false,
    onSelect: function (suggestion) {
		window.location.href =  window.location.href.split('?')[0]+'?story='+suggestion.data;
    }
});
});
JS;
$this->registerJs($Js, View::POS_READY);
?>
<script>

function doSelect(e,w){
	var url = new URL(w.location.href);
	var q = url.searchParams.get("q");
	if( q == null ) q = '';
	switch (e.value*1) {
		case 0:
			w.location.href = w.location.href.split('?')[0]+'?q='+q;
			break;
		case 1:
			var now = new Date(Date.now());
			var begin = new Date(Date.now()-7*24*60*60*1000);
			var daterange = begin.getDate()+'.'+(begin.getMonth()+1)+'.'+begin.getFullYear()+'+—+'+now.getDate()+'.'+(now.getMonth()+1)+'.'+now.getFullYear();
			w.location.href = w.location.href.split('?')[0]+'?q='+q+'&daterange='+daterange;
			break;
		case 2:
			var now = new Date(Date.now());
			var begin = new Date(Date.now()-30*24*60*60*1000);
			var daterange = begin.getDate()+'.'+(begin.getMonth()+1)+'.'+begin.getFullYear()+'+—+'+now.getDate()+'.'+(now.getMonth()+1)+'.'+now.getFullYear();
			w.location.href = w.location.href.split('?')[0]+'?q='+q+'&daterange='+daterange;
			break;
		case 3:
			var now = new Date(Date.now());
			var begin = new Date(Date.now()-365*24*60*60*1000);
			var daterange = begin.getDate()+'.'+(begin.getMonth()+1)+'.'+begin.getFullYear()+'+—+'+now.getDate()+'.'+(now.getMonth()+1)+'.'+now.getFullYear();
			w.location.href = w.location.href.split('?')[0]+'?q='+q+'&daterange='+daterange;
			break;
	}
}

</script>
<style>
.autocomplete-suggestions { border: 1px solid #999; background: #FFF; overflow: auto; }
.autocomplete-suggestion { padding: 2px 5px; white-space: nowrap; overflow: hidden; }
.autocomplete-selected { background: #F0F0F0; }
.autocomplete-suggestions strong { font-weight: normal; color: #3399FF; }
.autocomplete-group { padding: 2px 5px; }
.autocomplete-group strong { display: block; border-bottom: 1px solid #000; }
</style>
