<?php

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

class CreateLcExpensesTable extends Migration
{
    public function up()
    {
        if (Schema::hasTable('lc_expenses')) {
            return;
        }

        Schema::create('lc_expenses', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('business_id')->nullable();

            // Polymorphic parent: 'pr_share' | 'purchase' | 'purchase_order'
            $table->string('parent_type', 30);
            $table->unsignedInteger('parent_id');

            $table->string('name', 100);
            $table->enum('expense_type', ['shipping', 'customs', 'insurance', 'handling', 'freight', 'other'])
                  ->default('other');
            $table->decimal('amount', 15, 4);

            // Currency is interpreted by the parent's driver (pr_currencies for PR shares,
            // business currency for core purchases) — no hard FK so the module stays standalone.
            $table->unsignedInteger('currency_id')->nullable();
            $table->decimal('rate_to_base', 15, 6)->default(1);
            $table->decimal('base_amount', 15, 4);

            $table->enum('distribution_method', ['equal_qty', 'equal_value', 'equal_lines', 'custom'])
                  ->default('equal_value');
            $table->text('notes')->nullable();
            $table->unsignedInteger('created_by')->nullable();
            $table->timestamps();

            $table->index(['parent_type', 'parent_id']);
        });
    }

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