<?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
        if (Schema::hasTable('m_raw_materials')) {
            Schema::table('m_raw_materials', function (Blueprint $table) {
                // Drop conversion_factor column if exists (wrong column)
                if (Schema::hasColumn('m_raw_materials', 'conversion_factor')) {
                    $table->dropColumn('conversion_factor');
                }
                
                // Add correct conversion columns if not exist
                if (!Schema::hasColumn('m_raw_materials', 'konversi_satuan_utuh')) {
                    $table->string('konversi_satuan_utuh', 50)->nullable()->after('description');
                }
                
                if (!Schema::hasColumn('m_raw_materials', 'konversi_satuan_pakai')) {
                    $table->string('konversi_satuan_pakai', 50)->nullable()->after('konversi_satuan_utuh');
                }
                
                if (!Schema::hasColumn('m_raw_materials', 'konversi_satuan_kirim')) {
                    $table->string('konversi_satuan_kirim', 50)->nullable()->after('konversi_satuan_pakai');
                }
            });
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        // Check if table exists
        if (Schema::hasTable('m_raw_materials')) {
            Schema::table('m_raw_materials', function (Blueprint $table) {
                // Drop the correct columns
                if (Schema::hasColumn('m_raw_materials', 'konversi_satuan_utuh')) {
                    $table->dropColumn('konversi_satuan_utuh');
                }
                
                if (Schema::hasColumn('m_raw_materials', 'konversi_satuan_pakai')) {
                    $table->dropColumn('konversi_satuan_pakai');
                }
                
                if (Schema::hasColumn('m_raw_materials', 'konversi_satuan_kirim')) {
                    $table->dropColumn('konversi_satuan_kirim');
                }
                
                // Re-add conversion_factor if needed for rollback
                if (!Schema::hasColumn('m_raw_materials', 'conversion_factor')) {
                    $table->decimal('conversion_factor', 10, 4)->nullable()->after('description');
                }
            });
        }
    }
};
