<?php

namespace App\Models;

use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class LoanProduct extends Model
{
    use BelongsToTenant;

    protected $fillable = [
        'tenant_id',
        'name',
        'description',
        'loan_number_prefix',
        'interest_rate',
        'interest_method',
        'repayment_frequency',
        'term_value',
        'term_unit',
        'term_days',
        'penalty_type',
        'penalty_rate',
        'processing_fee_type',
        'processing_fee_value',
        'processing_fee_timing',
        'minimum_amount',
        'maximum_amount',
        'guarantor_requirement',
        'collateral_requirement',
        'show_on_member_portal',
        'show_on_public_website',
        'is_active',
    ];

    protected function casts(): array
    {
        return [
            'interest_rate' => 'decimal:2',
            'term_value' => 'integer',
            'penalty_rate' => 'decimal:2',
            'processing_fee_value' => 'decimal:2',
            'minimum_amount' => 'decimal:2',
            'maximum_amount' => 'decimal:2',
            'show_on_member_portal' => 'boolean',
            'show_on_public_website' => 'boolean',
            'is_active' => 'boolean',
        ];
    }

    public const PROCESSING_FEE_TIMINGS = [
        'before_disbursement' => 'Collect before disbursement',
        'deduct_from_disbursement' => 'Deduct from disbursement',
    ];

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

    public function processingFeeTimingLabel(): string
    {
        return self::PROCESSING_FEE_TIMINGS[$this->processing_fee_timing] ?? str($this->processing_fee_timing ?? 'before_disbursement')->headline()->toString();
    }
}
