<?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
 */
class PridanyStlpecPriezviskoPouzivateliaTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        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.
     *
     * @return void
     */
    public function down()
    {
        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');
        });
    }
}
