<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        // Only run if the branches table exists
        if (Schema::hasTable('branches')) {
            Schema::table('branches', function (Blueprint $table) {
                // Add fields if they don't exist
                if (!Schema::hasColumn('branches', 'name_en')) {
                    $table->string('name_en')->nullable()->after('name');
                }

                if (!Schema::hasColumn('branches', 'mobile')) {
                    $table->string('mobile')->nullable()->after('phone');
                }

                if (!Schema::hasColumn('branches', 'address_en')) {
                    $table->text('address_en')->nullable()->after('address');
                }

                if (!Schema::hasColumn('branches', 'location_lat')) {
                    $table->decimal('location_lat', 10, 7)->nullable()->after('postal_code');
                }

                if (!Schema::hasColumn('branches', 'location_lng')) {
                    $table->decimal('location_lng', 10, 7)->nullable()->after('location_lat');
                }

                // Rename is_main to is_main_branch if it exists
                if (Schema::hasColumn('branches', 'is_main') && !Schema::hasColumn('branches', 'is_main_branch')) {
                    $table->renameColumn('is_main', 'is_main_branch');
                }
            });
        }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        // Only run if the branches table exists
        if (Schema::hasTable('branches')) {
            Schema::table('branches', function (Blueprint $table) {
                // Drop the columns if they exist
                $columns = [
                    'name_en',
                    'mobile',
                    'address_en',
                    'location_lat',
                    'location_lng'
                ];

                foreach ($columns as $column) {
                    if (Schema::hasColumn('branches', $column)) {
                        $table->dropColumn($column);
                    }
                }

                // Rename is_main_branch back to is_main if it exists
                if (Schema::hasColumn('branches', 'is_main_branch') && !Schema::hasColumn('branches', 'is_main')) {
                    $table->renameColumn('is_main_branch', 'is_main');
                }
            });
        }
    }
};
