<?php

namespace app\controllers\mikrotik\ip\snmp;

require_once 'PEAR2_Net_RouterOS-1.0.0b5.phar';

use Yii;
use yii\helpers\Url;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\data\ArrayDataProvider;
use app\models\mikrotik\MikrotikSideMenu;
use app\models\mikrotik\ip\snmp\Snmp;
use app\models\mikrotik\ip\snmp\Communities;
use app\models\mikrotik\Interfaces;

class SnmpController extends Controller {

    public function behaviors() {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'except' => ['index'],
                'rules' => [
                    [
///access controll//////////////////////////////////////////////////////////
                        'actions' => ['index'], //what should be controlled - actionPing 
                        'allow' => true, //allow or deny this action   
                        'roles' => ['mikrotik_ipUpdateSNMP'], //"controller's name"_"rule name"
                    ],
                    [
                        '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() {
        $menu = new MikrotikSideMenu();
        $model = new Snmp();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            $opt = implode(",", $_POST['Snmp']['trap_interfaces']);
            $model->trap_interfaces = $opt;
            $opt = implode(",", $_POST['Snmp']['trap_generators']);
            $model->trap_generators = $opt;
            $model->update();
            return $this->redirect(Url::toRoute('mikrotik/ip/snmp/snmp/index'));
        }
        $com = new Communities();
        $comNames = $com->getNames();
        $model->getAll();
        $interfaces = new Interfaces();
        $intName = $interfaces->names();
        $intNames['all'] = 'all';
        foreach ($intName as $value) {
            $intNames[$value] = $value;
        }
        $model->trap_interfaces = explode(',', $model->trap_interfaces);
        $model->trap_generators = explode(',', $model->trap_generators);

        return $this->render('/mikrotik/ip/snmp/index', [
                    'menu' => $menu->getMenu(),
                    'model' => $model,
                    'intName' => $intNames,
                    'comName' => $comNames,
        ]);
    }

}
