<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // Update m_raw_materials
        if (Schema::hasTable('m_raw_materials')) {
            // Update existing data yang lebih dari 2 karakter
            DB::statement("UPDATE m_raw_materials SET uom = LEFT(uom, 2) WHERE LENGTH(uom) > 2");
            DB::statement("UPDATE m_raw_materials SET konversi_satuan_utuh = LEFT(konversi_satuan_utuh, 2) WHERE LENGTH(konversi_satuan_utuh) > 2");
            DB::statement("UPDATE m_raw_materials SET konversi_satuan_pakai = LEFT(konversi_satuan_pakai, 2) WHERE LENGTH(konversi_satuan_pakai) > 2");
            DB::statement("UPDATE m_raw_materials SET konversi_satuan_kirim = LEFT(konversi_satuan_kirim, 2) WHERE LENGTH(konversi_satuan_kirim) > 2");
            
            // Alter column length
            DB::statement("ALTER TABLE m_raw_materials ALTER COLUMN uom TYPE VARCHAR(2)");
            DB::statement("ALTER TABLE m_raw_materials ALTER COLUMN konversi_satuan_utuh TYPE VARCHAR(2)");
            DB::statement("ALTER TABLE m_raw_materials ALTER COLUMN konversi_satuan_pakai TYPE VARCHAR(2)");
            DB::statement("ALTER TABLE m_raw_materials ALTER COLUMN konversi_satuan_kirim TYPE VARCHAR(2)");
        }

        // Update m_item_conversions
        if (Schema::hasTable('m_item_conversions')) {
            DB::statement("UPDATE m_item_conversions SET uom_utuh = LEFT(uom_utuh, 2) WHERE LENGTH(uom_utuh) > 2");
            DB::statement("UPDATE m_item_conversions SET uom_pakai = LEFT(uom_pakai, 2) WHERE LENGTH(uom_pakai) > 2");
            
            DB::statement("ALTER TABLE m_item_conversions ALTER COLUMN uom_utuh TYPE VARCHAR(2)");
            DB::statement("ALTER TABLE m_item_conversions ALTER COLUMN uom_pakai TYPE VARCHAR(2)");
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        // Restore to original length
        if (Schema::hasTable('m_raw_materials')) {
            DB::statement("ALTER TABLE m_raw_materials ALTER COLUMN uom TYPE VARCHAR(10)");
            DB::statement("ALTER TABLE m_raw_materials ALTER COLUMN konversi_satuan_utuh TYPE VARCHAR(10)");
            DB::statement("ALTER TABLE m_raw_materials ALTER COLUMN konversi_satuan_pakai TYPE VARCHAR(10)");
            DB::statement("ALTER TABLE m_raw_materials ALTER COLUMN konversi_satuan_kirim TYPE VARCHAR(10)");
        }

        if (Schema::hasTable('m_item_conversions')) {
            DB::statement("ALTER TABLE m_item_conversions ALTER COLUMN uom_utuh TYPE VARCHAR(10)");
            DB::statement("ALTER TABLE m_item_conversions ALTER COLUMN uom_pakai TYPE VARCHAR(10)");
        }
    }
};
