<?php

use App\Models\Pouzivatel\Pouzivatel;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

/**
 * Class PridanyStlpecPriezviskoPouzivateliaTable
 */
return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('pouzivatelia', function (Blueprint $table) {
            $table->string('priezvisko')->nullable()->after('meno');
        });

        Pouzivatel::withoutEvents(function () {
            Pouzivatel::query()->chunk(20, function (Collection $pouzivatelia) {
                foreach ($pouzivatelia as $pouzivatel) {
                    $pouzivatel->priezvisko = explode(' ', $pouzivatel->meno)[1];
                    $pouzivatel->meno = explode(' ', $pouzivatel->meno)[0];
                    $pouzivatel->save();
                }
            });
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Pouzivatel::withoutEvents(function () {
            Pouzivatel::query()->chunk(20, function (Collection $pouzivatelia) {
                foreach ($pouzivatelia as $pouzivatel) {
                    $pouzivatel->meno = sprintf('%s %s', $pouzivatel->meno, $pouzivatel->priezvisko);
                    $pouzivatel->save();
                }
            });
        });

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