<?php

namespace app\controllers;

use Yii;
use app\base\Model;
use app\models\Stafflocationmapping;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use app\models\StafflocationmappingSearch;
use app\models\Users;
use app\models\Userrole;
use app\models\Staff;

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

    /**
     * Lists all Stafflocationmapping models.
     * @return mixed
     */
    public function actionIndex()
    {
		/*
        $dataProvider = new ActiveDataProvider([
			'query' => Stafflocationmapping::find()->groupBy(['staffcode']),
		]);

        return $this->render('index', [
            'dataProvider' => $dataProvider,
        ]);
		*/
		
		$searchModel = new StafflocationmappingSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

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

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

    /**
     * Creates a new Stafflocationmapping model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    /*
    public function actionCreate()
    {
        $model = new Stafflocationmapping();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->locmap_id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }
    */
    
    public function actionCreate()
    {
        $model = new Stafflocationmapping;
        $models = [new Stafflocationmapping];

        if ($model->load(Yii::$app->request->post())) {

            $post = [];
            $formName = $model->formName();
            $formVars = Yii::$app->request->post($formName);
            
            foreach($formVars as $key => $val) {
                if(is_array($val)) :
                    $post[$formName][] = $val;
                    unset($formVars[$key]);
                endif;
            }
            
            $models   = [];		
			$artc = array();
			foreach($post[$formName] as $k => $p) {
				//print_r($p["artccode"]);
		       // exit;				
				if(!in_array($p["artccode"], $artc))
				{
				 $models[] = new Stafflocationmapping;
                 $posts[$formName][$k] = array_merge($p, $formVars);
				 $artc[] =  $posts[$formName][$k]['artccode'];
				}	 
            }
			
			// print_r($posts[$formName][$k]);
		    // exit;
			
			$staffcode=$model->staffcode;	
		    $artccode = implode(",",$artc);	
		    $cntartc=count($artc);
				   
		   $Staffmodel = Staff::find()->where(["staffcode" => $staffcode])->one();
			if($Staffmodel  !== null) 
			 $Staffname = $Staffmodel->staffname;
			else
			 $Staffname="";
		  			
            Model::loadMultiple($models, $posts);
            $valid = Model::validateMultiple($models);

            if ($valid) {
                $transaction = \Yii::$app->db->beginTransaction();

                try {
                    foreach ($models as $modelAddress) {
                        if (! ($flag = $modelAddress->save(false))) {
                            $transaction->rollBack();
                            break;
                        }
                    }
                    if ($flag) {					    
					      $Umodel = Users::find()->where(['users_name' => $staffcode])->one();
                          if($Umodel === null)						  
                          $Umodel = new Users;
					  
						  $Umodel->users_name =  $staffcode;	
						  $Umodel->user_type =  2;
						  $Umodel->password = 123456;
						  $Umodel->auth_key = Yii::$app->security->generateRandomString();
						  $Umodel->full_name = $Staffname;
						  if($cntartc >1)
						   $Umodel->user_role = 2;
					      else
						   $Umodel->user_role = 3;  						
						  $Umodel->location = $artccode;						  
						  $Umodel->status=1;
						  $Umodel->create_time=$model->create_time;
						  $Umodel->create_user=$model->create_user;
						  $Umodel->update_time=$model->update_time;
						  $Umodel->record_date=strtotime(date('Y/m/d'));	
					
				 if ($Umodel->save(false)) {  
					if($Umodel->location != "")					
					 $locs = explode(",", $Umodel->location);
				  
				   foreach($locs as $val) {
					  $Rmodel = new Userrole;	
					  $Rmodel->user_id = $Umodel->usr_id;
					  $Rmodel->authorized_loc = $val;	
					  $Rmodel->status=1;
					  $Rmodel->create_time=$Umodel->create_time;
					  $Rmodel->create_user=$Umodel->create_user;
					  $Rmodel->update_time=$Umodel->update_time;
					  $Rmodel->record_date=$Umodel->record_date;
					  
					  $Rmodel->save(false);
					}	
				  }					
                        $transaction->commit();
                        Yii::$app->session->setFlash('success', "Records Created Successful");
                        return $this->redirect(['/'.Yii::$app->controller->id]);
                        // return $this->redirect(['view', 'id' => $models[0]->locmap_id]);
                    }
                } catch (Exception $e) {
                    $transaction->rollBack();
                }
            }
        }
        
        return $this->render('create', [
            'model' => $model,
            'models' => (empty($models)) ? [new Stafflocationmapping] : $models,
        ]);
    }

    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $models = $this->findModels($id);

        if ($model->load(Yii::$app->request->post())) {

            $post = [];
            $formName = $model->formName();
            $formVars = Yii::$app->request->post($formName);
            
            foreach($formVars as $key => $val) {
                if(is_array($val)) :
                    $post[$formName][] = $val;
                    unset($formVars[$key]);
                endif;
            }
            
            $recmodels = $models;
            $models   = [];
			$artc = array();
            foreach($post[$formName] as $k => $p) {
                if(empty($p["locmap_id"])) {
				   if(!in_array($p["artccode"], $artc)) {
                    $models[] = new Stafflocationmapping;
                    $p["create_user"] = $model->create_user;
                    $p["staffcode"] = $model->staffcode;
					// $artc[] =  $model->artccode;
				  }
                }
                else
                    $models[] = $this->findModel($p["locmap_id"]);
                    $posts[$formName][$k] = array_merge($p, $formVars);
				  if(!in_array($p["artccode"], $artc))
					$artc[] =  $posts[$formName][$k]['artccode'];			
					
             }
			
            $staffcode=$model->staffcode;	
		    $artccode = implode(",",$artc);
			$cntartc=count($artc);
			
            Model::loadMultiple($models, $posts);
            $valid = Model::validateMultiple($models);

            if(count($recmodels) > count($posts[$formName])) {
                $delid = substr(Yii::$app->request->post()[$formName]["delrec"], 0, -1);
                foreach (array_unique(explode(",", $delid)) as $key => $value) {
                    $this->findModel($value)->delete();
                }
            }

            if ($valid) {
                $transaction = \Yii::$app->db->beginTransaction();

                try {
                    foreach ($models as $modelAddress) {
                        if (! ($flag = $modelAddress->save(false))) {
                            $transaction->rollBack();
                            break;
                        }
                    }

                    if ($flag) {
						$Umodel = Users::find()->where(['users_name' => $staffcode])->one();
                          if($Umodel === null)						  
                          $Umodel = new Users;					  
						  $Umodel->users_name =  $staffcode;	
						  $Umodel->user_type =  2;
						  if($cntartc >1)
						   $Umodel->user_role = 2;
					      else
						   $Umodel->user_role = 3; 
						  unset($Umodel->password);
					      unset($Umodel->full_name);
						  $Umodel->auth_key = Yii::$app->security->generateRandomString();											  
						  $Umodel->location = $artccode;						  
						  $Umodel->status=1;
						  $Umodel->create_time=$model->create_time;
						  $Umodel->create_user=$model->create_user;
						  $Umodel->update_time=date('U');
				          $Umodel->update_user=yii::$app->user->identity->id;
						  $Umodel->record_date=strtotime(date('Y/m/d'));	
						  
			       if ($Umodel->save(false)) {  
                       if (($URmodel = Userrole::find()->where(['user_id' => $Umodel->usr_id])->one()) !== null) {		
							Userrole::deleteAll(['user_id' => $Umodel->usr_id]);
						}
			
					if($Umodel->location != "")		
					 $locs = explode(",", $Umodel->location);
				  
				   foreach($locs as $val) {
					  $Rmodel = new Userrole;	
					  $Rmodel->user_id = $Umodel->usr_id;
					  $Rmodel->authorized_loc = $val;	
					  $Rmodel->status=1;
					  $Rmodel->create_time=$Umodel->create_time;
					  $Rmodel->create_user=$Umodel->create_user;
					  $Rmodel->update_time=$Umodel->update_time;
					  $Rmodel->record_date=$Umodel->record_date;
					  
					  $Rmodel->save(false);
					}
				  }					
                        $transaction->commit();
                        Yii::$app->session->setFlash('success', "Records Updated Successful");
                        return $this->redirect(['/'.Yii::$app->controller->id]);
                        // return $this->redirect(['view', 'id' => $models[0]->locmap_id]);
                    }
                } catch (Exception $e) {
                    $transaction->rollBack();
                }
            }
        }
        
        return $this->render('update', [
            'model' => $model,
            'models' => (empty($models)) ? [new Stafflocationmapping] : $models,
        ]);
    }

    /**
     * Deletes an existing Stafflocationmapping 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();
        $model = $this->findModel($id);
        $staffcode = $model->staffcode;
        Stafflocationmapping::deleteAll(['staffcode' => $staffcode]);
        Yii::$app->session->setFlash('success', "Selected Record Deleted Successful");

        return $this->redirect(['/'.Yii::$app->controller->id]);
    }

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

    protected function findModels($id)
    {
        $model = Stafflocationmapping::findOne($id);
        $staffcode = $model->staffcode;

        if (($models = Stafflocationmapping::find()->where(['staffcode' => $staffcode])->all()) !== null) {
            return $models;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
