<?php

namespace App\Models;

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

class Transaction extends Model
{
    protected $fillable = [
        'member_id',
        'transaction_reference',
        'transaction_type',
        'contribution_type',
        'amount',
        'balance_before',
        'balance_after',
        'payment_method',
        'mpesa_receipt',
        'description',
        'transaction_date',
        'recorded_by'
    ];
    
    protected $casts = [
        'transaction_date' => 'date',
        'amount' => 'decimal:2',
        'balance_before' => 'decimal:2',
        'balance_after' => 'decimal:2'
    ];
    
    public function member(): BelongsTo
    {
        return $this->belongsTo(Member::class);
    }
    
    public function recorder(): BelongsTo
    {
        return $this->belongsTo(User::class, 'recorded_by');
    }
    
    public function getFormattedAmountAttribute()
    {
        return 'TSH ' . number_format($this->amount, 2);
    }
    
    public function getTypeBadgeAttribute()
    {
        $types = [
            'contribution' => 'success',
            'withdrawal' => 'warning',
            'loan_payment' => 'primary',
            'dividend' => 'info',
            'fee' => 'danger'
        ];
        
        return '<span class="badge bg-'.$types[$this->transaction_type].'">'
              . ucfirst(str_replace('_', ' ', $this->transaction_type))
              . '</span>';
    }
}