<?php

namespace common\modules\support\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\helpers\ArrayHelper;
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 = $this->getClient();

        $user = $client->user->getCurrentUser();

        $params = [
            'author_id' => $user['user']['id'],
        ];

        if(Yii::$app->request->get('s'))
        {
            $params = ArrayHelper::merge($params, [
                'f[]' => 'subject',
                'op[subject]' => '~',
                'v[subject][]' => Yii::$app->request->get('s'),
            ]);
        }

        $models = $client->issue->all($params);

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

    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)
    {
        $client = $this->getClient();

        $user = $client->user->getCurrentUser();

        $model = $client->issue->show($id);

        if(empty($model['issue']) || $model['issue']['author']['id'] != $user['user']['id'])
        {
            throw new NotFoundHttpException('Доступ запрещен!');
        }

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

    protected function getClient()
    {
        return $client = new \Redmine\Client(Settings::getValue('redmine-url'), Yii::$app->support->identity->redmine_key);
    }
}
