<?php

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('visits', function (Blueprint $table) {
            $table->id();
            $table->string('request_id', 50)->unique();

            // Host Information
            $table->string('host_email', 255);
            $table->string('host_name', 255);
            $table->string('host_phone', 20);
            $table->foreignId('location_id')->constrained('locations');

            // Visit Details
            $table->text('visit_reason');
            $table->string('main_visitor_email', 255);
            $table->enum('meeting_type', ['single', 'multiple']);

            // Date/Time for Single Day Meetings
            $table->date('date')->nullable();
            $table->time('start_time')->nullable();
            $table->time('end_time')->nullable();

            // Date Range for Multiple Day Meetings
            $table->date('date_from')->nullable();
            $table->date('date_to')->nullable();

            // Workflow Status
            $table->enum('status', [
                'Pending Visitor',
                'Pending Host',
                'Pending Approve',
                'Approved',
                'Rejected',
                'Canceled',
                'Completed',
                'Expired'
            ])->default('Pending Visitor');
            $table->text('rejection_reason')->nullable();

            // Token for Visitor Registration
            $table->string('registration_token', 64)->unique();
            $table->timestamp('token_expires_at');
            $table->timestamp('visitor_registered_at')->nullable();

            // Approval/Rejection
            $table->string('reviewed_by_email', 255)->nullable();
            $table->timestamp('reviewed_at')->nullable();

            // Metadata
            $table->integer('number_of_visitors')->default(1);
            $table->timestamps();

            // Foreign Keys
            $table->foreign('host_email')->references('email')->on('user_roles')->onDelete('cascade');
            $table->foreign('reviewed_by_email')->references('email')->on('user_roles')->onDelete('set null');

            // Indexes
            $table->index('request_id');
            $table->index('status');
            $table->index('host_email');
            $table->index('location_id');
            $table->index('registration_token');
            $table->index('date');
            $table->index('date_from');
            $table->index('created_at');
        });
    }

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