<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    protected $connection = 'sam_stat';

    public function up(): void
    {
        Schema::connection($this->connection)->create('stat_finance_daily', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('tenant_id');
            $table->date('stat_date');

            // 입출금
            $table->unsignedInteger('deposit_count')->default(0);
            $table->decimal('deposit_amount', 18, 2)->default(0);
            $table->unsignedInteger('withdrawal_count')->default(0);
            $table->decimal('withdrawal_amount', 18, 2)->default(0);
            $table->decimal('net_cashflow', 18, 2)->default(0)->comment('입금 - 출금');

            // 매입
            $table->unsignedInteger('purchase_count')->default(0);
            $table->decimal('purchase_amount', 18, 2)->default(0);
            $table->decimal('purchase_tax_amount', 18, 2)->default(0);

            // 미수/미지급
            $table->decimal('receivable_balance', 18, 2)->default(0)->comment('미수금 잔액');
            $table->decimal('payable_balance', 18, 2)->default(0)->comment('미지급 잔액');
            $table->decimal('overdue_receivable', 18, 2)->default(0)->comment('연체 미수금');

            // 어음
            $table->unsignedInteger('bill_issued_count')->default(0);
            $table->decimal('bill_issued_amount', 18, 2)->default(0);
            $table->unsignedInteger('bill_matured_count')->default(0);
            $table->decimal('bill_matured_amount', 18, 2)->default(0);

            // 카드
            $table->unsignedInteger('card_transaction_count')->default(0);
            $table->decimal('card_transaction_amount', 18, 2)->default(0);

            // 은행
            $table->decimal('bank_balance_total', 18, 2)->default(0)->comment('전 계좌 잔액 합계');

            $table->timestamps();

            $table->unique(['tenant_id', 'stat_date'], 'uk_tenant_date');
            $table->index('stat_date');
        });
    }

    public function down(): void
    {
        Schema::connection($this->connection)->dropIfExists('stat_finance_daily');
    }
};
