<?php

use App\User;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class SwitchToUtf8Mb4 extends Migration {
    /**
     * Returns all database tables.
     * @return string[]
     */
    private function getTables(): array {
        $tablesRows = DB::select(DB::raw('show tables'));
        return array_map(fn($row) => array_values(get_object_vars($row))[0], $tablesRows);
    }

    /**
     * The database name.
     * @var string
     */
    private $db;

    public function __construct() {
        $this->db = env('DB_DATABASE');
    }

    public function up() {
        echo "Changing default database encoding to uft8mb4...\n";

        DB::update("
            alter database $this->db
            character set = utf8mb4
            collate = utf8mb4_unicode_ci
        ");

        foreach ($this->getTables() as $table) {
            echo "Converting table \"$table\" to utf8mb4...\n";
            DB::update("
                alter table $table
                convert to character set utf8mb4
                collate utf8mb4_unicode_ci
            ");
        }
    }

    public function down() {
        echo "Reverting default database encoding back to default uft8...\n";

        DB::update("
            alter database $this->db
            character set = utf8
            collate = utf8_unicode_ci
        ");

        foreach ($this->getTables() as $table) {
            echo "Reverting table \"$table\" back to default utf8...\n";
            DB::update("
                alter table $table
                convert to character set utf8
                collate utf8_unicode_ci
            ");
        }
    }
}
