<?php

namespace modules\cors\controllers;

use Yii;
use modules\cors\models\Sightcheckbe;
use modules\cors\models\SightcheckbeSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use modules\forms\models\Dt188;
/**
 * SightcheckController implements the CRUD actions for sightcheckbe model.
 */
class SightcheckController extends Controller
{
   public function behaviors()
    {
        return [
			'access' => [
                'class' => \yii\filters\AccessControl::class,
                'only' => ['create', 'update', 'view', 'pdf'],
                'rules' => [
                
                    [
                        'actions' => ['create', 'update', 'view', 'pdf'],
                        'allow' => true,
                        'matchCallback' => function ($rule, $action) {
                            return yii::$app->user->identity->useradv->accesslevel >= 2;
                        }
                    ],
                    [
                        'actions' => ['index', 'deleted'],
                        'allow' => true,
                        'matchCallback' => function ($rule, $action) {
                            return yii::$app->user->identity->useradv->accesslevel >= 7;
                        }
                    ],
                ],
				'denyCallback' => function ($rule, $action) {
					return	$this->redirect(['site/accessdenied']);
			   
			}
            ],
			'verbs' => [
                'class' => VerbFilter::class,
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

	public function beforeAction($action) {
   		$id = yii::$app->request->get('id');
		Yii::$app->runaction('/audit/qcreate', ['id' => $id ? $id : null , 'controller' =>  Yii::$app->controller->id, 'action' => Yii::$app->controller->action->id, 'attributes' => null]);
		return parent::beforeAction($action);
	}
    /**
     * Lists all sightcheckbe models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new SightcheckbeSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('@modules/cors/views/sightcheck/index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
     /**
     * Lists Deleted sightcheckbe models.
     * @return mixed
     */
    public function actionDeleted()
    {
        $searchModel = new SightcheckbeSearch();
        $dataProvider = $searchModel->deleted(Yii::$app->request->queryParams);

        return $this->render('@modules/cors/views/sightcheck/index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single sightcheckbe model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('@modules/cors/views/sightcheck/view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new sightcheckbe model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
	public function actionCreate()
    {
        $model = new Sightcheckbe(['id' => Sightcheckbe::Tempid()]);
        $model->status = 'Active';
        $employees = \backend\models\User::Employees();
    
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            if ($model->result == 'Failed') {
        		$dt188 = new Dt188();
	        	$dt188->relatedid = $model->id;
	        	$dt188->name = $model->driverl->fullname;
	        	$dt188->type = 'sightcheck';
	        	$dt188->datetime = date('Y-m-d H:i:s',strtotime('now'));
	        	$dt188->details = $model->type.' Test Failed By '. $model->driverl->fullname;
	 			$dt188->save();
				$dt188 = Dt188::find()->where(['=', 'created_at', $dt188->created_at])->andWhere(['=', 'created_by', $dt188->created_by])->one();
		   		$alertgroup = \backend\models\Sysusergroupsbe::find()->where(['name' => 'Sight Checks'])->one();
		   		foreach ($alertgroup->user as $key => $user) {
					$alert = new \backend\models\Sysalertsbe();
					$alert->owner = $user->id;
					$alert->alert = 'NON COMPLIANCE RAISED - Eye Sight Test Failed'.$model->driverl->fullname;
					$alert->relatedid = $dt188->id;
					$alert->url = Yii::$app->request->HostInfo.'/dt188/view?id='.$dt188->id;
					$alert->save();
					$alert = \backend\models\Sysalertsbe::find()->where(['=', 'created_at', $alert->created_at])->andWhere(['=', 'created_by', $alert->created_by])->one();
				}
		    }
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('@modules/cors/views/sightcheck/create', [
                'model' => $model,
				'employees' => $employees,
            ]);
        }
    }

    /**
     * Updates an existing sightcheckbe model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $employees = \backend\models\User::Allemployeesid();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('@modules/cors/views/sightcheck/update', [
                'model' => $model,
				'employees' => $employees,
            ]);
        }
    }

    /**
     * Deletes an existing sightcheckbe model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
		$model = $this->findModel($id);
		$model->status = 'Deleted';
		$model->deleted_at = strtotime('now');
		$model->save();
        return $this->redirect(['index']);
    }

    /**
     * Finds the sightcheckbe model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return sightcheckbe the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Sightcheckbe::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
