<?php

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

class CreateVisibilityModulesTable extends Migration
{
    public function up()
    {
        Schema::create('visibility_modules', function (Blueprint $table) {
            $table->id();
            $table->string('key', 80)->unique();
            $table->string('label', 120);
            $table->string('group', 80)->default('Other');
            $table->string('description', 255)->nullable();
            $table->boolean('is_active')->default(true);
            $table->unsignedSmallInteger('sort_order')->default(0);
            $table->timestamps();
        });

        $modules = config('visibility.modules', []);
        $order = 0;
        $now = now();
        foreach ($modules as $key => $meta) {
            DB::table('visibility_modules')->insert([
                'key' => $key,
                'label' => $meta['label'] ?? $key,
                'group' => $meta['group'] ?? 'Other',
                'description' => $meta['description'] ?? null,
                'is_active' => true,
                'sort_order' => $order++,
                'created_at' => $now,
                'updated_at' => $now,
            ]);
        }
    }

    public function down()
    {
        Schema::dropIfExists('visibility_modules');
    }
}
