<?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
    {
        Schema::table('material_stocks', function (Blueprint $table) {
            $table->dropForeign(['project_id']);
            $table->dropForeign(['material_id']);
        });

        Schema::table('material_stocks', function (Blueprint $table) {
            $table->dropUnique(['project_id', 'material_id']);
        });

        Schema::table('material_stocks', function (Blueprint $table) {
            $table->foreign('project_id')->references('id')->on('projects')->cascadeOnDelete();
            $table->foreign('material_id')->references('id')->on('materials')->cascadeOnDelete();

            $table->foreignId('vendor_id')->nullable()->after('material_id')->constrained()->nullOnDelete();
            $table->date('received_date')->nullable()->after('quantity_used');
            $table->string('bill_number')->nullable()->after('received_date');
            $table->decimal('paid_amount', 15, 2)->default(0)->after('unit_price');
            $table->string('payment_method')->nullable()->after('paid_amount');
            $table->text('notes')->nullable()->after('payment_method');

            $table->index(['project_id', 'material_id']);
            $table->index(['vendor_id', 'received_date']);
        });
    }

    public function down(): void
    {
        Schema::table('material_stocks', function (Blueprint $table) {
            $table->dropForeign(['vendor_id']);
            $table->dropForeign(['project_id']);
            $table->dropForeign(['material_id']);
            $table->dropIndex(['project_id', 'material_id']);
            $table->dropIndex(['vendor_id', 'received_date']);
            $table->dropColumn([
                'vendor_id', 'received_date', 'bill_number',
                'paid_amount', 'payment_method', 'notes',
            ]);
        });

        Schema::table('material_stocks', function (Blueprint $table) {
            $table->foreign('project_id')->references('id')->on('projects')->cascadeOnDelete();
            $table->foreign('material_id')->references('id')->on('materials')->cascadeOnDelete();
            $table->unique(['project_id', 'material_id']);
        });
    }
};
