<?php

namespace modules\cors\controllers;

use Yii;
use modules\cors\models\Fueldatabe;
use modules\cors\models\FueldatabeSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * FueldataController implements the CRUD actions for fueldatabe model.
 */
class FueldataController extends Controller
{
public function behaviors()
    {
        return [
			'access' => [
                'class' => \yii\filters\AccessControl::class,
                'only' => ['create', 'update', 'view', 'pdf'],
                'rules' => [
                
                    [
                        'actions' => ['create', 'update', 'view', 'pdf', 'addrow', 'removerow', 'savefield','tempguid'],
                        '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 fueldatabe models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new fueldatabeSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

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

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

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

    /**
     * Creates a new fueldatabe model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new fueldatabe();
        
        	$tempid = Yii::$app->session->get('fueldatatempid');
        if (!$tempid) {	
			$tempid = \common\models\Base::tempId();
        	Yii::$app->session->set('fueldatatempid', $tempid);
			$r1 = new \backend\models\Fueldatabe();
			$r1->relatedid = $tempid;
			$r1->save();
		}
	
        $vehicles = \yii\helpers\ArrayHelper::map(\modules\cors\models\Vehiclebe::find()->where(['=', 'status', 'Active'])->orderby(['reg' => SORT_ASC])->all(), 'id', 'reg');
        $drivers = \frontend\models\User::Employees();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
        	$model = fueldatabe::find()->where(['=', 'created_at', $model->created_at])->andWhere(['=', 'created_by', $model->created_by])->one();
			$linked = \backend\models\Fueldatabe::find()->where(['relatedid' => Yii::$app->session->get('fueldatatempid')])->all();
				foreach ($linked as $a => $link) {
					$link->relatedid = $model->id;
					$link->save();
				}
			Yii::$app->session->remove('fueldatatempid');
                
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
                'drivers' => $drivers,
                'vehicles' => $vehicles,
            ]);
        }
    }

	 public function actionAddrow() {
		$id = yii::$app->request->Post('id');
		$dt179row = new \backend\models\Fueldatabe();
		$dt179row->relatedid = $id;
		if ($dt179row->save()) {
			return json_encode(['result' => 200, 'message' => 'Row Added']); 
		}else {
			return json_encode(['result' => 100, 'message' => $dt179row->errors]); 
			
		}
	}
    
    public function actionDeleterow() {
		$id = yii::$app->request->Post('id');
		$dt179row = \backend\models\Fueldatabe::find()->where(['id' => $id])->one();
		$dt179row->status = 'Deleted';
		if ($dt179row->delete()) {
			return json_encode(['result' => 200, 'message' => 'Row Deleted']); 
		}else {
			return json_encode(['result' => 100, 'message' => $dt179row->errors]); 
			
		}
	}
    
    Public function actionSavefield() {
		$id = yii::$app->request->Post('id');
		$field = yii::$app->request->Post('field');
		$value = yii::$app->request->Post('value');
		$dt179row = \backend\models\Fueldatabe::find()->where(['id' => $id])->one();
		$dt179row->$field = $value;
		if ($dt179row->save()) {
			return json_encode(['result' => 200, 'message' => 'Saved']); 
		}else {
			return json_encode(['result' => 100, 'message' => $dt179row->errors]); 
			
		}
	}
   
    /**
     * Updates an existing fueldatabe 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);
		$vehicles = \yii\helpers\ArrayHelper::map(\modules\cors\models\Vehiclebe::find()->where(['=', 'status', 'Active'])->orderby(['reg' => SORT_ASC])->all(), 'id', 'reg');
        $drivers = \frontend\models\User::Employees();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
                     'drivers' => $drivers,
                'vehicles' => $vehicles,
            
            ]);
        }
    }

    /**
     * Deletes an existing fueldatabe 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 fueldatabe model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return fueldatabe the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = fueldatabe::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
