<?php

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

return new class extends Migration {
    public function up(): void
    {
        Schema::table('supplier_responsibles', function (Blueprint $table) {
            $table->string('first_name')->nullable()->after('supplier_id');
            $table->string('last_name')->nullable()->after('first_name');
            $table->string('gender', 10)->nullable()->after('last_name'); // male | female | other
        });

        // Mevcut "name" verisini ad / soyad olarak ayır
        $rows = DB::table('supplier_responsibles')->whereNotNull('name')->get();
        foreach ($rows as $row) {
            $name = trim((string) $row->name);
            if ($name === '') {
                continue;
            }
            $parts = preg_split('/\s+/', $name);
            $last = count($parts) > 1 ? array_pop($parts) : '';
            $first = implode(' ', $parts);

            DB::table('supplier_responsibles')->where('id', $row->id)->update([
                'first_name' => $first !== '' ? $first : $name,
                'last_name' => $last,
            ]);
        }
    }

    public function down(): void
    {
        Schema::table('supplier_responsibles', function (Blueprint $table) {
            $table->dropColumn(['first_name', 'last_name', 'gender']);
        });
    }
};
