<?php 

namespace common\components;

use yii\base\Object;
use yii\db\Query;
use common\models\Product;
use yii\data\ActiveDataProvider;
use common\models\Transfer;


/**
 * 
 * @property common\models\Account $account a kassza
 * @property common\models\Product[] $products a termékek 
 * */
class ProductInventory extends Object{
	

	
	
	/**melyik kassza, csak akkor használjuk , ha a params['product_visiblity'] == 'account'*/
	public $account;
	
	/**read products query*/
	protected $query;
	/**
	 * a termék lista
	 * */
	public $products;
	
	public $dataProvider;
	
	public $pagination ;
	
	
	public function createDataProvider(){
		 $this->buildQuery();
		 $this->mkDataProvider();
		
	}
	public function createProductList(){
		
		 $this->buildQuery();
		 $this->readProducts();
		
	}
	
	protected function buildQuery(){
		$this->query = Product::find();
		$this->query = new Query();
		$this->query->select([ 'account.id_account as account_id_account','account.name as account_name', 'product.barcode as product_barcode', 'product.product_number as product_number',  'product.id_product as product_id','product.name as product_name','product.stock as product_stock','coalesce( sum(transfer.count),0 ) as product_sold']);
		$this->query->from('product');
		$this->query->leftJoin('transfer', 'product.id_product = transfer.id_object and transfer.type = 10');
		$this->query->innerJoin('account', 'product.id_account = account.id_account');
		$this->query->groupBy(['product.id_product','product.name','product.stock','product.barcode', 'product.product_number','account.id_account','account.name' ]);
		
		$this->query->andWhere(['in','transfer.status', [Transfer::STATUS_PAID, Transfer::STATUS_NOT_PAID]]);
		
		
		
		
		if ( Helper::isProductVisibilityAccount() && isset($this->account)){
			$this->query->andWhere(['product.id_account' => $this->account->id_account]);
		}
		
// 		$this->query->orderBy('product.name');
	}
	
	
	protected function getSortAttributes(){
		
		return Helper::mkYiiSortItems([
				['product_id','product.id_product'],
				['product_number','product.product_number'],
				['product_barcode','product.barcode'],
				['product_name','product.name'],
				['product_sold','sum(transfer.count)'],
				['product_stock','product.stock'],
				['account_name','account.name'],
		]);
	}
	
	protected function readProducts(){
		
		$this->products = $this->query->findAll();
		
	}
	
	
	protected function mkDataProvider(){
		$this->dataProvider = new ActiveDataProvider(
			[
				'query' => $this->query,
					'sort' =>[
							'defaultOrder' => ['product_name'  => SORT_ASC],
							'attributes' => $this->getSortAttributes()
							],
			]
				
		);
		
		if ( isset($this->pagination) && $this->pagination == false ){
			$this->dataProvider->pagination = false;
		}
		
// 		echo print_r( $this->dataProvider->sort );
	}
	
	
}

?>