<?php

namespace app\controllers\mikrotik\terminal;

use Yii;
use yii\web\Controller;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use app\models\mikrotik\terminal\Terminal;
use yii\helpers\Url;
use app\models\mikrotik\backup\Backupdb;
use app\models\mikrotik\MikrotikSideMenu;
use yii\data\ArrayDataProvider;

class TerminalController extends Controller {

    public function behaviors() {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['index'],
                        'allow' => true,
                        'roles' => ['mikrotik_terminal'],
                    ],
                    [
                        'actions' => [],
                        'allow' => true,
                        'roles' => ['admin'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
//                    'logout' => ['post'],
                ],
            ],
        ];
    }

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

    public function actionIndex() {
        $model = new Terminal();
        $menu = new MikrotikSideMenu();
        $response = null;
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            $session = Yii::$app->session;
            $session->open();
            $response.=$model->response;
            $server[$session->get('ip')] = ['login' => $session->get('login'), 'pwd' => $session->get('pwd')];
            $msg = $model->command;
            //return var_dump($model->com($server, $msg));
            $model->response.=$session->get('login') . ' > ' . $msg . "\r\n";
            $model->response.=$model->com($server, $msg) . "\r\n";
            $model->command = '';
        }

        return $this->render('/mikrotik/terminal/terminal', [
                    'menu' => $menu->getMenu(),
                    'model' => $model,
        ]);
    }

}
