<?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 = [
        'partner_id',
        'customer_id',
        'scheme_id',
        'loan_scheme_id',
        'loan_number',
        'principal_amount',
        'interest_rate',
        'processing_fee',
        'insurance_fee',
        'other_fee',
        'interest_amount',
        'duration_type',
        'duration_value',
        'monthly_installment',
        'total_amount',
        'paid_amount',
        'remaining_amount',
        'disbursement_date',
        'due_date',
        'maturity_date',
        'status',
        'notes',
    ];

    protected function casts(): array
    {
        return [
            'principal_amount' => 'decimal:2',
            'interest_rate' => 'decimal:2',
            'processing_fee' => 'decimal:2',
            'insurance_fee' => 'decimal:2',
            'other_fee' => 'decimal:2',
            'interest_amount' => 'decimal:2',
            'monthly_installment' => 'decimal:2',
            'total_amount' => 'decimal:2',
            'paid_amount' => 'decimal:2',
            'remaining_amount' => 'decimal:2',
            'disbursement_date' => 'date',
            'due_date' => 'date',
            'maturity_date' => 'date',
        ];
    }

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

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

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

    public function loanScheme(): BelongsTo
    {
        return $this->belongsTo(LoanScheme::class, 'loan_scheme_id');
    }

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

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

    public function isOverdue(): bool
    {
        return $this->due_date < now() && $this->status === 'active';
    }

    public function getDurationDisplayAttribute(): string
    {
        return $this->duration_value . ' ' . ucfirst($this->duration_type);
    }

    public function getInstallmentLabelAttribute(): string
    {
        return match($this->duration_type) {
            'daily' => 'Daily Installment',
            'weekly' => 'Weekly Installment',
            'monthly' => 'Monthly Installment',
        };
    }
}
