<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePrProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        if (Schema::hasTable('pr_products')) { return; }
        Schema::create('pr_products', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('business_id')->unsigned();
            $table->foreign('business_id')->references('id')->on('business')->onDelete('cascade');
            $table->bigInteger('pr_request_id')->unsigned();
            $table->foreign('pr_request_id')->references('id')->on('pr_requests')->onDelete('cascade');
            $table->integer('product_id')->unsigned();
            $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
            $table->integer('variation_id')->unsigned();
            $table->foreign('variation_id')->references('id')->on('variations')->onDelete('cascade');
            $table->decimal('current_stock', 22, 4)->default(0);
            $table->decimal('required_quantity', 22, 4)->default(0);
            $table->decimal('covered_qty', 22, 4)->default(0);
            $table->decimal('pending_purchase_qty', 22, 4)->default(0);
            $table->decimal('avg_unit_cost', 22, 4)->default(0);
            $table->decimal('last_purchase_price', 22, 4)->default(0);
            $table->decimal('selling_price', 22, 4)->default(0);
            $table->text('notes')->nullable();
            $table->boolean('has_previous_purchase')->default(true);
            $table->timestamps();
            $table->softDeletes();

            $table->index(['pr_request_id', 'product_id']);
            $table->index('variation_id');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('pr_products');
    }
}
