<?php

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

return new class extends Migration
{
    public function up(): void
    {
        // Decode any HTML entities stored in existing rows for name, slug and description.
        DB::table('news_categories')->orderBy('id')->chunkById(100, function ($rows) {
            foreach ($rows as $row) {
                $name = html_entity_decode($row->name ?? '', ENT_QUOTES | ENT_HTML5, 'UTF-8');
                $slug = html_entity_decode($row->slug ?? '', ENT_QUOTES | ENT_HTML5, 'UTF-8');
                $description = html_entity_decode($row->description ?? '', ENT_QUOTES | ENT_HTML5, 'UTF-8');

                if ($name !== ($row->name ?? '') || $slug !== ($row->slug ?? '') || $description !== ($row->description ?? '')) {
                    DB::table('news_categories')->where('id', $row->id)->update([
                        'name' => $name,
                        'slug' => $slug,
                        'description' => $description,
                    ]);
                }
            }
        });
    }

    public function down(): void
    {
        // Irreversible: restoring previous encoding isn't safe without a backup.
    }
};
