<?php

namespace PortalPeople\creditnotes\traits;

/**
 * Credit Note Trait
 *
 * Provides methods for managing credit notes associated with a parent entity (invoice, subscription, etc).
 */
trait HasCreditNotesTrait
{
    /**
     * Get credit notes for this entity
     *
     * @return \yii\db\ActiveQuery
     */
    public function getCreditNotes()
    {
        return $this->hasMany(\PortalPeople\creditnotes\models\CreditNote::class, ['entity_id' => 'id'])
            ->andWhere(['entity_type' => static::class]);
    }

    /**
     * Get total amount of credit notes
     *
     * @return float
     */
    public function getTotalCreditAmount(): float
    {
        return (float) $this->getCreditNotes()
            ->where(['status' => \PortalPeople\creditnotes\models\CreditNote::STATUS_ISSUED])
            ->sum('amount') ?? 0;
    }

    /**
     * Get entity balance (total - credit notes)
     *
     * Requires entity to have a 'total' or 'amount' attribute.
     *
     * @return float
     */
    public function getBalance(): float
    {
        $total = $this->total ?? $this->amount ?? 0;
        return $total - $this->getTotalCreditAmount();
    }

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