<?php

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

return new class extends Migration
{
    /**
     * The "root" entities that belong directly to a company. Child/pivot
     * tables (chapters, contents, questions, exam_sessions, enrollments,
     * transactions, reviews, and the like) deliberately do NOT get their
     * own company_id here — they scope transitively through the parent
     * they already belong to (a chapter through its course, an enrollment
     * through its course, and so on), so tenancy stays enforced without
     * denormalizing company_id onto every table in the schema.
     */
    private array $tables = [
        'categories',
        'courses',
        'instructors',
        'exams',
        'quizzes',
        'coupons',
        'invoices',
        'blogs',
        'articles',
        'pages',
        'testimonials',
        'offer_banners',
        'notifications',
        'payment_gateways',
        'languages',
        'frames',
        'subscribers',
        'social_media',
        'plans',
        'manage_certificates',
        'contact_messages',
        'newslatter_subscriptions',
    ];

    /**
     * Run the migrations.
     */
    public function up(): void
    {
        foreach ($this->tables as $tableName) {
            if (!Schema::hasTable($tableName) || Schema::hasColumn($tableName, 'company_id')) {
                continue;
            }

            Schema::table($tableName, function (Blueprint $table) {
                $table->foreignId('company_id')->nullable()->after('id')->constrained()->nullOnDelete();
            });
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        foreach ($this->tables as $tableName) {
            if (!Schema::hasTable($tableName) || !Schema::hasColumn($tableName, 'company_id')) {
                continue;
            }

            Schema::table($tableName, function (Blueprint $table) {
                $table->dropForeign(['company_id']);
                $table->dropColumn('company_id');
            });
        }
    }
};
