<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up()
    {
        Schema::table('purchases', function (Blueprint $table) {
            // Check if columns exist before adding them
            if (!Schema::hasColumn('purchases', 'is_credit_purchase')) {
                $table->boolean('is_credit_purchase')->default(false)->after('created_by');
            }
            
            if (!Schema::hasColumn('purchases', 'due_date')) {
                $table->date('due_date')->nullable()->after('is_credit_purchase');
            }
            
            if (!Schema::hasColumn('purchases', 'discount_amount')) {
                $table->decimal('discount_amount', 10, 2)->default(0)->after('subtotal');
            }
            
            if (!Schema::hasColumn('purchases', 'shipping_charges')) {
                $table->decimal('shipping_charges', 10, 2)->default(0)->after('tax_amount');
            }
            
            if (!Schema::hasColumn('purchases', 'payment_notes')) {
                $table->text('payment_notes')->nullable()->after('payment_method');
            }
            
            if (!Schema::hasColumn('purchases', 'updated_by')) {
                $table->unsignedBigInteger('updated_by')->nullable()->after('created_by');
                $table->foreign('updated_by')->references('id')->on('users')->onDelete('set null');
            }
        });
    }

    public function down()
    {
        Schema::table('purchases', function (Blueprint $table) {
            // Drop the columns if they exist
            $columns = ['is_credit_purchase', 'due_date', 'discount_amount', 
                       'shipping_charges', 'payment_notes', 'updated_by'];
            
            foreach ($columns as $column) {
                if (Schema::hasColumn('purchases', $column)) {
                    $table->dropColumn($column);
                }
            }
        });
    }
};