<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        if (! Schema::hasTable('attendances')) {
            return;
        }
        Schema::table('attendances', function (Blueprint $table) {
            if (! Schema::hasColumn('attendances', 'clock_in_latitude')) {
                $table->decimal('clock_in_latitude', 10, 8)->nullable()->after('clock_in_ip_address');
            }
            if (! Schema::hasColumn('attendances', 'clock_in_longitude')) {
                $table->decimal('clock_in_longitude', 11, 8)->nullable()->after('clock_in_latitude');
            }
            if (! Schema::hasColumn('attendances', 'clock_in_location')) {
                $table->string('clock_in_location', 500)->nullable()->after('clock_in_longitude');
            }
            if (! Schema::hasColumn('attendances', 'clock_out_latitude')) {
                $table->decimal('clock_out_latitude', 10, 8)->nullable()->after('clock_out_ip_address');
            }
            if (! Schema::hasColumn('attendances', 'clock_out_longitude')) {
                $table->decimal('clock_out_longitude', 11, 8)->nullable()->after('clock_out_latitude');
            }
            if (! Schema::hasColumn('attendances', 'clock_out_location')) {
                $table->string('clock_out_location', 500)->nullable()->after('clock_out_longitude');
            }
        });
    }

    public function down(): void
    {
        if (! Schema::hasTable('attendances')) {
            return;
        }
        $drops = [];
        if (Schema::hasColumn('attendances', 'clock_in_latitude')) $drops[] = 'clock_in_latitude';
        if (Schema::hasColumn('attendances', 'clock_in_longitude')) $drops[] = 'clock_in_longitude';
        if (Schema::hasColumn('attendances', 'clock_in_location')) $drops[] = 'clock_in_location';
        if (Schema::hasColumn('attendances', 'clock_out_latitude')) $drops[] = 'clock_out_latitude';
        if (Schema::hasColumn('attendances', 'clock_out_longitude')) $drops[] = 'clock_out_longitude';
        if (Schema::hasColumn('attendances', 'clock_out_location')) $drops[] = 'clock_out_location';
        if (! empty($drops)) {
            Schema::table('attendances', fn (Blueprint $t) => $t->dropColumn($drops));
        }
    }
};
