<?php

namespace App\Models;

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

class Loan extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'user_account_id',
        'lender_name',
        'loan_no',
        'principal_amount',
        'remaining_amount',
        'interest_rate',
        'start_date',
        'status',
        'closed_at',
        'note',
    ];

    protected $casts = [
        'principal_amount' => 'decimal:2',
        'remaining_amount' => 'decimal:2',
        'interest_rate'    => 'decimal:4',
        'start_date'       => 'date',
        'closed_at'        => 'datetime',
    ];

    public function account()
    {
        return $this->belongsTo(UserAccount::class, 'user_account_id');
    }

    public function payments()
    {
        return $this->hasMany(LoanPayment::class);
    }

    public function latestPayment()
    {
        return $this->hasOne(LoanPayment::class)->latestOfMany('paid_at');
    }
}