<?php

namespace app\controllers\mikrotik;

require_once 'PEAR2_Net_RouterOS-1.0.0b5.phar';

use PEAR2\Net\RouterOS;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use app\models\mikrotik\PingForm; // location of controller's model folder app\models\"module folder - same as controller's name"\"model file name" 
use app\models\mikrotik\MikrotikSideMenu;

class PingController extends Controller {

    public function behaviors() {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'except' => ['index'],
                'rules' => [
                    [
                        ///access controll//////////////////////////////////////////////////////////
                        'actions' => ['ping'], //what should be controlled - actionPing 
                        'allow' => true, //allow or deny this action   
                        'roles' => ['ping_ping'], //"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 PingForm();
       
        return $this->render('index', [
                    'model' => $model,
                    'menu' => $menu->getMenu(),
        ]);
    }

    public function actionPing() {
        $menu = new MikrotikSideMenu();
        $model = new PingForm();
        if (Yii::$app->request->isPost) {
            $model->load(Yii::$app->request->post());
            if ($client = new RouterOS\Client('192.168.80.10', 'admin', '')) {
                $pingRequest = new RouterOS\Request('/ping count=3');
                $results = $client->sendSync($pingRequest->setArgument('address', $model->address));

                return $this->render('ping', [
                            'results' => $results,
                            'menu' => $menu->getMenu(),
                ]);
            } else {
                return [
                    'error' => [
                        'class' => 'yii\web\ErrorAction',
                    ],
                ];
            }
        }
    }

}
