<?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::create('packages', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('code')->unique();
            $table->text('description')->nullable();
            $table->decimal('monthly_price', 12, 2)->default(0);
            $table->decimal('yearly_price', 12, 2)->default(0);
            $table->unsignedInteger('employee_limit')->default(0);
            $table->unsignedInteger('branch_limit')->default(0);
            $table->unsignedInteger('device_limit')->default(0);
            $table->unsignedInteger('trial_days')->default(0);
            $table->json('features')->nullable();
            $table->boolean('is_active')->default(true);
            $table->timestamps();
        });

        Schema::create('tenants', function (Blueprint $table) {
            $table->id();
            $table->foreignId('package_id')->nullable()->constrained()->nullOnDelete();
            $table->string('name');
            $table->string('slug')->unique();
            $table->string('email');
            $table->string('phone')->nullable();
            $table->string('logo_path')->nullable();
            $table->string('status')->default('trial')->index();
            $table->string('timezone')->default('UTC');
            $table->string('currency', 3)->default('USD');
            $table->unsignedInteger('employee_limit')->default(0);
            $table->unsignedInteger('branch_limit')->default(0);
            $table->unsignedInteger('device_limit')->default(0);
            $table->timestamp('expires_at')->nullable();
            $table->json('settings')->nullable();
            $table->timestamps();
        });

        Schema::table('users', function (Blueprint $table) {
            $table->foreignId('tenant_id')->nullable()->after('id')->constrained()->nullOnDelete();
            $table->boolean('is_super_admin')->default(false)->after('password');
            $table->timestamp('two_factor_confirmed_at')->nullable()->after('is_super_admin');
        });
    }

    public function down(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropConstrainedForeignId('tenant_id');
            $table->dropColumn(['is_super_admin', 'two_factor_confirmed_at']);
        });
        Schema::dropIfExists('tenants');
        Schema::dropIfExists('packages');
    }
};
