<?php

namespace common\modules\support\controllers;

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

use common\components\FrontendController;
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 FrontendController
{    
	public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'user' => 'support',
                'only' => ['index', 'create', 'view', 'file', 'close'],
                'rules' => [
                    [
                        'allow' => true,
                        'actions' => ['index', 'create', 'view', 'file', 'close'],
                        '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'],
                'assigned_to_manager_id' => null
            ];

            $membership = $client->membership->all($model->project_id);

            if(isset($membership))
            {
                foreach ($membership as $member) 
                {
                    if(isset($member['roles']))
                    {
                        foreach ($member['roles'] as $role) 
                        {
                            if($role['id'] == RedmineHelper::MANAGER)
                            {
                                $params['assigned_to_manager_id'] = $member['user']['id'];
                            }
                        }
                    }

                    if($params['assigned_to_manager_id']) 
                    {
                        break;
                    }
                }
            }

            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 actionClose($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('Доступ запрещен!');
        }

        if($model['issue']['status']['id'] == Issue::STATUS_APPROVE)
        {
            $client->issue->update($id, [
                'status_id' => Issue::STATUS_ACCEPTED
            ]);
        }

        return $this->redirect(['/support/view/'.$id]);
    }

    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);
    }
}
