<?php

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

// Cross-cutting system tables: activity log, in-app notifications, and extra
// columns on users for RBAC + branch scoping.
return new class extends Migration
{
    public function up(): void
    {
        Schema::create('activity_logs', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->nullable()->constrained()->nullOnDelete();
            $table->string('user_name')->nullable();
            $table->foreignId('branch_id')->nullable();
            $table->string('action');   // login|logout|create|update|delete|restore|export|import|sync|settings|permission
            $table->string('module')->nullable();
            $table->text('description')->nullable();
            $table->string('subject_type')->nullable();
            $table->unsignedBigInteger('subject_id')->nullable();
            $table->string('ip_address')->nullable();
            $table->timestamps();
            $table->index(['module', 'action']);
        });

        Schema::create('app_notifications', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->nullable()->constrained()->nullOnDelete();
            $table->foreignId('branch_id')->nullable();
            $table->string('title');
            $table->text('body')->nullable();
            $table->string('icon')->nullable();
            $table->string('priority')->default('low'); // low|medium|high
            $table->string('link')->nullable();
            $table->timestamp('read_at')->nullable();
            $table->timestamps();
        });

        Schema::table('users', function (Blueprint $table) {
            $table->string('role')->default('staff')->after('email'); // super-admin|admin|manager|teacher|staff
            $table->json('permissions')->nullable()->after('role');
            $table->foreignId('default_branch_id')->nullable()->after('permissions');
            $table->string('avatar')->nullable();
            $table->boolean('is_active')->default(true);
        });
    }

    public function down(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn(['role', 'permissions', 'default_branch_id', 'avatar', 'is_active']);
        });
        Schema::dropIfExists('app_notifications');
        Schema::dropIfExists('activity_logs');
    }
};
