<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class LedgerEntry extends Model
{
    use HasFactory;

    protected $fillable = [
        'ledger_transaction_id',
        'account_id',
        'entry_type',
        'amount',
        'currency',
        'description',
        'metadata',
    ];

    protected $casts = [
        'amount' => 'decimal:8',
        'metadata' => 'array',
    ];

    // Relationship with ledger transaction
    public function ledgerTransaction()
    {
        return $this->belongsTo(LedgerTransaction::class, 'ledger_transaction_id');
    }

    // Scope for debit entries
    public function scopeDebit($query)
    {
        return $query->where('entry_type', 'debit');
    }

    // Scope for credit entries
    public function scopeCredit($query)
    {
        return $query->where('entry_type', 'credit');
    }

    // Scope for entries by account
    public function scopeForAccount($query, $accountId)
    {
        return $query->where('account_id', $accountId);
    }

    // Scope for entries by currency
    public function scopeForCurrency($query, $currency)
    {
        return $query->where('currency', $currency);
    }

    // Check if entry is a debit
    public function isDebit()
    {
        return $this->entry_type === 'debit';
    }

    // Check if entry is a credit
    public function isCredit()
    {
        return $this->entry_type === 'credit';
    }

    // Get the sign multiplier (-1 for debit, +1 for credit)
    public function getSignMultiplier()
    {
        return $this->isDebit() ? -1 : 1;
    }

    // Get the effective amount considering the entry type
    public function getEffectiveAmount()
    {
        return $this->getSignMultiplier() * $this->amount;
    }
}