<?php

namespace common\modules\blog\controllers;

use Yii;
use common\components\BaseController;
use yii\web\NotFoundHttpException;

use common\modules\blog\models\Post;
use common\modules\blog\models\PostTag;

/**
 * PostController implements the CRUD actions for Post model.
 */
class PostController extends BaseController
{
    public static function actionsTitles()
    {
        return [
            'Index'           => 'Блог',
            'Tag'             => 'Просмотр тега',
            'View'            => 'Просмотр записи',
        ];
    }

    /**
     * Displays all Post models.
     * @return mixed
     */
    public function actionIndex()
    {
        $this->meta_title = Yii::t('menu', 'Blog') . ' - ' . \Yii::$app->params['name'];

        $models = Post::find()->where(['active' => 1])->all();

        return $this->render('index', [
            'models' => $models,
        ]);
    }

    /**
     * Displays a single Post model.
     * @param string $url
     * @return mixed
     */
    public function actionTag($tag)
    {
        $model = PostTag::find()->where(['name' => $tag])->one();

        if(!$model || !$model->posts)
        {
            throw new NotFoundHttpException('The requested page does not exist.');
        }

        $this->meta_title = Yii::t('app', 'Tag') . ': ' . $model->name . ' - ' . \Yii::$app->params['name'];

        return $this->render('tag', [
            'model' => $model,
        ]);
    }

    /**
     * Displays a single Post model.
     * @param string $url
     * @return mixed
     */
    public function actionView($url)
    {
        $model = $this->findModelByUrl($url);
        
        $this->meta_title = $model->metaTag->title . ' - ' . \Yii::$app->params['name'];
        $this->meta_description = $model->metaTag->description;
        $this->meta_keywords = $model->metaTag->keywords;

        return $this->render('view', [
            'model' => $model,
        ]);
    }

    /**
     * Finds the Post model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $url
     * @return Post the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModelByUrl($url)
    {
        if (($model = Post::find()->where([
            'url' => $url,
            'active' => 1
        ])->one()) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
