<?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('purchases', function (Blueprint $table) {
            if (!Schema::hasColumn('purchases', 'attachment')) {
                $table->string('attachment')->nullable()->after('challan_no');
            }
        });

        Schema::table('purchase_items', function (Blueprint $table) {
            if (!Schema::hasColumn('purchase_items', 'manufacturer_id')) {
                $table->foreignId('manufacturer_id')->nullable()->constrained('manufacturers')->onDelete('set null');
            }
            if (!Schema::hasColumn('purchase_items', 'brand_id')) {
                $table->foreignId('brand_id')->nullable()->constrained('brands')->onDelete('set null');
            }
            if (!Schema::hasColumn('purchase_items', 'unit_id')) {
                $table->foreignId('unit_id')->nullable()->constrained('units')->onDelete('set null');
            }
        });
    }

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

        Schema::table('purchase_items', function (Blueprint $table) {
            $table->dropForeign(['manufacturer_id']);
            $table->dropForeign(['brand_id']);
            $table->dropForeign(['unit_id']);
            $table->dropColumn(['manufacturer_id', 'brand_id', 'unit_id']);
        });
    }
};
