<?php

namespace frontend\controllers;

use common\models\News;
use common\services\UserService;
use frontend\models\DataForm;
use Yii;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;

/**
 * Site controller
 */
class NewsController extends Controller
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'only' => ['logout', 'signup'],
                'rules' => [
                    [
                        'actions' => ['signup'],
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                    [
                        'actions' => ['logout'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::class,
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => \yii\web\ErrorAction::class,
            ],
            'captcha' => [
                'class' => \yii\captcha\CaptchaAction::class,
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    /**
     * Displays homepage.
     *
     * @return mixed
     */
    public function actionIndex()
    {
        $news = News::find()->all();

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

    /**
     * Экшен просмотра одной новости
     * @param null $slug
     * @return mixed
     */
    public function actionGetOne($slug = null)
    {
        $new = News::find()->where(['slug' => $slug])->one();
        return $this->render('one', [
            'new' => $new
        ]);
    }

    /**
     * Экшен для обработки формы
     * @return string|\yii\web\Response
     */
    public function actionData()
    {
        $model = new DataForm();

        if (Yii::$app->request->isPost) {
            if ($model->load(Yii::$app->request->post()) && $model->validate()) {
                Yii::$app->session->setFlash('success', 'Валидация прошла успешно');
            } else {
                Yii::$app->session->setFlash('error', 'Что-то не так');
            }
            return $this->refresh();
        }

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

    /**
     * Экшен для просмотра текста по профилю и языку
     * @param $id
     * @param $slug
     * @return string
     */
    public function actionText($id, $slug)
    {
        $texts = UserService::run()->getTextByLanguage($id, $slug);

        return $this->render('text', [
            'texts' => $texts
        ]);
    }
}