<?php

namespace backend\controllers;

use Yii;
use common\models\Procurement;
use backend\models\ProcurementSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use common\models\Warehouse;
use common\models\Product;
use common\models\User;
use common\components\Helper;
use common\models\Account;
use yii\helpers\Url;
use backend\models\ProcurementUpdate;

/**
 * ProcurementController implements the CRUD actions for Procurement model.
 */
class ProcurementController  extends \backend\controllers\BackendController
{

	
	public function behaviors()
	{
		return [
			'access' => [
				'class' => \yii\filters\AccessControl::className(),
				'rules' => [
				// allow authenticated users
					[
						'actions' => ['create','index','view', 'create-product','update'],
						'allow' => true,
						'roles' => ['@'],
					],
				// everything else is denied
				],
			],
		];
	}
	
	
    /**
     * Lists all Procurement models.
     * @return mixed
     */
    public function actionIndex()
    {
    	
    	$warehouses = Warehouse::read(null);
    	$products = Product::read(null);
    	$users = User::read(null);
    	
        $searchModel = new ProcurementSearch();

        $today = time();
        $tomorrow = time()+86400;
        $searchModel->timestampStart = date("Y-m-d" , $today  );
        $searchModel->timestampEnd = date("Y-m-d"   , $tomorrow );
        $searchModel->date_start = Yii::$app->formatter->asDate($today);
        $searchModel->date_end = Yii::$app->formatter->asDate($tomorrow);
        
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

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

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

    /**
     * Update procurement
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
    	$model = ProcurementUpdate::findOne($id);
    	if ( !isset($model)){
    		throw new NotFoundHttpException("Az oldal nem található");
    	}
    	
    	if ($model->load(Yii::$app->request->post()) && $model->validate()) {
    		$model->save();
    	}
    	
        return $this->render('update', [
            'model' => $model
        ]);
    }

    /**
     * Creates a new Procurement model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Procurement();
        $model->scenario = 'create_general';
        
        $accounts = Account::find()->andWhere(['status' => Account::STATUS_ACTIVE])->andWhere(['type' => Account::TYPE_ALL])->all();
        
        $model->id_user = Yii::$app->user->id;

        $warehouses = Warehouse::read(null);
        
        $products = Product::find()->all();
        $products = Product::modelToMapIdNameLong( $products );
        
        if ( count($warehouses) <= 0 ){
        	 throw new NotFoundHttpException( Yii::t('common/procurement' ,'No active warehouse found.' ));
        }
        
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
        	
        	$connection = \Yii::$app->db;
        	
        	$transaction = $connection->beginTransaction();
        	
        	try {
				
        		$product = $model->_product;
        		$model->stock = $product->stock;
        		$result = $model->save(false);
        		$model->id_account = $product->id_account;
        		$product->stock = $product->stock + $model->count;
        		$result &= $product->save(false);
        		
        		if ($result) {
        			$transaction->commit();
        		} else {
        			$transaction->rollback();
        			Helper::flash('error', "Hiba történt!");
        			throw new NotFoundHttpException( Yii::t('common/procurement' ,'Failed to fullfill procurement.' ));
        		}
        		Helper::flash('success', Yii::t('backend/procurement', 'Beszerzés mentve'));
        	} catch (\Exception $e) {
        		$transaction->rollback();
        		throw $e;
        	}
        	
        	
        	if ( isset($_POST['_next'])){
            	return $this->redirect(['create' ]);
        	}else{
	            return $this->redirect(['index' ]);
        	}
        } else {
        	
        	
        	
            return $this->render('create', [
                'model' => $model,
            	'warehouses' =>$warehouses,
            	'accounts' => $accounts,
            	'products' => $products
            ]);
            
            
        }
    }
    /**
     * Creates a new Procurement model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreateProduct($id)
    {
    	
    	$product = $this->findProduct($id);
    	
        $model = new Procurement();
        
        $warehouses = Warehouse::read(null);
        
        $model->id_user = Yii::$app->user->id;
        $model->id_product = $product->id_product;
        $model->stock = $product->stock;

        $warehouses = Warehouse::read(null);
        
        if ( count($warehouses) <= 0 ){
        	 throw new NotFoundHttpException( Yii::t('common/procurement' ,'No active warehouse found.' ));
        }
        
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
        	
        	$connection = \Yii::$app->db;
        	
        	$transaction = $connection->beginTransaction();
        	
        	try {
				
        		$result = $model->save(false);
        		
        		$product->stock = $product->stock + $model->count;
        		$result &= $product->save(false);
        		
        		if ($result) {
        			$transaction->commit();
        		} else {
        			$transaction->rollback();
        		}
        	} catch (\Exception $e) {
        		$transaction->rollback();
        		throw $e;
        	}
        	
        	
//             return $this->redirect(['view', 'id' => $model->id_procurement]);
            	$url = Url::previous("product_index");
            	if ( isset($url)){
            		return $this->redirect(  $url );
            	}else{
            		return $this->redirect(['product/index']);
            	}
            
//             return $this->redirect(Yii::$app->request->referrer);
        } else {
            return $this->render('create_product', [
                'model' => $model,
            	'warehouses' =>$warehouses,
            	'product' => $product
            ]);
        }
    }

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