<?php

namespace common\models;

use /** @noinspection PhpMethodOrClassCallIsNotCaseSensitiveInspection */
	Yii;
use yii\db\Expression;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use common\components\UserAwareBehavior;
use common\components\ProductAwareBehavior;

/**
 * This is the model class for table "inventory_item".
 *
 * @property integer $id_inventory_item
 * @property integer $id_inventory
 * @property integer $count_in
 * @property integer $count_sold
 * @property integer $count
 * @property integer $count_prev
 * @property integer $count_system
 * @property integer $type
 * @property integer $id_product
 * @property integer $id_inventory_group
 * @property integer $id_user
 * @property integer $id_inventory_item_prev
 * @property integer $price_brutto
 * @property string $created_at
 * @property string $updated_at
 * @property mixed productName
 * @property mixed product
 * @property integer tax
 * @property integer purchase_price_net
 * @property integer net_stock_money
 * @property integer stock_missing_count
 * @property integer stock_missing_money
 * @property \common\models\InventoryGroup inventoryGroup
 */
class InventoryItem extends BaseFitnessActiveRecord
{
    
    public static $TYPE_PRODUCT = 10;
    public static $TYPE_INVENTORY_GROUP = 20;
    
    
    public static /** @noinspection SqlResolve */
		$UPDATE_COUNT = "
    		UPDATE product as p1
			inner JOIN (  select  inventory_item.id_product as id_product  , inventory_item.count as count
 			from inventory_item 
			where inventory_item.type = 10
				 and inventory_item.id_inventory = :id_inventory
				 and inventory_item.count is not null
						 ) as t 
			on t.id_product =  p1.id_product
			SET p1.stock  = case when t.id_product is null then ( p1.stock  )  else (  t.count  )    end	
    		";
    
    
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'inventory_item';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
        	[['count'],'integer'] ,
        	[['count'],'required'] ,
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id_inventory_item' => Yii::t('common/inventory_item', 'Id Inventory Item'),
            'id_inventory' => Yii::t('common/inventory_item', 'Id Inventory'),
            'count_in' => Yii::t('common/inventory_item', 'Count In'),
            'count_sold' => Yii::t('common/inventory_item', 'Count Sold'),
            'count' => Yii::t('common/inventory_item', 'Leltározott mennyiség'),
            'type' => Yii::t('common/inventory_item', 'Type'),
            'id_product' => Yii::t('common/inventory_item', 'Id Product'),
            'id_inventory_group' => Yii::t('common/inventory_item', 'Id Inventory Group'),
            'id_user' => Yii::t('common/inventory_item', 'Id User'),
            'created_at' => Yii::t('common/inventory_item', 'Created At'),
            'updated_at' => Yii::t('common/inventory_item', 'Updated At'),
        ];
    }
    public function behaviors()
    {
    	return ArrayHelper::merge(  [
    			[
    					'class' => UserAwareBehavior::className(),
    			],
    			[
    					'class' => ProductAwareBehavior::className(),
    			]
    			], parent::behaviors());
    }

    public static function creqteQueryInventoryItems($id_inventory ) {
    	$query = InventoryItem::find();
    	
    	$query->andWhere(['inventory_item.id_inventory' => $id_inventory]);
    	return $query;
    }
    
    public function getProduct(){
    	return $this->hasOne( Product::className() , [ 'id_product' => 'id_product' ]);
    }
    
    public function getInventoryGroup(){
    	return $this->hasOne( Product::className() , [ 'id_inventory_group' => 'id_inventory_group' ]);
    }

	public function getInventoryItemPrev(){
		return $this->hasOne( InventoryItem::className(),['id_inventory_item' => 'id_inventory_item_prev'] );
	}

    public function getProductName(){
    	$result = "";
    	
    	$product = $this->product;
    	
    	if ( isset($product)){
    		$result = $product->name;	
    	}
    	
    	return $result;
    }

    public function getInventoryGroupName(){
    	$result = "";
    	
    	$product = $this->inventoryGroup;
    	
    	if ( isset($product)){
    		$result = $product->name;	
    	}
    	
    	return $result;
    }

	/**
	 * @return string
     */
	public function getName(){

    	if ( isset($this->id_product )){
    		$name = $this->getProductName();
    	}else{
    		$name = $this->getInventoryGroupName();
    	}
    	
    	return $name;
    }

	public static function findNextItemAlphabetical($id_inventory_item){

        $inventoryItem = InventoryItem::findOne($id_inventory_item);
        $id_inventory = $inventoryItem->id_inventory;
		$currentItemId = $id_inventory_item;

		$query = new Query();
		$query->select([
			'inventory_item.id_inventory_item as inventory_item_id_inventory',
			new Expression(
				"case when inventory_item.type = " .InventoryItem::$TYPE_PRODUCT . " then product.name else inventory_group.name end as name"
			)
		]);

		$query->from('inventory_item');
		$query->leftJoin("product", 'product.id_product = inventory_item.id_product and inventory_item.type =' .InventoryItem::$TYPE_PRODUCT);
		$query->leftJoin("inventory_group", 'inventory_group.id_inventory_group = inventory_item.id_product and inventory_item.type =' .InventoryItem::$TYPE_INVENTORY_GROUP);
		$query->andWhere(['id_inventory' => $id_inventory]);
		$query->orderBy("name");
		$result = $query->all();

		$currentItemIndex = null;
		$size = count($result);
		for ( $i = 0; $i < $size; $i++ ){
			$item = $result[$i];
            $id = $item['inventory_item_id_inventory'];
			if ( $id == $currentItemId ){
				$currentItemIndex = $i;
				break;
			}
		}

		if ( isset( $currentItemIndex ) ){
			$next = ($currentItemIndex +1 );
			if ($size > $next){
				return  $result[$next]['inventory_item_id_inventory'];
			}
		}

        return null;
	}

    /**
     * Recalculate the next values:
     *
                netto készlet érték
                leltárhiány db
                leltárhiány összeg
     *
     * @param boolean $insert whether this method called while inserting a record.
     * If false, it means the method is called while updating a record.
     * @return boolean whether the insertion or updating should continue.
     * If false, the insertion or updating will be cancelled.
     */
    public function beforeSave($insert)
    {
        $result =  parent::beforeSave($insert);
        if ( $result ){
            if ( !isset($this->id_inventory_group) ){
                $count = 0;
                $purchase_price_net = 0;
                $count_prev = 0;
                $count_in = 0;
                $count_sold = 0;

                $price = 0;
                if (isset($price) && is_numeric($price)){
                    $price = $this->price_brutto;
                }

                if ( isset($this->count)){
                    $count = $this->count;
                }

                if ( isset($this->purchase_price_net)){
                    $purchase_price_net = $this->purchase_price_net;
                }

                if ( isset($this->count_prev) ){
                    $count_prev = $this->count_prev;
                }

                if ( isset($this->count_in)){
                    $count_in = $this->count_in;
                }

                if ( isset($this->count_sold)){
                    $count_sold = $this->count_sold;
                }

                //netto készlet érték
                $this->net_stock_money = $count * $purchase_price_net;
                //leltárhiány db
                $this->stock_missing_count  = $this->count -  ($count_prev + $count_in - $count_sold) ;
                //leltárhiány összeg
                $this->stock_missing_money  = $price * $this->stock_missing_count;
            }
        }
        return $result;
    }


    public function afterSave($insert, $changedAttributes){
    	if ( !$insert ){
//     		if ( $this->type == 'product'){
// 	    		$product = $this->product;
// 	    		$product->stock = $this->count;
// 	    		if ( !$product->save(false) ){
// 	    			\Yii::error("Failed to save product stock");
// 	    			throw new \Exception("A leltár elem mentése nem sikerült");
// 	    		}
//     		}
    	}
    }
    
}
