<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\DB;
use App\Classes\ColumnClass;

class UpdateCreatedAtDefaultToCurrentTimestamp extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        $databaseName = DB::getDatabaseName();
        $tables = DB::select("SHOW TABLES");
        $tableKey = "Tables_in_{$databaseName}";

        foreach ($tables as $tableObj) {
            $tableName = $tableObj->$tableKey;

            if (Schema::hasColumn($tableName, 'created_at') && ColumnClass::getColumnDefault($tableName, 'created_at') !== 'CURRENT_TIMESTAMP') {
                DB::statement("
                    ALTER TABLE `$tableName`
                    CHANGE `created_at` `created_at` TIMESTAMP NULL 
                        DEFAULT CURRENT_TIMESTAMP
                ");
            }

            if (Schema::hasColumn($tableName, 'updated_at')) {
                DB::statement("
                    ALTER TABLE `$tableName`
                    CHANGE `updated_at` `updated_at` TIMESTAMP NULL 
                        DEFAULT CURRENT_TIMESTAMP 
                        ON UPDATE CURRENT_TIMESTAMP
                ");
            }
        }
    }
}


