<?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::create('user_social_links', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->string('platform', 30);
            $table->string('value', 500);
            $table->unsignedSmallInteger('sort_order')->default(0);
            $table->timestamps();
            $table->index(['user_id', 'sort_order']);
        });

        // Migrate existing individual social columns into the new table
        $cols = ['twitter','instagram','facebook','youtube','linkedin','tiktok',
                 'website','whatsapp','google_location','social_phone','social_email'];
        foreach (\DB::table('users')->get() as $user) {
            $order = 0;
            foreach ($cols as $col) {
                $val = $user->$col ?? null;
                if ($val) {
                    \DB::table('user_social_links')->insert([
                        'user_id'    => $user->id,
                        'platform'   => $col,
                        'value'      => $val,
                        'sort_order' => $order++,
                        'created_at' => now(),
                        'updated_at' => now(),
                    ]);
                }
            }
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('user_social_links');
    }
};
