<?php

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

return new class extends Migration
{
    public function up(): void
    {
        // Convert existing string data to JSON format
        $packages = DB::table('packages')->get();

        foreach ($packages as $package) {
            $updates = [];

            // name
            $updates['name'] = json_encode(['ar' => $package->name ?? '', 'en' => ''], JSON_UNESCAPED_UNICODE);

            // description
            $updates['description'] = $package->description
                ? json_encode(['ar' => $package->description, 'en' => ''], JSON_UNESCAPED_UNICODE)
                : null;

            // badge_text
            $updates['badge_text'] = $package->badge_text
                ? json_encode(['ar' => $package->badge_text, 'en' => ''], JSON_UNESCAPED_UNICODE)
                : null;

            DB::table('packages')->where('id', $package->id)->update($updates);
        }

        Schema::table('packages', function (Blueprint $table) {
            $table->json('name')->change();
            $table->json('description')->nullable()->change();
            $table->json('badge_text')->nullable()->change();
        });
    }

    public function down(): void
    {
        Schema::table('packages', function (Blueprint $table) {
            $table->string('name')->change();
            $table->text('description')->nullable()->change();
            $table->string('badge_text')->nullable()->change();
        });
    }
};
