<?php
namespace frontend\controllers;

use Yii;
use yii\base\InvalidArgumentException;
use yii\web\BadRequestHttpException;
use yii\web\NotFoundHttpException;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use backend\models\Tag;
use backend\models\Post;
use frontend\models\ShareYourTravelStory;

class TagController extends Controller {

    /**
     * @inheritdoc
     */
    public function behaviors() {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['index', 'view'],
                        'allow' => true,
                        'roles' => ['?', '@']
                    ],
                ]
            ],
        ];
    }
	
	public function actionIndex() {
		$caQuery = Tag::find()->where(['status' => 1]);
		$stateDataProvider = new ActiveDataProvider([

            'query' => $caQuery,
            'sort' => [
                'defaultOrder' => [
                    'id' => SORT_DESC,
                ]
            ],
            'pagination' => [
                'pageSize' => 12,
        ]]);
		
		return $this->render('index', [
					'stateDataProvider' => $stateDataProvider,
		]);
    }
	
	public function actionView($slug = NULL) {
		$model = Tag::find()->where(['slug' => $slug, 'status' => 1])->one();
        if(isset($model)) {
	    $caQuery = Post::find()->where(['status' => 1])->andWhere('FIND_IN_SET('.$model->id.', tag_id)');
		$catDataProvider = new ActiveDataProvider([

            'query' => $caQuery,
            'sort' => [
                'defaultOrder' => [
                    'id' => SORT_DESC,
                ]
            ],
            'pagination' => [
                'pageSize' => 21,
        ]]);
		$travelstory = ShareYourTravelStory::find()->where(['status' => 1])->orderBy(['id' => SORT_DESC])->limit(6)->all();
		return $this->render('view', [
					'model' => $model,
					'catDataProvider' => $catDataProvider,
					'travelstory' => $travelstory,
		]);
     } else {
			throw new NotFoundHttpException('The requested page does not exist.');
		 }	
    }
}
