<?php

namespace App\Models;

use App\Traits\ModelCounterTrait;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Credit extends Model
{
    use HasFactory, SoftDeletes, ModelCounterTrait;

    protected $fillable = [
        'lender_id',
        'code',
        'type',
        'amount',
        'date',
        'due_date',
        'attachment',
        'is_valid',
        'validation_date',
        'total_repayments',
    ];

    // Relationship with Lender
    public function lender()
    {
        return $this->belongsTo(Lender::class);
    }

    // Relationship with Repayment
    public function repayments()
    {
        return $this->hasMany(Repayment::class);
    }

    public static function booted(): void {
        static::creating(function(Credit $credit) {
            $credit->code = $credit->codeGenerator([
                "prefix" => "CRD",
                "model" => "Credit",
                "length" => 5,
            ]);
        });
    }
}
