<?php

use yii\db\Schema;
use yii\db\Migration;

class m170104_063931_alter__table__inventory__item__add__tax__net_stock_valu__sotck_missing extends Migration
{
    public function up()
    {
        $this->addColumn("inventory_item", "tax", "int default 0");
        $this->addColumn("inventory_item", "net_stock_money", "int default 0");
        $this->addColumn("inventory_item", "purchase_price_net", "int default 0");
        $this->addColumn("inventory_item", "stock_missing_money", "int default 0");
        $this->addColumn("inventory_item", "stock_missing_count", "int default 0");


        $sql = "UPDATE inventory_item AS i
            INNER JOIN product AS p ON p.id_product = i.id_product
            SET 
              i.tax = p.tax,
              i.purchase_price_net = p.purchase_net_price,
              i.net_stock_money  = i.count * p.purchase_net_price,
              i.stock_missing_count = (coalesce(i.count,0) - ( coalesce(i.count_prev,0) + coalesce(i.count_in,0) - coalesce(i.count_sold,0) )),
              i.stock_missing_money = i.price_brutto * (coalesce(i.count,0) - ( coalesce(i.count_prev,0) + coalesce(i.count_in,0) - coalesce(i.count_sold,0) ))
            WHERE  i.id_inventory_group is null ";


        $this->execute($sql);


    }

    public function down()
    {
        echo "m170104_063931_alter__table__inventory__item__add__tax__net_stock_valu__sotck_missing cannot be reverted.\n";

        return false;
    }

    /*
    // Use safeUp/safeDown to run migration code within a transaction
    public function safeUp()
    {
    }

    public function safeDown()
    {
    }
    */
}
