<?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
    {
        Schema::create('purchases', function (Blueprint $t) {
            $t->id();
            $t->foreignId('company_id')->constrained()->cascadeOnDelete();
            $t->string('number', 32);                          // P-26-0001
            $t->foreignId('supplier_id')->nullable()->constrained()->nullOnDelete();
            $t->date('order_date')->default(now());
            $t->date('expected_at')->nullable();
            $t->date('received_at')->nullable();
            $t->date('paid_at')->nullable();
            $t->string('status')->default('draft');            // draft / ordered / received / cancelled
            $t->decimal('total', 12, 2)->default(0);
            $t->text('notes')->nullable();

            $t->timestamps();
            $t->softDeletes();

            $t->unique(['company_id', 'number']);
            $t->index(['company_id', 'status']);
            $t->index(['company_id', 'order_date']);
        });

        Schema::create('purchase_items', function (Blueprint $t) {
            $t->id();
            $t->foreignId('company_id')->constrained()->cascadeOnDelete();
            $t->foreignId('purchase_id')->constrained()->cascadeOnDelete();
            $t->foreignId('part_id')->nullable()->constrained()->nullOnDelete();

            $t->string('name');
            $t->string('article', 64)->nullable();
            $t->decimal('qty', 10, 2)->default(1);
            $t->string('unit', 16)->default('buc');
            $t->decimal('buy_price', 10, 2)->default(0);
            $t->decimal('total', 12, 2)->default(0);
            $t->boolean('received')->default(false);

            $t->timestamps();

            $t->index(['company_id', 'purchase_id']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('purchase_items');
        Schema::dropIfExists('purchases');
    }
};
