<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('financial_items', function (Blueprint $table) {
            // =====================================================
            // Behavior Policy Flags
            // These control what the system does with each item.
            // Admins can override these per item in the Filament UI.
            // =====================================================

            // Payment behavior
            $table->boolean('allows_advance_payment')->default(true)
                ->comment('Whether members can prepay future periods for this item')
                ->after('is_active');

            $table->boolean('allows_partial_payment')->default(false)
                ->comment('Whether members can pay less than the full amount')
                ->after('allows_advance_payment');

            // Assignment behavior
            $table->boolean('is_optional')->default(false)
                ->comment('Optional items (e.g., donations) do not affect membership standing')
                ->after('allows_partial_payment');

            $table->boolean('requires_manual_assignment')->default(false)
                ->comment('If true, admin must manually assign to members instead of auto-generating')
                ->after('is_optional');

            // Category — purely for UI grouping, filtering, and display
            $table->string('category', 50)->nullable()
                ->comment('Presentational category: dues, levy, fine, fee, donation, contribution, special_assessment')
                ->after('type');

            // Advance payment cap per item (overrides association-level setting)
            $table->unsignedInteger('max_advance_periods')->nullable()
                ->comment('Per-item cap on advance periods. Null = use association default.')
                ->after('requires_manual_assignment');
        });

        // Seed `category` from existing `type` column so nothing breaks
        DB::statement("UPDATE financial_items SET category = type");

        // Set smart behavior defaults based on existing type
        // Dues: recurring, advance OK, no partial, mandatory
        DB::table('financial_items')->where('type', 'dues')->update([
            'allows_advance_payment' => true,
            'allows_partial_payment' => false,
            'is_optional' => false,
            'requires_manual_assignment' => false,
        ]);

        DB::table('financial_items')->where('type', 'membership_subscription')->update([
            'allows_advance_payment' => true,
            'allows_partial_payment' => false,
            'is_optional' => false,
            'requires_manual_assignment' => false,
            'category' => 'dues',
        ]);

        // Donation: no advance, partial OK, optional, manual
        DB::table('financial_items')->where('type', 'donation')->update([
            'allows_advance_payment' => false,
            'allows_partial_payment' => true,
            'is_optional' => true,
            'requires_manual_assignment' => true,
        ]);

        // Fine: no advance, partial OK, mandatory, manual
        DB::table('financial_items')->where('type', 'fine')->update([
            'allows_advance_payment' => false,
            'allows_partial_payment' => true,
            'is_optional' => false,
            'requires_manual_assignment' => true,
        ]);

        // Levy: no advance by default, no partial, mandatory
        DB::table('financial_items')->where('type', 'levy')->update([
            'allows_advance_payment' => false,
            'allows_partial_payment' => false,
            'is_optional' => false,
            'requires_manual_assignment' => false,
        ]);

        // Fee: no advance by default, partial OK, mandatory
        DB::table('financial_items')->where('type', 'fee')->update([
            'allows_advance_payment' => false,
            'allows_partial_payment' => true,
            'is_optional' => false,
            'requires_manual_assignment' => false,
        ]);

        // =====================================================
        // Association-level financial policy settings
        // =====================================================
        Schema::table('associations', function (Blueprint $table) {
            // Partial payment policy
            $table->boolean('allow_partial_payments')->default(false)
                ->comment('Global toggle: allow partial payments across the association')
                ->after('auto_apply_late_fees');

            // Late fee compounding model
            // (late_fee_compound already exists from previous migration, skip if present)

            // Default behavior presets for newly created items
            $table->json('financial_item_defaults')->nullable()
                ->comment('JSON: default behavior flags when admin creates a new financial item, keyed by type')
                ->after('allow_partial_payments');
        });
    }

    public function down(): void
    {
        Schema::table('financial_items', function (Blueprint $table) {
            $table->dropColumn([
                'allows_advance_payment',
                'allows_partial_payment',
                'is_optional',
                'requires_manual_assignment',
                'category',
                'max_advance_periods',
            ]);
        });

        Schema::table('associations', function (Blueprint $table) {
            $table->dropColumn([
                'allow_partial_payments',
                'financial_item_defaults',
            ]);
        });
    }
};
