<?php

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

return new class extends Migration
{
    public function up(): void
    {
        // Extend enum status: draft -> review -> issued -> cancelled
        DB::statement("ALTER TABLE invoices MODIFY status ENUM('draft','review','issued','cancelled') NOT NULL DEFAULT 'draft'");

        Schema::table('invoices', function (Blueprint $table) {
            $table->timestamp('review_submitted_at')->nullable()->after('issued_at');
            $table->foreignId('review_submitted_by')->nullable()->after('review_submitted_at')->constrained('users')->nullOnDelete();
            $table->timestamp('review_approved_at')->nullable()->after('review_submitted_by');
            $table->foreignId('review_approved_by')->nullable()->after('review_approved_at')->constrained('users')->nullOnDelete();

            $table->timestamp('due_reminder_sent_at')->nullable()->after('paid_at');
            $table->timestamp('overdue_reminder_sent_at')->nullable()->after('due_reminder_sent_at');

            $table->decimal('credited_total', 15, 2)->default(0)->after('amount_paid');
        });
    }

    public function down(): void
    {
        Schema::table('invoices', function (Blueprint $table) {
            $table->dropConstrainedForeignId('review_approved_by');
            $table->dropConstrainedForeignId('review_submitted_by');
            $table->dropColumn([
                'review_submitted_at',
                'review_approved_at',
                'due_reminder_sent_at',
                'overdue_reminder_sent_at',
                'credited_total',
            ]);
        });

        DB::statement("ALTER TABLE invoices MODIFY status ENUM('draft','issued','cancelled') NOT NULL DEFAULT 'draft'");
    }
};
