<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('news', function (Blueprint $table) {
            $table->json('images')->nullable()->after('content');
        });

        // Migrate existing single image to images array
        $news = \Illuminate\Support\Facades\DB::table('news')->whereNotNull('image')->get();
        foreach ($news as $item) {
            \Illuminate\Support\Facades\DB::table('news')
                ->where('id', $item->id)
                ->update(['images' => json_encode([$item->image])]);
        }

        Schema::table('news', function (Blueprint $table) {
            $table->dropColumn('image');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('news', function (Blueprint $table) {
            $table->string('image')->nullable()->after('content');
        });

        $news = \Illuminate\Support\Facades\DB::table('news')->whereNotNull('images')->get();
        foreach ($news as $item) {
            $images = json_decode($item->images, true);
            $firstImage = (is_array($images) && count($images) > 0) ? $images[0] : null;
            if ($firstImage) {
                \Illuminate\Support\Facades\DB::table('news')
                    ->where('id', $item->id)
                    ->update(['image' => $firstImage]);
            }
        }

        Schema::table('news', function (Blueprint $table) {
            $table->dropColumn('images');
        });
    }
};
