<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use App\Modules\Stock\StockItem;
use App\Modules\Stock\Stock;
use App\Modules\Bookings\Part;

class MergeStockTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		// Add columns to stock table only if they do not exist
		$columns = collect(DB::select('SHOW COLUMNS FROM stock'))->pluck('Field')->toArray();
		Schema::table('stock', function(Blueprint $table) use ($columns) {
			if (!in_array('margin', $columns)) {
				$table->float('margin')->after('type')->default(0);
			}
			if (!in_array('business_margin', $columns)) {
				$table->float('business_margin')->after('margin')->default(0);
			}
			if (!in_array('cost', $columns)) {
				$table->float('cost')->after('business_margin')->default(0);
			}
			if (!in_array('retail', $columns)) {
				$table->float('retail')->after('cost')->default(0);
			}
			if (!in_array('quantity', $columns)) {
				$table->integer('quantity')->after('retail')->default(0);
			}
			if (!in_array('order_id', $columns)) {
				$table->integer('order_id')->after('quantity')->nullable();
			}
			if (!in_array('deleted_at', $columns)) {
				$table->timestamp('deleted_at')->nullable()->after('updated_at');
			}
		});

		// Only alter parts table if stock_item_id exists
		$partsColumns = collect(DB::select('SHOW COLUMNS FROM parts'))->pluck('Field')->toArray();
		if (in_array('stock_item_id', $partsColumns)) {
			DB::statement('ALTER TABLE  `parts` CHANGE  `stock_item_id`  `stock_id` INT( 10 ) UNSIGNED NOT NULL');
		}

		// Migrate data from stock_items table
		$items = StockItem::all();

		foreach ($items as $item) {
			$stock = Stock::find($item->stock_id);
			$stock->fill($item->toArray());
			$stock->save();
		}

		// Migrate parts data
		$parts = Part::all();
		foreach ($parts as $part) {
			$stock_item = StockItem::find($part->stock_id);
			$part->stock_id = $stock_item->stock_id;
			$part->save();
		}
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		Schema::table('stock', function(Blueprint $table)
		{
			$table->dropColumn('margin');
			$table->dropColumn('business_margin');
			$table->dropColumn('cost');
			$table->dropColumn('retail');
			$table->dropColumn('quantity');
			$table->dropColumn('order_id');
		});

		DB::statement('ALTER TABLE  `parts` CHANGE  `stock_id`  `stock_item_id` INT( 10 ) UNSIGNED NOT NULL');
	}

}