<?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::create('purchase_order_details', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('purchase_order_id');
            $table->foreign('purchase_order_id')->references('id')->on('purchase_orders')->onDelete('cascade');
            $table->unsignedBigInteger('purchase_requisition_id')->nullable();
            $table->unsignedBigInteger('purchase_requisition_detail_id')->nullable();
            $table->unsignedBigInteger('item_id');
            $table->foreign('item_id')->references('id')->on('items')->onDelete('restrict');
            $table->unsignedBigInteger('unit');
            $table->foreign('unit')->references('id')->on('item_units')->onDelete('restrict');
            $table->decimal('qty', 25, 3);
            $table->decimal('price', 20, 2);
            $table->decimal('discount', 20, 2)->default(0.00);
            $table->decimal('subtotal', 20, 2);
            $table->string('base_unit');
            $table->decimal('base_qty', 20, 3);
            $table->decimal('qty_left', 25, 3);
            $table->decimal('add_tax_detail', 20, 2)->nullable();
            $table->text('description')->nullable();
            $table->boolean('is_cancel')->nullable();
            $table->text('cancel_notes')->nullable();
            $table->datetime('canceled_at')->nullable();
            $table->unsignedBigInteger('canceled_by')->nullable();
            $table->timestamps();
            $table->unsignedBigInteger('created_by')->nullable();
            $table->unsignedBigInteger('updated_by')->nullable();

            $table->foreign('purchase_requisition_id')->references('id')->on('purchase_requisitions')->onDelete('restrict');
            $table->foreign('purchase_requisition_detail_id')->references('id')->on('purchase_requisition_details')->onDelete('restrict');
            $table->foreign('canceled_by')->references('id')->on('users')->onDelete('restrict');
            $table->foreign('created_by')->references('id')->on('users')->onDelete('restrict');
            $table->foreign('updated_by')->references('id')->on('users')->onDelete('restrict');
            $table->foreign(['item_id','base_qty'])->references(['item_id','conversion'])->on('item_details')->onDelete('restrict');
        });
    }

    public function down()
    {
        Schema::dropIfExists('purchase_order_details');
    }
};
