<?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
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // First, convert existing string data to JSON format
        $categories = DB::table('categories')->get();
        
        foreach ($categories as $category) {
            $nameData = [
                'ar' => $category->name ?? '',
                'en' => '',
            ];
            
            $descriptionData = $category->description ? [
                'ar' => $category->description,
                'en' => '',
            ] : null;
            
            DB::table('categories')
                ->where('id', $category->id)
                ->update([
                    'name' => json_encode($nameData, JSON_UNESCAPED_UNICODE),
                    'description' => $descriptionData ? json_encode($descriptionData, JSON_UNESCAPED_UNICODE) : null,
                ]);
        }
        
        // Then change column types
        Schema::table('categories', function (Blueprint $table) {
            $table->json('name')->change();
            $table->json('description')->nullable()->change();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('categories', function (Blueprint $table) {
            $table->string('name')->change();
            $table->text('description')->nullable()->change();
        });
    }
};
