<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('users', function (Blueprint $table) {
            if (!Schema::hasColumn('users', 'deleted_at')) {
                $table->softDeletes();
            }
        });

        Schema::table('shifts', function (Blueprint $table) {
            if (!Schema::hasColumn('shifts', 'type')) {
                $table->string('type')->default('guru')->after('name'); // guru, siswa, khusus, tambahan
                $table->integer('late_tolerance_minutes')->default(0)->after('end_time');
            }
            if (!Schema::hasColumn('shifts', 'deleted_at')) {
                $table->softDeletes();
            }
        });

        Schema::table('fingerprint_machines', function (Blueprint $table) {
            if (!Schema::hasColumn('fingerprint_machines', 'firmware')) {
                $table->string('firmware')->nullable()->after('status');
                $table->integer('user_count')->default(0)->after('firmware');
                $table->integer('log_count')->default(0)->after('user_count');
                $table->integer('latency_ms')->default(0)->after('log_count');
            }
            if (!Schema::hasColumn('fingerprint_machines', 'deleted_at')) {
                $table->softDeletes();
            }
        });

        Schema::table('audit_logs', function (Blueprint $table) {
            if (!Schema::hasColumn('audit_logs', 'ip_address')) {
                $table->string('ip_address', 45)->nullable()->after('description');
                $table->text('user_agent')->nullable()->after('ip_address');
                $table->string('browser', 100)->nullable()->after('user_agent');
                $table->string('device', 100)->nullable()->after('browser');
                $table->json('before_values')->nullable()->after('device');
                $table->json('after_values')->nullable()->after('before_values');
            }
        });
    }

    public function down(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropSoftDeletes();
        });

        Schema::table('shifts', function (Blueprint $table) {
            $table->dropColumn(['type', 'late_tolerance_minutes']);
            $table->dropSoftDeletes();
        });

        Schema::table('fingerprint_machines', function (Blueprint $table) {
            $table->dropColumn(['firmware', 'user_count', 'log_count', 'latency_ms']);
            $table->dropSoftDeletes();
        });

        Schema::table('audit_logs', function (Blueprint $table) {
            $table->dropColumn(['ip_address', 'user_agent', 'browser', 'device', 'before_values', 'after_values']);
        });
    }
};
