<?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::table('purchases', function (Blueprint $table) {
            // Hanya tambahkan status jika belum ada
            if (!Schema::hasColumn('purchases', 'status')) {
                $table->enum('status', ['pending', 'approved', 'rejected'])->default('pending')->after('notes');
            }
            
            // Hanya tambahkan supplier_id jika belum ada
            if (!Schema::hasColumn('purchases', 'supplier_id')) {
                $table->unsignedBigInteger('supplier_id')->nullable()->after('supplier_name');
            }
            
            // Hanya tambahkan approved_at jika belum ada
            if (!Schema::hasColumn('purchases', 'approved_at')) {
                $table->timestamp('approved_at')->nullable()->after('status');
            }
            
            // Hanya tambahkan approved_by jika belum ada
            if (!Schema::hasColumn('purchases', 'approved_by')) {
                $table->unsignedBigInteger('approved_by')->nullable()->after('approved_at');
            }
            
            // Hanya tambahkan supervisor_feedback jika belum ada
            if (!Schema::hasColumn('purchases', 'supervisor_feedback')) {
                $table->text('supervisor_feedback')->nullable()->after('approved_by');
            }
        });

        // Tambahkan foreign keys dengan try-catch untuk menghindari error jika sudah ada
        try {
            Schema::table('purchases', function (Blueprint $table) {
                if (Schema::hasColumn('purchases', 'supplier_id')) {
                    $table->foreign('supplier_id')->references('id')->on('suppliers')->onDelete('set null');
                }
            });
        } catch (\Exception $e) {
            // Foreign key mungkin sudah ada, abaikan error
        }

        try {
            Schema::table('purchases', function (Blueprint $table) {
                if (Schema::hasColumn('purchases', 'approved_by')) {
                    $table->foreign('approved_by')->references('id')->on('users')->onDelete('set null');
                }
            });
        } catch (\Exception $e) {
            // Foreign key mungkin sudah ada, abaikan error
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('purchases', function (Blueprint $table) {
            $table->dropForeign(['supplier_id']);
            $table->dropForeign(['approved_by']);
            $table->dropColumn(['status', 'supplier_id', 'approved_at', 'approved_by', 'supervisor_feedback']);
        });
    }
};