<?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
    {
        // Check if table exists before modifying
        if (Schema::hasTable('t_item_requests')) {
            Schema::table('t_item_requests', function (Blueprint $table) {
                // Add csv_generated_at column if not exists
                if (!Schema::hasColumn('t_item_requests', 'csv_generated_at')) {
                    $table->timestamp('csv_generated_at')->nullable()->after('updated_at');
                }
                
                // Add csv_generated_by column if not exists
                if (!Schema::hasColumn('t_item_requests', 'csv_generated_by')) {
                    $table->unsignedBigInteger('csv_generated_by')->nullable()->after('csv_generated_at');
                    $table->foreign('csv_generated_by')->references('id')->on('users')->onDelete('set null');
                }
            });
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        if (Schema::hasTable('t_item_requests')) {
            Schema::table('t_item_requests', function (Blueprint $table) {
                if (Schema::hasColumn('t_item_requests', 'csv_generated_by')) {
                    $table->dropForeign(['csv_generated_by']);
                    $table->dropColumn('csv_generated_by');
                }
                
                if (Schema::hasColumn('t_item_requests', 'csv_generated_at')) {
                    $table->dropColumn('csv_generated_at');
                }
            });
        }
    }
};
