<?php

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

class AddFizikalRegistrationVerifiedAtToVoterTable extends Migration
{
    /**
     * Physical attendees (kehadiran = 1) need admin confirmation before voting.
     * NULL = not verified yet; non-NULL = verified at that time.
     * Maya (kehadiran = 2) does not use this column for gating.
     *
     * @return void
     */
    public function up()
    {
        if (! Schema::hasColumn('voter', 'fizikal_registration_verified_at')) {
            Schema::table('voter', function (Blueprint $table) {
                $table->timestamp('fizikal_registration_verified_at')->nullable()->after('kehadiran');
            });
        }

        // Existing physical registrations are treated as already verified.
        DB::table('voter')
            ->where('kehadiran', 1)
            ->whereNull('fizikal_registration_verified_at')
            ->update(['fizikal_registration_verified_at' => now()]);
    }

    /**
     * @return void
     */
    public function down()
    {
        if (Schema::hasColumn('voter', 'fizikal_registration_verified_at')) {
            Schema::table('voter', function (Blueprint $table) {
                $table->dropColumn('fizikal_registration_verified_at');
            });
        }
    }
}
