<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('debts', function (Blueprint $table) {
            $table->id();
            $table->string('debt_number')->unique();
            $table->foreignId('customer_id')->constrained()->onDelete('cascade');
            $table->foreignId('sale_id')->constrained()->onDelete('cascade');
            $table->decimal('total_debt_amount', 15, 2)->default(0); // Total debt amount from the sale
            $table->decimal('paid_amount', 15, 2)->default(0); // Total amount paid so far
            $table->decimal('remaining_amount', 15, 2)->default(0); // Remaining debt amount
            $table->enum('status', ['pending', 'partial', 'paid'])->default('pending');
            $table->date('due_date')->nullable(); // Optional due date for the debt
            $table->text('notes')->nullable(); // Additional notes about the debt
            $table->timestamps();

            // Indexes for better performance
            $table->index(['customer_id', 'status']);
            $table->index(['status', 'due_date']);
            $table->index('created_at');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('debts');
    }
};