<?php

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

class CreateLcLandedCostsTable extends Migration
{
    /**
     * Generic landed-cost storage for parents that do not have their own landed-cost
     * column (i.e. core Purchases / Purchase Orders). The PurchaseRequisition driver
     * keeps writing to pr_supplier_products and does not use this table.
     */
    public function up()
    {
        if (Schema::hasTable('lc_landed_costs')) {
            return;
        }

        Schema::create('lc_landed_costs', function (Blueprint $table) {
            $table->increments('id');
            $table->string('parent_type', 30);
            $table->unsignedInteger('parent_id');
            $table->unsignedInteger('purchase_line_id');
            $table->decimal('base_unit_price', 22, 4)->default(0);      // supplier-currency unit price
            $table->decimal('landed_unit_cost', 22, 4)->default(0);     // supplier-currency landed cost
            $table->decimal('landed_unit_cost_base', 22, 4)->default(0);// base-currency landed cost
            $table->timestamps();

            $table->unique(['parent_type', 'parent_id', 'purchase_line_id'], 'lc_landed_costs_parent_line_unique');

            $table->foreign('purchase_line_id')
                  ->references('id')->on('purchase_lines')
                  ->onDelete('cascade');
        });
    }

    public function down()
    {
        Schema::dropIfExists('lc_landed_costs');
    }
}
