<?php

namespace App\Models;

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

class LoanGuarantor extends Model
{
    protected $fillable = [
        'loan_id',
        'guarantor_user_id',
        'guarantee_amount',
        'relationship_type',
        'relationship_details',
        'status',
        'approval_notes',
        'approved_at',
        'approved_by',
    ];

    protected $casts = [
        'guarantee_amount' => 'decimal:2',
        'approved_at' => 'datetime',
    ];

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

    public function guarantor(): BelongsTo
    {
        return $this->belongsTo(User::class, 'guarantor_user_id');
    }

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

    public function getRelationshipLabelAttribute()
    {
        return match($this->relationship_type) {
            'family' => 'Family Member',
            'friend' => 'Friend',
            'colleague' => 'Colleague',
            'other' => 'Other',
            default => ucfirst($this->relationship_type)
        };
    }

    public function getStatusColorAttribute()
    {
        return match($this->status) {
            'approved' => 'success',
            'pending' => 'warning',
            'rejected' => 'danger',
            default => 'secondary'
        };
    }

    public function scopeEligible($query)
    {
        return $query->whereHas('guarantor.membership', function($q) {
            $q->where('created_at', '<=', now()->subMonths(3))
              ->whereHas('user.savings', function($sq) {
                  $sq->where('status', 'active');
              });
        });
    }
}
