<?php

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

/**
 * Holds the ORIGINAL (pre-landed) purchase-line and product-variation costs for a parent,
 * captured the first time landed cost is applied. Existence of rows for a parent means
 * "landed cost applied"; rollback restores from here and deletes the rows.
 */
class CreateLcCostSnapshotsTable extends Migration
{
    public function up()
    {
        if (Schema::hasTable('lc_cost_snapshots')) {
            return;
        }

        Schema::create('lc_cost_snapshots', function (Blueprint $table) {
            $table->increments('id');
            $table->string('parent_type', 30);
            $table->unsignedInteger('parent_id');
            $table->unsignedInteger('purchase_line_id');
            $table->unsignedBigInteger('variation_id')->nullable();

            // original purchase_lines cost
            $table->decimal('orig_purchase_price', 22, 4)->default(0);
            $table->decimal('orig_purchase_price_inc_tax', 22, 4)->default(0);
            $table->decimal('orig_item_tax', 22, 4)->default(0);
            $table->decimal('orig_pp_without_discount', 22, 4)->default(0);

            // original variations cost (nullable — line may have no variation)
            $table->decimal('orig_var_default_purchase_price', 22, 4)->nullable();
            $table->decimal('orig_var_dpp_inc_tax', 22, 4)->nullable();
            $table->decimal('orig_var_profit_percent', 22, 4)->nullable();

            $table->dateTime('applied_at')->nullable();
            $table->unsignedInteger('applied_by')->nullable();
            $table->timestamps();

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

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

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