<?php

use App\Libs\Facades\ContentTypes;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class AddDeletedAtColumnToEntries extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        $contentTypes = ContentTypes::all();

        foreach ($contentTypes as $contentType) {
            $modelType = $contentType->getModelType();
            $model = new $modelType();
            $tableName = $model->getTable();

            Schema::table($tableName, function (Blueprint $table) use ($tableName) {
                $table->dateTime('updated_at')->nullable()->default(null)->change();
                $table->dateTime('created_at')->nullable()->default(null)->change();
                $table->softDeletes();
            });
        }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        $contentTypes = ContentTypes::all();

        foreach ($contentTypes as $contentType) {
            $modelType = $contentType->getModelType();
            $model = new $modelType();
            $tableName = $model->getTable();

            Schema::table($tableName, function (Blueprint $table) {
                $table->dropSoftDeletes();
            });
        }
    }

    private function _getColumnDefault($tableName, $columnName)
    {
        $query = "SELECT COLUMN_DEFAULT
            FROM INFORMATION_SCHEMA.COLUMNS
            WHERE TABLE_NAME = '$tableName'
            AND COLUMN_NAME = '$columnName'";

        $result = DB::select($query);

        if (empty($result)) {
            return null;
        }

        return $result[0]->COLUMN_DEFAULT;
    }
}
