<?php

namespace common\modules\support\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\web\NotFoundHttpException;

use common\models\Settings;
use common\modules\support\models\redmine\Issue;
use common\modules\support\models\redmine\IssueSearch;

/**
 * Default controller for the `support` module
 */
class SupportController extends Controller
{
	public $meta_title;
    public $meta_description;
    public $meta_keywords;
    
	public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'user' => 'support',
                'only' => ['index'],
                'rules' => [
                    [
                        'allow' => true,
                        'actions' => ['index'],
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }

	public static function actionsTitles()
    {
        return [
            'Index'          => 'Техническая поддержка',
        ];
    }

    public function actionIndex()
    {
        $client = new \Redmine\Client('http://help-russia.ru', Yii::$app->support->identity->redmine_key);

        $works = $client->issue->all([
            'author_id' => 23
        ]);

        return $this->render('index', [
            'works' => $works,
            // 'ratings' => $ratings,
            // 'tests' => $tests,
            // 'approves' => $approves,
            // 'accepteds' => $accepteds,
        ]);
    }

    public function actionCreate()
    {
        $model = new Issue();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    public function actionView($id)
    {
        $model = $this->findModel($id);

        if($model->author_id != Yii::$app->support->identity->support_id)
        {
            throw new NotFoundHttpException('Доступ запрещен!');
        }

        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 integer $id
     * @return Post the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Issue::findOne($id)) !== null) 
        {
            return $model;
        } 
        else 
        {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
