<?php

namespace App\Models;

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

class Repayment extends Model
{
    use HasFactory;

    protected $table = 'repayments';
    protected $primaryKey = 'id';

    protected $fillable = [
        'customerid', 'rpid', 'rloanid', 'rtotal', 'rinterest', 'rprincipal',
        'rdate', 'status', 'pmethod', 'transtype'
    ];

    protected $casts = [
        'rdate' => 'datetime',
        'rtotal' => 'decimal:2',
        'rinterest' => 'decimal:2',
        'rprincipal' => 'decimal:2',
    ];

    /**
     * Relationship with Loan
     */
    public function loan()
    {
        return $this->belongsTo(Loan::class, 'rloanid', 'loanid');
    }

    /**
     * Relationship with Customer
     */
    public function customer()
    {
        return $this->belongsTo(Customer::class, 'customerid', 'id');
    }

    /**
     * Scope for successful repayments
     */
    public function scopeSuccessful($query)
    {
        return $query->where('status', 'completed')->orWhere('transtype', 'repayment');
    }
}