<?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 Loan extends Model
{
    use HasFactory, softDeletes, ModelCounterTrait;

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

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

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

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