<?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
    {
        Schema::table('obat_keluars', function (Blueprint $table) {
            // Add new fields with existence checks
            if (!Schema::hasColumn('obat_keluars', 'barcode')) {
                $table->string('barcode')->nullable()->after('kode_batch');
            }
            if (!Schema::hasColumn('obat_keluars', 'sumber_dana')) {
                $table->string('sumber_dana')->nullable()->after('tujuan_pemakaian');
            }
            if (!Schema::hasColumn('obat_keluars', 'harga')) {
                $table->decimal('harga', 15, 2)->nullable()->after('jumlah');
            }
            if (!Schema::hasColumn('obat_keluars', 'harga_total')) {
                $table->decimal('harga_total', 15, 2)->nullable()->after('harga');
            }
        });

        // First, expand the enum to include all values (both old and new)
        DB::statement("ALTER TABLE obat_keluars MODIFY COLUMN status ENUM('terkirim', 'proses', 'selesai', 'dibatalkan') DEFAULT 'proses'");
        
        // Update existing 'terkirim' status to 'selesai'
        DB::statement("UPDATE obat_keluars SET status = 'selesai' WHERE status = 'terkirim'");
        
        // Finally, narrow enum to only new values
        DB::statement("ALTER TABLE obat_keluars MODIFY COLUMN status ENUM('proses', 'selesai', 'dibatalkan') DEFAULT 'proses'");
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        // Revert status enum
        DB::statement("ALTER TABLE obat_keluars MODIFY COLUMN status ENUM('terkirim', 'proses', 'dibatalkan') DEFAULT 'proses'");
        DB::statement("UPDATE obat_keluars SET status = 'terkirim' WHERE status = 'selesai'");

        Schema::table('obat_keluars', function (Blueprint $table) {
            $table->dropColumn(['barcode', 'sumber_dana', 'harga', 'harga_total']);
        });
    }
};
