<?php

namespace App\Models\Tenants;

use App\Traits\Auditable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class BillInstallment extends Model
{
    use Auditable;

    protected $fillable = [
        'bill_id',
        'type',
        'installment_date',
        'amount',
        'counterparty',
        'note',
        'created_by',
    ];

    protected $casts = [
        'installment_date' => 'date',
        'amount' => 'decimal:2',
        'bill_id' => 'integer',
    ];

    /**
     * 배열/JSON 변환 시 날짜 형식 지정
     */
    public function toArray(): array
    {
        $array = parent::toArray();

        if (isset($array['installment_date']) && $this->installment_date) {
            $array['installment_date'] = $this->installment_date->format('Y-m-d');
        }

        return $array;
    }

    /**
     * 어음 관계
     */
    public function bill(): BelongsTo
    {
        return $this->belongsTo(Bill::class);
    }

    /**
     * 생성자 관계
     */
    public function creator(): BelongsTo
    {
        return $this->belongsTo(\App\Models\Members\User::class, 'created_by');
    }
}
