<?php

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

return new class extends Migration
{
    public function up()
    {
        Schema::create('tenancies', function (Blueprint $table) {
            $table->id();
            
            // Foreign keys
            $table->unsignedBigInteger('customer_id');
            $table->foreign('customer_id')->references('CustomerID')->on('customer');
            
            $table->unsignedBigInteger('unit_id');
            $table->foreign('unit_id')->references('UnitID')->on('prounits');
            
            $table->unsignedBigInteger('company_id');
            $table->foreign('company_id')->references('CompanyID')->on('company');
            
            $table->unsignedBigInteger('status_id')->nullable();
            $table->foreign('status_id')->references('id')->on('tenancy_statuses');
            
            // Tenancy details
            $table->date('start_date');
            $table->date('end_date')->nullable();
            $table->decimal('monthly_rent', 12, 2);
            $table->decimal('security_deposit', 12, 2)->default(0);
            
            // Move-in/move-out details
            $table->date('move_in_date')->nullable();
            $table->date('move_out_date')->nullable();
            $table->text('move_in_notes')->nullable();
            $table->text('move_out_notes')->nullable();
            
            // Contract/document references
            $table->string('lease_document_path')->nullable();
            $table->string('contract_number')->nullable();
            
            // Audit fields
            $table->foreignId('created_by')->nullable()->constrained('users');
            $table->foreignId('updated_by')->nullable()->constrained('users');
            
            $table->timestamps();
            $table->softDeletes();
            
            // Indexes
            $table->index(['customer_id', 'unit_id']);
            $table->index(['unit_id', 'status_id']);
            $table->index(['company_id', 'status_id']);
        });
    }

    public function down()
    {
        Schema::dropIfExists('tenancies');
    }
};