<?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
    {
        // Add payment_term_id to sales orders
        Schema::table('core_sales_orders', function (Blueprint $table) {
            if (! Schema::hasColumn('core_sales_orders', 'payment_term_id')) {
                $table->foreignId('payment_term_id')
                    ->nullable()
                    ->after('customer_id')
                    ->constrained('core_payment_terms')
                    ->nullOnDelete();
            }
        });

        // Add payment_term_id to purchase orders
        Schema::table('core_purchase_orders', function (Blueprint $table) {
            if (! Schema::hasColumn('core_purchase_orders', 'payment_term_id')) {
                $table->foreignId('payment_term_id')
                    ->nullable()
                    ->after('supplier_id')
                    ->constrained('core_payment_terms')
                    ->nullOnDelete();
            }
        });
    }

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

        Schema::table('core_purchase_orders', function (Blueprint $table) {
            if (Schema::hasColumn('core_purchase_orders', 'payment_term_id')) {
                $table->dropForeign(['payment_term_id']);
                $table->dropColumn('payment_term_id');
            }
        });
    }
};
