<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('maintenance_logs', function (Blueprint $table) {
            $table->unsignedBigInteger('invoice_id')->nullable()->after('technician_id');
        });

        // Add foreign key constraint if maintenance_invoices table exists
        if (Schema::hasTable('maintenance_invoices')) {
            Schema::table('maintenance_logs', function (Blueprint $table) {
                $table->foreign('invoice_id')->references('id')->on('maintenance_invoices');
            });
        }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        if (Schema::hasTable('maintenance_logs')) {
            Schema::table('maintenance_logs', function (Blueprint $table) {
                if (Schema::hasTable('maintenance_invoices')) {
                    $table->dropForeign(['invoice_id']);
                }
                $table->dropColumn('invoice_id');
            });
        }
    }
};
