<?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
    {
        // Step 1: Gabungkan nilai fstr ke item_olahan sebelum drop column
        // Hanya jika ada data di fstr yang tidak 0
        DB::statement("
            UPDATE t_stock_opname_details 
            SET item_olahan = COALESCE(item_olahan, 0) + COALESCE(fstr, 0)
            WHERE fstr IS NOT NULL AND fstr != 0
        ");
        
        // Step 2: Drop column fstr
        if (Schema::hasColumn('t_stock_opname_details', 'fstr')) {
            Schema::table('t_stock_opname_details', function (Blueprint $table) {
                $table->dropColumn('fstr');
            });
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        // Rollback: Tambah kembali column fstr dengan default 0
        if (!Schema::hasColumn('t_stock_opname_details', 'fstr')) {
            Schema::table('t_stock_opname_details', function (Blueprint $table) {
                $table->decimal('fstr', 10, 2)->default(0)->nullable()->after('item_olahan');
            });
        }
    }
};
