<?php

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

return new class extends Migration
{
    public function up()
    {
        Schema::create('installments', function (Blueprint $table) {
            $table->id();
            $table->foreignId('sale_id')->constrained()->onDelete('cascade');
            $table->integer('installment_no');
            $table->decimal('amount', 12, 2);
            $table->decimal('paid_amount', 12, 2)->default(0);
            $table->decimal('due_amount', 12, 2);
            $table->date('due_date');
            $table->date('payment_date')->nullable();
            $table->enum('status', ['pending', 'paid', 'overdue', 'partial', 'cancelled'])->default('pending');
            $table->decimal('late_fee', 12, 2)->default(0);
            $table->integer('grace_period_days')->default(7);
            $table->text('notes')->nullable();
            $table->timestamps();
            
            $table->unique(['sale_id', 'installment_no']);
            $table->index('sale_id');
            $table->index('status');
            $table->index('due_date');
            $table->index('payment_date');
        });
    }

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