<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Traits\Auditable;

class Transaction extends Model
{
    use HasFactory, Auditable;

    protected $fillable = [
        'voucher_no', 'user_id', 'date', 'details', 'type',
        'payment_method', 'bank_account_id', 'digital_payment_id',
        'expense_type_id', 'amount', 'balance_before', 'balance_after',
        'reference', 'notes'
    ];

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

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function bankAccount()
    {
        return $this->belongsTo(BankAccount::class);
    }

    public function digitalPayment()
    {
        return $this->belongsTo(DigitalPayment::class);
    }

    public function expenseType()
    {
        return $this->belongsTo(ExpenseType::class);
    }

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($transaction) {
            $transaction->voucher_no = 'VOU-' . date('Ymd') . '-' . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
        });
    }
}
