<?php

namespace portalpeople\invoicing\traits;

/**
 * Credit Note Trait
 *
 * Provides methods for managing credit notes associated with invoices.
 */
trait CreditNoteTrait
{
    /**
     * Get credit notes for this invoice
     *
     * @return \yii\db\ActiveQuery
     */
    public function getCreditNotes()
    {
        return $this->hasMany(\portalpeople\invoicing\models\CreditNote::class, ['invoice_id' => 'id']);
    }

    /**
     * Get total amount of credit notes
     *
     * @return float
     */
    public function getTotalCreditAmount(): float
    {
        return (float) $this->getCreditNotes()->sum('amount') ?? 0;
    }

    /**
     * Get invoice balance (total - credit notes)
     *
     * @return float
     */
    public function getInvoiceBalance(): float
    {
        return $this->total - $this->getTotalCreditAmount();
    }

    /**
     * Check if invoice can have credit note added
     *
     * @return bool
     */
    public function canAddCreditNote(): bool
    {
        return $this->getTotalCreditAmount() < $this->total;
    }
}
