<?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('payments', function (Blueprint $table) {
            $table->id();
            $table->uuid('uuid')->unique();
            $table->foreignId('academy_id')->constrained()->cascadeOnDelete();
            $table->foreignId('invoice_id')->nullable()->constrained()->nullOnDelete();
            $table->string('reference', 50)->nullable();
            $table->string('direction', 10);
            $table->string('method', 20);
            $table->string('status', 20)->default('pending');

            $table->nullableMorphs('payer');

            $table->bigInteger('amount')->default(0);
            $table->string('currency', 3)->default('EGP');

            $table->date('payment_date');
            $table->timestamp('confirmed_at')->nullable();
            $table->timestamp('failed_at')->nullable();

            $table->text('notes')->nullable();
            $table->jsonb('gateway_data')->default('{}');
            $table->jsonb('metadata')->default('{}');

            $table->foreignId('received_by')->nullable()->constrained('users')->nullOnDelete();
            $table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();

            $table->timestamps();
            $table->softDeletes();

            $table->index(['academy_id', 'status']);
            $table->index(['academy_id', 'direction']);
            $table->index(['academy_id', 'payment_date']);
            $table->index('invoice_id');
        });

        DB::statement("ALTER TABLE payments ADD CONSTRAINT payments_direction_check CHECK (direction IN ('inbound', 'outbound'))");
        DB::statement("ALTER TABLE payments ADD CONSTRAINT payments_method_check CHECK (method IN ('cash', 'card', 'bank_transfer', 'wallet', 'online', 'cheque', 'other'))");
        DB::statement("ALTER TABLE payments ADD CONSTRAINT payments_status_check CHECK (status IN ('pending', 'confirmed', 'failed', 'cancelled', 'refunded'))");
    }

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