<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class SavingsTransaction extends Model
{
    protected $fillable = [
        'saving_id',
        'type',
        'amount',
        'balance_before',
        'balance_after',
        'transaction_number',
        'notes',
        'processed_by',
        'transaction_date',
    ];

    protected $casts = [
        'amount' => 'decimal:2',
        'balance_before' => 'decimal:2',
        'balance_after' => 'decimal:2',
        'transaction_date' => 'datetime',
    ];

    public function account(): BelongsTo
    {
        return $this->belongsTo(Saving::class, 'saving_id');
    }

    public function processor(): BelongsTo
    {
        return $this->belongsTo(User::class, 'processed_by');
    }

    public function getTypeLabelAttribute()
    {
        return match($this->type) {
            'deposit' => 'Deposit',
            'withdrawal' => 'Withdrawal',
            default => ucfirst($this->type)
        };
    }

    public function getTypeColorAttribute()
    {
        return match($this->type) {
            'deposit' => 'success',
            'withdrawal' => 'danger',
            default => 'secondary'
        };
    }

    public function getFormattedAmountAttribute()
    {
        $prefix = $this->type === 'withdrawal' ? '-' : '+';
        return $prefix . 'KSh ' . number_format($this->amount, 2);
    }
}
