<?php

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

/**
 * Managed payment methods / accounts (e.g. "JazzCash 0333-0000330"). Each can be
 * enabled/disabled so a closed account is retained for history but no longer
 * offered when collecting new payments, and can map to a ledger account so
 * collections post to the right place in accounting.
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::create('payment_methods', function (Blueprint $table) {
            $table->id();
            $table->foreignId('branch_id')->constrained('branches')->cascadeOnUpdate()->restrictOnDelete();
            $table->string('name');                  // display name, e.g. "JazzCash Main"
            $table->string('channel', 30)->default('cash'); // cash|bank|easypaisa|jazzcash|cheque|other
            $table->string('account_number')->nullable();
            $table->string('account_title')->nullable();
            $table->foreignId('account_id')->nullable()->constrained('accounts')->nullOnDelete(); // ledger mapping
            $table->boolean('is_active')->default(true)->index();
            $table->unsignedInteger('sort_order')->default(0);
            $table->timestamps();
        });

        Schema::table('fee_payments', function (Blueprint $table) {
            $table->foreignId('payment_method_id')->nullable()->after('method')
                ->constrained('payment_methods')->nullOnDelete();
        });
    }

    public function down(): void
    {
        Schema::table('fee_payments', function (Blueprint $table) {
            $table->dropConstrainedForeignId('payment_method_id');
        });
        Schema::dropIfExists('payment_methods');
    }
};
