<?php

namespace frontend\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\InventoryItem;
use yii\db\Query;
use yii\db\Expression;
use common\models\User;
use common\models\Product;
use common\models\InventoryGroup;
use common\components\Helper;
use common\models\Inventory;

/**
 * InventoryItemSearch represents the model behind the search form about `common\models\InventoryItem`.
 */
class InventoryItemSearch extends InventoryItem
{
	public $inventory;
	public $output;
	public $item_name;
	public $item_type;
	public $item_id;
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id_inventory_item', 'id_inventory', 'count_in', 'count_sold', 'count', 'type', 'id_product', 'id_inventory_group', 'id_user'], 'integer'],
        	['output', 'string'],
        	['item_name', 'string'],
        	['item_type', 'string'],
        	['item_id', 'integer'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query =  new Query();
        
    	$query->select([
    			'inventory_item.id_inventory_item as item_id_inventory_item',
    			'inventory_item.created_at as item_created_at',
    			new Expression('case when inventory_item.id_product is null then inventory_group.name else product.name end as item_name'),
    			'user.username as user_username',
    			'coalesce(inventory_item.count_prev ,0)as item_count_prev',
    			'coalesce(inventory_item.count_in,0) as item_count_in',
    			'coalesce(inventory_item.count_sold,0) as item_count_sold',
    			'coalesce(inventory_item.count,0) as item_count',
    			'coalesce(inventory_item.count_system,0) as item_count_system',
    			'inventory.created_at as inventory_created_at',
    			'inventory_prev.id_inventory as inventory_prev_id_inventory',
    			'inventory_prev.name as inventory_prev_name',
    			new Expression('(coalesce(inventory_item.count,0) - ( coalesce(inventory_item.count_prev,0) + coalesce(inventory_item.count_in,0) - coalesce(inventory_item.count_sold,0) )) as item_difference'),
    	]);
    	
    	$query->from(InventoryItem::tableName());
    	
    	
    	$query->innerJoin(User::tableName(), "user.id = inventory_item.id_user");
    	$query->leftJoin(Product::tableName(), "product.id_product = inventory_item.id_product");
    	$query->leftJoin(InventoryGroup::tableName(), "inventory_group.id_inventory_group = inventory_item.id_inventory_group");
    	$query->leftJoin(Inventory::tableName(), "inventory.id_inventory = inventory_item.id_inventory");
    	
    	$query->leftJoin( "inventory_item as item_prev", "item_prev.id_inventory_item = inventory_item.id_inventory_item_prev" );
    	$query->leftJoin( "inventory as inventory_prev", "inventory_prev.id_inventory = item_prev.id_inventory" );
    	
    	$query->andWhere( ['inventory_item.id_inventory' => $this->inventory->id_inventory] );
    	
    	$this->load($params);
    	
    	if (!$this->validate()) {
    		// uncomment the following line if you do not want to return any records when validation fails
    		// $query->where('0=1');
    		return $dataProvider;
    	}
    	
    	$dataProvider = new ActiveDataProvider(
    		['query' => $query ,
    		 'pagination' => ( empty($this->output)  ?  [] : false  ),
    		 'sort' =>  [
    		 		'defaultOrder' => ['item_name' => SORT_ASC],
    		 		'attributes' => Helper::mkYiiSortItems([
    		 			['item_created_at', 'item_created_at'],	
    		 			['item_name', 'item_name'],	
    		 			['user_username', 'user_username'],	
    		 			['item_count_prev', 'item_count_prev'],	
    		 			['item_count_sold', 'item_count_sold'],	
    		 			['item_count_in', 'item_count_in'],	
    		 			['item_count', 'item_count'],	
    		 			['item_count', 'item_count'],	
    		 			['item_difference', 'item_difference'],	
    		 			['item_count_system', 'item_count_system'],	
    		 			['inventory.id_inventory', 'inventory_id_inventory'],	
    		 			['inventory.name', 'inventory_name'],	
    		 			['inventory_prev_name', 'inventory_prev_name'],	
    		 		])
    		 ,		
    		]		
    				]
    	);
      

    	if ( !empty($this->item_type) && is_numeric($this->item_id) ){
    		if ( $this->item_type == 'product'){
    			$query->andFilterWhere(['product.id_product' => $this->item_id]);
    		}else if ( $this->item_type == 'group' ){
    			$query->andFilterWhere(['inventory_group.id_inventory_group' => $this->item_id]);
    		}
    	}
    	

        return $dataProvider;
    }
}
