<?php

use App\Enums\VisitorStatus;
use App\Enums\VisitorType;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration {
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('visitors', function (Blueprint $table) {
            $table->id();

            $table->foreignId('wing_id')->constrained('wings')->onDelete('cascade');
            $table->foreignId('flat_id')->constrained('flats')->onDelete('cascade');
            $table->foreignId('approved_by')->nullable()->constrained('users')->onDelete('set null');
            $table->foreignId('checked_in_by')->nullable()->constrained('users')->onDelete('set null');
            $table->foreignId('checked_out_by')->nullable()->constrained('users')->onDelete('set null');

            $table->string('name');
            $table->string('phone');
            $table->string('email')->nullable();
            $table->enum('visitor_type', VisitorType::values())->default(VisitorType::GUEST->value);
            $table->string('purpose');
            $table->text('photo')->nullable();
            $table->enum('status', VisitorStatus::values())->default(VisitorStatus::PENDING->value);
            $table->timestamp('entry_time')->nullable();
            $table->timestamp('exit_time')->nullable();
            $table->timestamp('approved_at')->nullable();
            $table->text('approval_notes')->nullable();
            $table->text('rejection_reason')->nullable();
            $table->json('additional_info')->nullable();
            $table->boolean('is_recurring')->default(false);
            $table->timestamps();

            $table->index(['status', 'wing_id', 'flat_id']);
            $table->index(['phone', 'status']);
            $table->index(['entry_time', 'exit_time']);
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('visitors');
    }
};
