<?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::table('users', function (Blueprint $table) {
            // التحقق من وجود الأعمدة قبل إضافتها
            if (!Schema::hasColumn('users', 'governorate_id')) {
                $table->foreignId('governorate_id')->nullable()->constrained()->onDelete('set null');
            }
            
            if (!Schema::hasColumn('users', 'city_id')) {
                $table->foreignId('city_id')->nullable()->constrained()->onDelete('set null');
            }
            
            if (!Schema::hasColumn('users', 'address')) {
                $table->string('address')->nullable(); // العنوان التفصيلي
            }
            
            // إضافة فهارس فقط إذا لم تكن موجودة
            if (!Schema::hasColumn('users', 'governorate_id') || !Schema::hasColumn('users', 'city_id')) {
                $table->index(['governorate_id', 'city_id']);
            }
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('users', function (Blueprint $table) {
            if (Schema::hasColumn('users', 'governorate_id')) {
                $table->dropForeign(['governorate_id']);
                $table->dropColumn('governorate_id');
            }
            
            if (Schema::hasColumn('users', 'city_id')) {
                $table->dropForeign(['city_id']);
                $table->dropColumn('city_id');
            }
            
            if (Schema::hasColumn('users', 'address')) {
                $table->dropColumn('address');
            }
        });
    }
};
