<?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_sweep_rules', function (Blueprint $table) {
            $table->id();
            $table->foreignId('subsidiary_id')->constrained('companies')->onDelete('cascade');
            $table->foreignId('parent_company_id')->constrained('companies')->onDelete('cascade');
            $table->enum('sweep_type', ['percentage', 'threshold', 'fixed_amount'])->default('percentage');
            $table->decimal('sweep_percentage', 5, 2)->nullable();
            $table->decimal('threshold_amount', 15, 2)->nullable();
            $table->decimal('fixed_amount', 15, 2)->nullable();
            $table->enum('frequency', ['daily', 'weekly', 'monthly', 'quarterly', 'annual'])->default('monthly');
            $table->integer('day_of_execution')->nullable();
            $table->boolean('is_active')->default(true);
            $table->date('effective_from');
            $table->date('effective_to')->nullable();
            $table->timestamps();
            
            $table->index(['subsidiary_id', 'is_active']);
        });

        Schema::create('profit_sweep_transactions', function (Blueprint $table) {
            $table->id();
            $table->foreignId('sweep_rule_id')->constrained('profit_sweep_rules')->onDelete('cascade');
            $table->string('transaction_number')->unique();
            $table->foreignId('from_company_id')->constrained('companies')->onDelete('restrict');
            $table->foreignId('to_company_id')->constrained('companies')->onDelete('restrict');
            $table->date('sweep_date');
            $table->decimal('calculated_amount', 15, 2);
            $table->decimal('actual_amount', 15, 2);
            $table->decimal('subsidiary_profit', 15, 2)->nullable();
            $table->enum('status', ['pending', 'processed', 'failed', 'reversed'])->default('pending');
            $table->text('notes')->nullable();
            $table->foreignId('processed_by')->nullable()->constrained('users');
            $table->timestamp('processed_at')->nullable();
            $table->timestamps();
            
            $table->index(['from_company_id', 'sweep_date']);
        });
    }

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