<?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
    {
        // 1. Update products table
        Schema::table('products', function (Blueprint $table) {
            if (!Schema::hasColumn('products', 'stock')) {
                $table->decimal('stock', 15, 2)->default(0)->after('price');
            }
            if (!Schema::hasColumn('products', 'min_stock')) {
                $table->decimal('min_stock', 15, 2)->default(0)->after('stock');
            }
            if (!Schema::hasColumn('products', 'code')) {
                $table->string('code')->nullable()->unique()->after('name');
            }
        });

        // 2. Update invoice_items table
        Schema::table('invoice_items', function (Blueprint $table) {
            if (!Schema::hasColumn('invoice_items', 'product_id')) {
                $table->foreignId('product_id')->nullable()->after('invoice_id')->constrained('products')->nullOnDelete();
            }
        });

        // 3. Create bill_items table
        if (!Schema::hasTable('bill_items')) {
            Schema::create('bill_items', function (Blueprint $table) {
                $table->id();
                $table->foreignId('bill_id')->constrained('bills')->onDelete('cascade');
                $table->foreignId('product_id')->nullable()->constrained('products')->nullOnDelete();
                $table->string('description');
                $table->decimal('quantity', 15, 2);
                $table->decimal('unit_price', 15, 2);
                $table->decimal('total', 15, 2);
                $table->timestamps();
            });
        }
    }

    public function down(): void
    {
        Schema::dropIfExists('bill_items');

        Schema::table('invoice_items', function (Blueprint $table) {
            $table->dropForeign(['product_id']);
            $table->dropColumn('product_id');
        });

        Schema::table('products', function (Blueprint $table) {
            $table->dropColumn(['stock', 'min_stock', 'code']);
        });
    }
};
