<?php

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

/**
 * Maliyetler resource_cost_items'a taşındı (…_020000); sabit kolonlar kaldırılır.
 * down() kolonları geri açar ve "Günlük Yevmiye" / "Km Başı Maliyet" başlıklı
 * satırlardan doldurur.
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::table('resources', function (Blueprint $table) {
            $table->dropColumn(['cost_daily', 'cost_per_km']);
        });
    }

    public function down(): void
    {
        Schema::table('resources', function (Blueprint $table) {
            $table->decimal('cost_daily', 10, 2)->default(0)->after('vehicle_registration_document');
            $table->decimal('cost_per_km', 10, 2)->default(0)->after('cost_daily');
        });

        if (!Schema::hasTable('resource_cost_items')) {
            return;
        }

        DB::table('resource_cost_items')
            ->whereIn('title', ['Günlük Yevmiye', 'Km Başı Maliyet'])
            ->orderBy('id')
            ->chunkById(200, function ($items) {
                foreach ($items as $item) {
                    $column = $item->title === 'Günlük Yevmiye' ? 'cost_daily' : 'cost_per_km';
                    DB::table('resources')->where('id', $item->resource_id)->update([$column => $item->amount]);
                }
            });
    }
};
