<?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('payments', function (Blueprint $t) {
            $t->id();
            $t->foreignId('company_id')->constrained()->cascadeOnDelete();
            $t->foreignId('client_id')->nullable()->constrained()->nullOnDelete();
            $t->foreignId('work_order_id')->nullable()->constrained()->nullOnDelete();
            $t->foreignId('user_id')->nullable()->constrained()->nullOnDelete(); // operator înregistrare

            $t->date('paid_at')->default(now());
            $t->decimal('amount', 12, 2);
            $t->string('method')->default('cash');     // cash / card / transfer / mobile
            $t->string('reference')->nullable();        // nr. chitanță / tranzacție
            $t->text('notes')->nullable();

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

            $t->index(['company_id', 'paid_at']);
            $t->index(['company_id', 'work_order_id']);
            $t->index(['company_id', 'method']);
        });

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

            $t->date('paid_at')->default(now());
            $t->string('category');                     // salary / purchase / rent / utilities / advance / tax / other
            $t->string('name');                          // descriere
            $t->decimal('amount', 12, 2);
            $t->string('method')->default('cash');
            $t->string('reference')->nullable();
            $t->text('notes')->nullable();

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

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

    public function down(): void
    {
        Schema::dropIfExists('expenses');
        Schema::dropIfExists('payments');
    }
};
