<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('profit_distribution_lines', function (Blueprint $table) {
            $table->id();
            $table->foreignId('profit_distribution_id')->constrained()->cascadeOnDelete();
            $table->foreignId('partner_id')->constrained()->cascadeOnDelete();

            // Snapshot of ownership at distribution time
            $table->decimal('ownership_percentage', 8, 4);
            $table->decimal('capital_at_distribution', 15, 2);

            // Calculated amounts
            $table->decimal('gross_amount', 15, 2);
            $table->decimal('retained_amount', 15, 2)->default('0.00');
            $table->decimal('net_amount', 15, 2);

            // Payment tracking
            $table->boolean('is_paid')->default(false);
            $table->date('paid_at')->nullable();
            $table->string('payment_method')->nullable();
            $table->string('payment_reference')->nullable();

            // Link to withdrawal record
            $table->foreignId('withdrawal_id')->nullable()
                ->constrained('partner_withdrawals')->nullOnDelete();

            $table->timestamps();

            // Indexes
            $table->unique(['profit_distribution_id', 'partner_id'], 'pdl_distribution_partner_unique');
        });
    }

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