<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Modules\Billing\Enums\BillPayStatusEnum;
use Modules\Inventory\Enums\PurchaseStatusEnum;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('purchase_invoices', function (Blueprint $table) {
            $table->id();
            $table->foreignId('fiscal_year_id')->constrained('fiscal_years');
            $table->foreignId('accounting_period_id')->constrained('accounting_periods');
            $table->foreignId('purchase_requisition_id')->constrained()->cascadeOnDelete();
            $table->string('invoice_no')->unique();

            $table->foreignId('supplier_id')->constrained();
            $table->foreignId('voucher_id')->nullable()->constrained('account_vouchers')->nullOnDelete();

            $table->date('invoice_date');

            $table->decimal('subtotal', 20, 2)->default(0);
            $table->decimal('total_discount', 20, 2)->default(0);
            $table->decimal('taxable_amount', 20, 2)->default(0);
            $table->decimal('total_vat', 20, 2)->default(0);
            $table->decimal('rounding_adjustment', 20, 2)->default(0);
            $table->decimal('grand_total', 20, 2)->default(0);

            $table->decimal('paid_amount', 20, 2)->default(0);
            $table->decimal('due_amount', 20, 2)->default(0);
            $table->enum('payment_status', BillPayStatusEnum::casesAsArray())->default(BillPayStatusEnum::UNPAID->value);

            $table->boolean('is_posted')->default(false);
            $table->enum('status', PurchaseStatusEnum::casesAsArray())
                ->default(PurchaseStatusEnum::DRAFT->value);
            $table->text('note')->nullable();

            $table->timestamp('submitted_at')->nullable();
            $table->timestamp('approved_at')->nullable();
            $table->timestamp('rejected_at')->nullable();
            $table->timestamp('posted_at')->nullable();
            $table->foreignId('posted_by')->nullable()->constrained('users')->nullOnDelete();
            $table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
            $table->foreignId('updated_by')->nullable()->constrained('users')->nullOnDelete();

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

            $table->index([
                'invoice_date',
                'supplier_id'
            ]);

            $table->index([
                'status',
                'payment_status'
            ]);
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('purchase_invoices');
    }
};
