<?php

declare(strict_types=1);

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

/**
 * Add operational credit settings to company_financial_settings.
 *
 * These settings allow Company Admins to configure:
 * - Credit amount limits and default values
 * - Interest rate constraints
 * - Payment policies
 * - Simplified input mode for PWA
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::table('company_financial_settings', function (Blueprint $table) {
            // ═══════════════════════════════════════════════════════════════════════
            // CREDIT AMOUNT CONSTRAINTS
            // ═══════════════════════════════════════════════════════════════════════
            $table->decimal('min_credit_amount', 15, 2)->default(100000.00)->after('track_principal_interest_separately')
                ->comment('Minimum credit amount allowed');

            $table->decimal('max_credit_amount', 15, 2)->default(50000000.00)->after('min_credit_amount')
                ->comment('Maximum credit amount allowed');

            $table->decimal('default_credit_amount', 15, 2)->nullable()->after('max_credit_amount')
                ->comment('Default amount pre-filled in credit form');

            // ═══════════════════════════════════════════════════════════════════════
            // INTEREST RATE CONSTRAINTS
            // ═══════════════════════════════════════════════════════════════════════
            $table->decimal('min_interest_rate', 5, 2)->default(0.00)->after('default_credit_amount')
                ->comment('Minimum interest rate allowed (%)');

            $table->decimal('max_interest_rate', 5, 2)->default(30.00)->after('min_interest_rate')
                ->comment('Maximum interest rate allowed (%)');

            $table->decimal('default_interest_rate', 5, 2)->nullable()->after('max_interest_rate')
                ->comment('Default interest rate pre-filled');

            // ═══════════════════════════════════════════════════════════════════════
            // INSTALLMENT CONSTRAINTS
            // ═══════════════════════════════════════════════════════════════════════
            $table->unsignedSmallInteger('min_installments')->default(1)->after('default_interest_rate')
                ->comment('Minimum number of installments');

            $table->unsignedSmallInteger('max_installments')->default(60)->after('min_installments')
                ->comment('Maximum number of installments');

            $table->unsignedSmallInteger('default_installments')->nullable()->after('max_installments')
                ->comment('Default number of installments');

            // ═══════════════════════════════════════════════════════════════════════
            // PERIODICITY & PAYMENT SETTINGS
            // ═══════════════════════════════════════════════════════════════════════
            $table->json('allowed_periodicities')->nullable()->after('default_installments')
                ->comment('Allowed periodicities: ["daily", "weekly", "biweekly", "monthly"]');

            $table->string('default_periodicity', 20)->default('monthly')->after('allowed_periodicities')
                ->comment('Default periodicity for new credits');

            $table->unsignedTinyInteger('default_grace_days')->default(0)->after('default_periodicity')
                ->comment('Default grace days before late fees');

            // ═══════════════════════════════════════════════════════════════════════
            // LATE PAYMENT POLICIES
            // ═══════════════════════════════════════════════════════════════════════
            $table->decimal('late_fee_percentage', 5, 2)->default(0.00)->after('default_grace_days')
                ->comment('Late fee as percentage of installment');

            $table->decimal('late_fee_fixed', 15, 2)->default(0.00)->after('late_fee_percentage')
                ->comment('Fixed late fee amount per late installment');

            $table->unsignedSmallInteger('days_until_delayed')->default(1)->after('late_fee_fixed')
                ->comment('Days after due date to mark credit as delayed');

            $table->unsignedSmallInteger('days_until_default')->default(90)->after('days_until_delayed')
                ->comment('Days after due date to mark credit as defaulted');

            // ═══════════════════════════════════════════════════════════════════════
            // PAYMENT BEHAVIOR
            // ═══════════════════════════════════════════════════════════════════════
            $table->boolean('allow_partial_payments')->default(true)->after('days_until_default')
                ->comment('Allow payments smaller than installment amount');

            $table->boolean('allow_overpayments')->default(true)->after('allow_partial_payments')
                ->comment('Allow payments larger than remaining balance');

            $table->boolean('auto_close_on_full_payment')->default(true)->after('allow_overpayments')
                ->comment('Automatically close credit when fully paid');

            $table->boolean('apply_payment_to_oldest_first')->default(true)->after('auto_close_on_full_payment')
                ->comment('Apply payments to oldest unpaid installments first');

            // ═══════════════════════════════════════════════════════════════════════
            // SIMPLIFIED INPUT MODE (PWA)
            // ═══════════════════════════════════════════════════════════════════════
            $table->boolean('simplified_input_enabled')->default(false)->after('apply_payment_to_oldest_first')
                ->comment('Enable simplified input (omit zeros) in PWA');

            $table->unsignedInteger('simplified_input_multiplier')->default(1000)->after('simplified_input_enabled')
                ->comment('Multiplier for simplified input: 1000 = ×1,000');

            $table->json('simplified_input_contexts')->nullable()->after('simplified_input_multiplier')
                ->comment('Contexts where simplified input applies: ["credit_create", "payment_create"]');

            $table->boolean('simplified_input_require_confirm')->default(true)->after('simplified_input_contexts')
                ->comment('Require confirmation checkbox for simplified input');

            // ═══════════════════════════════════════════════════════════════════════
            // UI PREFERENCES
            // ═══════════════════════════════════════════════════════════════════════
            $table->boolean('show_client_balance_on_payment')->default(true)->after('simplified_input_require_confirm')
                ->comment('Show client total balance when creating payment');

            $table->boolean('require_payment_notes')->default(false)->after('show_client_balance_on_payment')
                ->comment('Require notes field when creating payment');

            $table->boolean('show_installment_breakdown')->default(true)->after('require_payment_notes')
                ->comment('Show principal/interest breakdown in installments');
        });

        // Update existing records with default allowed_periodicities
        DB::table('company_financial_settings')
            ->whereNull('allowed_periodicities')
            ->update([
                'allowed_periodicities' => json_encode(['daily', 'weekly', 'biweekly', 'monthly']),
                'simplified_input_contexts' => json_encode(['pwa_credit_create', 'pwa_payment_create']),
            ]);
    }

    public function down(): void
    {
        Schema::table('company_financial_settings', function (Blueprint $table) {
            $table->dropColumn([
                // Credit constraints
                'min_credit_amount',
                'max_credit_amount',
                'default_credit_amount',
                'min_interest_rate',
                'max_interest_rate',
                'default_interest_rate',
                'min_installments',
                'max_installments',
                'default_installments',
                // Periodicity
                'allowed_periodicities',
                'default_periodicity',
                'default_grace_days',
                // Late payment
                'late_fee_percentage',
                'late_fee_fixed',
                'days_until_delayed',
                'days_until_default',
                // Payment behavior
                'allow_partial_payments',
                'allow_overpayments',
                'auto_close_on_full_payment',
                'apply_payment_to_oldest_first',
                // Simplified input
                'simplified_input_enabled',
                'simplified_input_multiplier',
                'simplified_input_contexts',
                'simplified_input_require_confirm',
                // UI
                'show_client_balance_on_payment',
                'require_payment_notes',
                'show_installment_breakdown',
            ]);
        });
    }
};
