<?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()
    {
        // Ensure the property table exists first
        if (!Schema::hasTable('property')) {
            Schema::create('property', function (Blueprint $table) {
                $table->index('PropID');
                $table->index('CompanyID');
                $table->string('PropName');
                $table->engine = 'InnoDB';
            });
        }

        Schema::create('blocks', function (Blueprint $table) {
            // $table->engine = 'InnoDB';
            // $table->charset = 'utf8mb4';
            // $table->collation = 'utf8mb4_unicode_ci';
            $table->id('BlockID');
            $table->unsignedBigInteger('PropID');
             $table->unsignedBigInteger('CompanyID');
            
            // Add foreign key for CompanyID
            $table->foreign('CompanyID')
                  ->references('CompanyID')
                  ->on('company')
                  ->onDelete('cascade');
                  
            $table->string('BlockName', 50);
            $table->string('BlockCode', 20);
            $table->text('Description')->nullable();
            $table->integer('Floors')->default(1);
            $table->integer('UnitsPerFloor')->default(0);
            $table->boolean('HasLift')->default(false);
            $table->string('BlockStatus', 20)->default('Active');
            $table->timestamps();
            
            // Foreign key constraint
            if (Schema::hasTable('property') && Schema::hasColumn('property', 'PropID')) {
                $table->foreign('PropID')
                      ->references('PropID')
                      ->on('property')
                      ->onDelete('cascade');
            }
        });

        // Add BlockID to prounits table if it exists
        if (Schema::hasTable('prounits') && !Schema::hasColumn('prounits', 'BlockID')) {
            Schema::table('prounits', function (Blueprint $table) {
                $table->unsignedInteger('BlockID')->nullable()->after('PropID');
                
                if (Schema::hasTable('blocks')) {
                    $table->foreign('BlockID')
                          ->references('BlockID')
                          ->on('blocks')
                          ->onDelete('set null');
                }
            });
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down()
    {
        // Drop foreign key first
        Schema::table('prounits', function (Blueprint $table) {
            $table->dropForeign(['BlockID']);
            $table->dropColumn('BlockID');
        });
        
        Schema::dropIfExists('blocks');
    }
};
