<?php

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

class UpdateAllPalsuStatusToOne extends Migration
{
    /**
     * Get active database connections
     */
    private function getActiveDB(): array
    {
        $config_db = array_keys(config("database.connections"));

        $db_connection = array_filter($config_db, function($connection) {
            try {
                if ($connection == 'mysql7') {
                    return false;
                }

                DB::connection($connection)->select('SELECT 1');
                return true;
            } catch (\Exception $e) {
                return false;
            }
        });
        
        return $db_connection ? array_values($db_connection) : [];
    }

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        $db_connection = $this->getActiveDB();

        foreach ($db_connection as $dbase) {
            try {
                // Update all status values to 1 in palsu table
                $updated = DB::connection($dbase)->table('palsu')
                    ->update(['status' => 1]);
                    
                if ($updated > 0) {
                    echo "Updated {$updated} records in {$dbase} palsu table to status = 1\n";
                }
            } catch (\Exception $e) {
                echo "Error updating {$dbase}: " . $e->getMessage() . "\n";
            }
        }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        $db_connection = $this->getActiveDB();

        foreach ($db_connection as $dbase) {
            try {
                // Revert all status values back to 0 in palsu table
                $reverted = DB::connection($dbase)->table('palsu')
                    ->update(['status' => 0]);
                    
                if ($reverted > 0) {
                    echo "Reverted {$reverted} records in {$dbase} palsu table to status = 0\n";
                }
            } catch (\Exception $e) {
                echo "Error reverting {$dbase}: " . $e->getMessage() . "\n";
            }
        }
    }
}
