<?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
    {
        Schema::table('projects', function (Blueprint $table) {
            $table->json('contact')->nullable()->after('design_unit');
        });

        $projects = DB::table('projects')->get();

        foreach ($projects as $project) {
            $contactUnit = json_decode($project->contact_unit, true);
            $contactPhone = json_decode($project->contact_phone, true);
            $inversmentPhone = json_decode($project->inversment_phone, true);

            $contact = [];

            if (is_array($contactUnit)) {
                foreach ($contactUnit as $locale => $value) {
                    $contact[$locale] = $value;
                }
            }

            if (is_array($contactPhone)) {
                foreach ($contactPhone as $locale => $value) {
                    if (isset($contact[$locale])) {
                        $contact[$locale] .= ' ' . $value;
                    } else {
                        $contact[$locale] = $value;
                    }
                }
            }
            
            if (is_array($inversmentPhone)) {
                foreach ($inversmentPhone as $locale => $value) {
                    if (isset($contact[$locale])) {
                        $contact[$locale] .= ' ' . $value;
                    } else {
                        $contact[$locale] = $value;
                    }
                }
            }

            DB::table('projects')
                ->where('id', $project->id)
                ->update(['contact' => json_encode($contact)]);
        }

        Schema::table('projects', function (Blueprint $table) {
            $table->dropColumn('contact_unit');
            $table->dropColumn('contact_phone');
            $table->dropColumn('inversment_phone');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('projects', function (Blueprint $table) {
            $table->json('contact_unit')->nullable();
            $table->json('contact_phone')->nullable();
            $table->json('inversment_phone')->nullable();
            $table->dropColumn('contact');
        });
    }
};