<?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('payment_plans', function (Blueprint $table) {
            $table->id();
            $table->uuid('uuid')->unique();
            $table->foreignId('academy_id')->constrained()->cascadeOnDelete();
            $table->foreignId('invoice_id')->constrained()->cascadeOnDelete();
            $table->string('status', 20)->default('active');
            $table->integer('total_installments');
            $table->integer('paid_installments')->default(0);
            $table->bigInteger('installment_amount');
            $table->string('frequency', 20)->default('monthly');
            $table->date('start_date');
            $table->date('next_due_date')->nullable();
            $table->text('notes')->nullable();
            $table->timestamps();

            $table->index(['academy_id', 'status']);
            $table->index('next_due_date');
        });

        DB::statement("ALTER TABLE payment_plans ADD CONSTRAINT payment_plans_status_check CHECK (status IN ('active', 'completed', 'defaulted', 'cancelled'))");
        DB::statement("ALTER TABLE payment_plans ADD CONSTRAINT payment_plans_frequency_check CHECK (frequency IN ('weekly', 'biweekly', 'monthly', 'quarterly'))");

        Schema::create('installments', function (Blueprint $table) {
            $table->id();
            $table->foreignId('payment_plan_id')->constrained()->cascadeOnDelete();
            $table->foreignId('payment_id')->nullable()->constrained()->nullOnDelete();
            $table->integer('sequence');
            $table->bigInteger('amount');
            $table->date('due_date');
            $table->string('status', 20)->default('pending');
            $table->timestamp('paid_at')->nullable();
            $table->timestamps();

            $table->index(['payment_plan_id', 'sequence']);
            $table->index('due_date');
        });

        DB::statement("ALTER TABLE installments ADD CONSTRAINT installments_status_check CHECK (status IN ('pending', 'paid', 'overdue', 'cancelled', 'waived'))");
    }

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