<?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('m_raw_materials', function (Blueprint $table) {
            $table->unsignedBigInteger('period_id')->nullable()->after('periode_order');
            $table->foreign('period_id')->references('id')->on('m_periods');
            $table->index('period_id');
        });

        // Update existing data to use period_id instead of periode_order string
        DB::statement("
            UPDATE m_raw_materials rm 
            SET period_id = (
                SELECT p.id 
                FROM m_periods p 
                WHERE p.code = rm.periode_order 
                AND p.delete_flag = false
                LIMIT 1
            )
            WHERE rm.periode_order IS NOT NULL
        ");
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('m_raw_materials', function (Blueprint $table) {
            $table->dropForeign(['period_id']);
            $table->dropIndex(['period_id']);
            $table->dropColumn('period_id');
        });
    }
};