<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('users', function (Blueprint $table) {
            if (!Schema::hasColumn('users', 'fingerprint_pin')) {
                $table->string('fingerprint_pin', 8)->nullable()->unique()->after('nip_nis');
            }
        });

        // Backfill: gunakan ID user sebagai PIN mesin (max 8 digit protokol ZK)
        $users = DB::table('users')->whereNull('fingerprint_pin')->orderBy('id')->get(['id']);
        foreach ($users as $user) {
            DB::table('users')->where('id', $user->id)->update([
                'fingerprint_pin' => substr((string) $user->id, 0, 8),
            ]);
        }
    }

    public function down(): void
    {
        Schema::table('users', function (Blueprint $table) {
            if (Schema::hasColumn('users', 'fingerprint_pin')) {
                $table->dropUnique(['fingerprint_pin']);
                $table->dropColumn('fingerprint_pin');
            }
        });
    }
};
