<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Loan extends Model
{
    protected $fillable = [
        'loan_type_id','user_id','group_id','principal','interest_rate',
        'total_payable','balance','status','approved_by','approved_at','amortization_schedule','admin_notes'
    ];

  protected $casts = [
    'approved_at' => 'datetime',
    'disbursed_at' => 'datetime',
    'created_at' => 'datetime',
    'updated_at' => 'datetime',
    'amortization_schedule' => 'array',
];


    public function loanType()
    {
        return $this->belongsTo(LoanType::class);
    }

public function repayments()
{
    return $this->hasMany(\App\Models\IndividualLoanRepayment::class);
}



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

    public function group()
    {
        return $this->belongsTo(\App\Models\Group::class);
    }

    public function approvedBy()
    {
        return $this->belongsTo(\App\Models\User::class, 'approved_by');
    }

    // helper to compute outstanding (if not stored)
    public function outstanding(): float
    {
        return floatval($this->balance ?? $this->total_payable ?? 0);
    }
}
