<?php

namespace common\modules\support\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\web\Controller;
use yii\web\Response;
use yii\web\NotFoundHttpException;

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

/**
 * 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', 'create', 'view', 'file'],
                'rules' => [
                    [
                        'allow' => true,
                        'actions' => ['index', 'create', 'view', 'file'],
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }

    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()
    {
        $this->view->registerJsFile('/js/support.js', ['position' => yii\web\View::POS_END ]);

        $model = new Issue();
        $model->setScenario(Issue::SCENARIO_CREATE);

        $client = $this->getClient();

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

        if ($model->load(Yii::$app->request->post()) && $model->validate()) 
        {
            $params = [
                'subject' => $model->subject,
                'description' => $model->description,
                'project_id' => $model->project_id,
                'priority_id' => $model->priority_id,
                'status_id' => $model->status_id,
                'tracker_id' => $model->tracker_id,
                'author_id' => $user['user']['id']
            ];

            if($model->files)
            {
                $uploads = [];

                foreach ($model->files as $file) 
                {
                    $uploads[] = [
                        'token' => $file['token'],
                        'filename' => $file['filename'],
                        'content_type' => $file['type'],
                    ];
                }

                $params = ArrayHelper::merge($params, [
                    'uploads' => $uploads
                ]);
            }

            $client->issue->create($params);

            return $this->redirect(['/support']);
        }
            
        return $this->render('create', [
            'model' => $model,
            'user' => $user
        ]);
    }

    public function actionView($id)
    {
        $this->view->registerJsFile('/js/support.js', ['position' => yii\web\View::POS_END ]);

        $client = $this->getClient();

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

        $model = $client->issue->show($id, [
            'include' => [
                'attachments',
                'journals'
            ]
        ]);

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

        $issue = new Issue();
        $issue->setScenario(Issue::SCENARIO_UPDATE);

        if ($issue->load(Yii::$app->request->post()) && $issue->validate()) 
        {
            $params = [
                'notes' => $issue->notes,
            ];

            if($issue->files)
            {
                $uploads = [];

                foreach ($issue->files as $file) 
                {
                    $uploads[] = [
                        'token' => $file['token'],
                        'filename' => $file['filename'],
                        'content_type' => $file['type'],
                    ];
                }

                $params = ArrayHelper::merge($params, [
                    'uploads' => $uploads
                ]);
            }

            $client->issue->update($id, $params);

            return $this->refresh();
        }

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

    public function actionFile()
    {
        if(Yii::$app->request->isAjax)
        {
            Yii::$app->response->format = Response::FORMAT_JSON;

            try 
            {
                if($_FILES['files'])
                {
                    $client = $this->getClient();

                    $html = '';
                    foreach ($_FILES['files']['name'] as $i => $name) 
                    {
                        if($_FILES['files']['size'][$i] <= RedmineHelper::MAX_FILE_SIZE) 
                        {
                            $response = json_decode($client->attachment->upload(@file_get_contents($_FILES['files']['tmp_name'][$i])));

                            $html .= $this->renderPartial('_file', [
                                'name' => $name,
                                'size' => RedmineHelper::formatSize($_FILES['files']['size'][$i]),
                                'token' => $response->upload->token,
                                'type' => $_FILES['files']['type'][$i]
                            ]);
                        }
                        else
                        {
                            $html .= Html::tag('div', 'Превышен максимально допустимый размер файла&nbsp;&nbsp;<a class="delete-file" href="#"><span class="glyphicon glyphicon-remove color_gray"></span></a>', ['class'=>'file_box_wr']);
                        }
                    }

                    return [
                        'html' => $html,
                        'success' => true
                    ];
                }
            } 
            catch (Exception $e) 
            {
                return ['success' => false];
            }
                
            return ['success' => false];
        }
        else
        {
            throw new NotFoundHttpException('Доступ запрещен!');
        }
    }

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