<?php

namespace app\controllers;

use Yii;
use app\models\Vltransportation;
use app\models\Activelog;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\web\Response;
use yii\widgets\ActiveForm;
use app\models\District;
use yii\helpers\ArrayHelper;
use app\models\VltransportationSearch;
use app\models\State;
use app\models\Staff;
use app\models\Boxidref;
use app\models\Artcentre;
use app\models\Vll;
use app\base\Common;

/**
 * VltransportationController implements the CRUD actions for Vltransportation model.
 */
class VltransportationController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['error'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['index', 'create', 'update', 'view', 'delete','staff','artc','staffdetails','boxid','vllname'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Vltransportation models.
     * @return mixed
     */
   public function actionIndex()
    {
        $searchModel = new VltransportationSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

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

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

    /**
     * Creates a new Vltransportation model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
     
    public function actionCreate()
    {
          $model = new Vltransportation();		
		  $model->scenario = 'create';
	         		  
    if ($model->load(Yii::$app->request->post())) {     		
          
 		  // ajax validation
            if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
                Yii::$app->response->format = Response::FORMAT_JSON;
                return ActiveForm::validate($model);
            }           		
			
	 if ($model->load(Yii::$app->request->post())) {			   
			 
        $sloc=$model->artccode;		
        $Cmonth=substr(date("F", strtotime(date('Y/m/d'))),0,3);	
        $today = strtotime(date('Y/m/d'));
        $Cweek = ceil(date('d',$today)/7);		
		
	    $BModel = Boxidref::generateBoxno($sloc,$Cmonth,$Cweek);
		 } 
					
          $transaction = \Yii::$app->db->beginTransaction();
			try {
			   if (!($flag =$model->save())) {
                            $transaction->rollBack();
                           return false;
               }			   
			   $BModel->save();
				  
			  if ($flag) {
				        $transaction->commit();
                        Yii::$app->session->setFlash('success', 'Transaction Saved Successfully');                      
						return $this->redirect(['view', 'id' => $model->recid]);
                        
                }
			   } catch (\yii\db\Exception $e) {
				   // echo $e->getName();
					Yii::$app->session->setFlash('error', 'Errors occured in the Transaction. Please double check your answers');
				    $transaction->rollBack();	
					return $this->redirect(['/'.Yii::$app->controller->id]);				   	
                }
		
		}	
         
            return $this->render('create', [
                'model' => $model,
            ]);
        
    }
	
    /**
     * Updates an existing Vltransportation model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
			
		if ($model->load(Yii::$app->request->post())) {     		
          
 		  // ajax validation
            if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
                Yii::$app->response->format = Response::FORMAT_JSON;
                return ActiveForm::validate($model);
            } 

        $transaction = \Yii::$app->db->beginTransaction();
			try {
			   if (!($flag =$model->save())) {
                            $transaction->rollBack();
                           return false;
               }			
			  if ($flag) {
				        $transaction->commit();
                        Yii::$app->session->setFlash('success', 'Transaction Updates Successfully');                      
						return $this->redirect(['view', 'id' => $model->recid]);
                        
                }
			   } catch (\yii\db\Exception $e) {				  
					Yii::$app->session->setFlash('error', 'Errors occured in the Transaction. Please double check your answers');
				    $transaction->rollBack();	
					return $this->redirect(['/'.Yii::$app->controller->id]);				   	
                }
		
		}	
         
            return $this->render('update', [
                'model' => $model,
            ]);
      
   }

    /**
     * Deletes an existing Vltransportation model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();
        return $this->redirect(['/'.Yii::$app->controller->id]);
    }

    /**
     * Finds the Vltransportation model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Vltransportation the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Vltransportation::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
	
	   public function actionStaff()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $request = Yii::$app->request;
        if ($request->isGet)
            $id = $request->get('uid');
        if ($request->isPost)
            $id = $request->post('uid');
	  
        $model = Staff::find()->where(["staffname" => $id])->one();
        if ($model !== null) {		
         return $model;
        } 
    }	 
	
	   public function actionArtc()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $request = Yii::$app->request;
        if ($request->isGet)
            $id = $request->get('uid');
        if ($request->isPost)
            $id = $request->post('uid');
	  
        $model = Artcentre::find()->where(["artcname" => $id])->one();
        if ($model !== null) {		
         return $model;
        } 
    }	

    public function actionStaffdetails()
    {    
     Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $request = Yii::$app->request;
        if ($request->isGet)
            $id = $request->get('depdrop_parents');
        if ($request->isPost)
            $id = $request->post('depdrop_parents');
		
		$aid =$id[0];
		$Artccode=Artcentre::find()->where(["artcname" => $aid])->one()->artccode;
        
        $selected = "";
		 $list = Staff::find()->select(['staffname'])->where(["artccode" =>$Artccode])->andWhere(["status" => 1])->distinct()->orderBy(['staffname' => SORT_ASC])->all();
		 $model = ArrayHelper::map($list, 'staffname', 'staffname');
   
        $arr = [];
        $index = 0;
        foreach ($model as $key => $value) {
            $arr[$index]['id'] = (string)$key;
            $arr[$index]['name'] = (string)$value;
            $index++;
        }
        return ['output' => $arr, 'selected' => $selected];	       
   
    }	
	
	
	   public function actionBoxid()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $request = Yii::$app->request;
        if ($request->isGet)
            $id = $request->get('uid');
        if ($request->isPost)
            $id = $request->post('uid');
	  
        $model = Artcentre::find()->where(["artcname" => $id])->one();
        if ($model !== null) {	
            $Cmonth=substr(date("F", strtotime(date('Y/m/d'))),0,3);
			$today = strtotime(date('Y/m/d'));
			$Cweek = ceil(date('d',$today)/7);
			
            $Boxid= Common::getBoxid($model->artccode,$Cmonth,$Cweek);	
         } 
		else
		    $Boxid="";
		return $Boxid;
    }	
	
	   public function actionVllname()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $request = Yii::$app->request;
        if ($request->isGet)
            $id = $request->get('uid');
        if ($request->isPost)
            $id = $request->post('uid');
		
        $model = Artcentre::find()->where(["artcname" => $id])->one();
        if ($model !== null) {
			$Vllname=Vll::find()->where(["vllcode" => $model->vllcode])->one()->name_vl_lab_linked;;
         } 
		else
		    $Vllname="";
		return $Vllname;
    }	
  
}
