<?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::table('orders', function (Blueprint $table) {
            $table->enum('payment_type', ['cash', 'credit', 'partial'])->default('cash')->after('payment_method');
            $table->decimal('credit_amount', 12, 2)->default(0)->after('payment_type');
            $table->decimal('paid_amount', 12, 2)->default(0)->change();
            $table->date('due_date')->nullable()->after('credit_amount');
            $table->enum('credit_status', ['pending', 'partial', 'paid', 'overdue'])->nullable()->after('due_date');
        });

        Schema::create('credit_payments', function (Blueprint $table) {
            $table->id();
            $table->foreignId('order_id')->constrained()->onDelete('cascade');
            $table->foreignId('customer_id')->constrained()->onDelete('cascade');
            $table->decimal('amount', 12, 2);
            $table->decimal('balance_before', 12, 2)->default(0);
            $table->decimal('balance_after', 12, 2)->default(0);
            $table->string('payment_method')->default('cash');
            $table->string('reference_number')->nullable();
            $table->text('notes')->nullable();
            $table->foreignId('user_id')->constrained()->onDelete('cascade');
            $table->timestamps();
        });
    }

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

        Schema::table('orders', function (Blueprint $table) {
            $table->dropColumn(['payment_type', 'credit_amount', 'due_date', 'credit_status']);
        });
    }
};
