<?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.
     *
     * @return void
     */
    public function up()
    {
        // Check if table exists
        if (!Schema::hasTable('t_stock_opname_details')) {
            return;
        }

        // Migrate data: Ensure lsm_aktual has all values from qty_total
        // (They should already be the same, but just to be safe)
        if (Schema::hasColumn('t_stock_opname_details', 'qty_total') && 
            Schema::hasColumn('t_stock_opname_details', 'lsm_aktual')) {
            
            DB::statement("
                UPDATE t_stock_opname_details 
                SET lsm_aktual = qty_total 
                WHERE lsm_aktual IS NULL OR lsm_aktual = 0
            ");
            
            \Log::info('Migration: Migrated qty_total values to lsm_aktual');
        }

        // Drop qty_total column
        Schema::table('t_stock_opname_details', function (Blueprint $table) {
            if (Schema::hasColumn('t_stock_opname_details', 'qty_total')) {
                $table->dropColumn('qty_total');
                \Log::info('Migration: Dropped qty_total column from t_stock_opname_details');
            }
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        // Re-add qty_total column
        Schema::table('t_stock_opname_details', function (Blueprint $table) {
            if (!Schema::hasColumn('t_stock_opname_details', 'qty_total')) {
                $table->decimal('qty_total', 10, 2)->default(0)->after('qty_converted');
                \Log::info('Migration rollback: Re-added qty_total column');
            }
        });

        // Restore data from lsm_aktual
        if (Schema::hasColumn('t_stock_opname_details', 'qty_total') && 
            Schema::hasColumn('t_stock_opname_details', 'lsm_aktual')) {
            
            DB::statement("
                UPDATE t_stock_opname_details 
                SET qty_total = lsm_aktual
            ");
            
            \Log::info('Migration rollback: Restored qty_total values from lsm_aktual');
        }
    }
};
