<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Loan extends Model
{
    protected $fillable = [
        'user_id',
        'amount',
        'paid_amount',
        'interest_rate',
        'term_months',
        'application_date',
        'return_date',
        'status',
        'approved_at',
        'notes',
    ];

    protected $casts = [
        'amount' => 'decimal:2',
        'paid_amount' => 'decimal:2',
        'interest_rate' => 'decimal:2',
        'application_date' => 'date',
        'return_date' => 'date',
        'approved_at' => 'datetime',
    ];

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

    public function repayments(): HasMany
    {
        return $this->hasMany(Transaction::class)->where('type', 'loan_repayment');
    }

    public function getTotalAmountAttribute()
    {
        return $this->amount + ($this->amount * $this->interest_rate / 100);
    }

    public function getTermMonthsAttribute()
    {
        if ($this->application_date && $this->return_date) {
            return ceil($this->application_date->diffInMonths($this->return_date));
        }
        return $this->attributes['term_months'] ?? 0; // Fallback to stored value if dates not set
    }

    public function getMonthlyPaymentAttribute()
    {
        $termMonths = $this->term_months;
        if ($termMonths > 0) {
            return $this->total_amount / $termMonths;
        }
        return 0;
    }

    public function getBalanceAttribute()
    {
        return $this->total_amount - $this->paid_amount;
    }

    public function guarantees(): HasMany
    {
        return $this->hasMany(LoanGuarantee::class);
    }

    public function activeGuarantee()
    {
        return $this->hasOne(LoanGuarantee::class)->whereIn('status', ['approved', 'pending']);
    }
}
