<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;

class LoanProduct extends Model
{
    use HasFactory;

    public const PROCESSING_FEE_PAYMENT_MODES = [
        'cash' => 'Paid cash upfront',
        'deducted' => 'Deduct from disbursement',
        'financed' => 'Include in loan repayments',
    ];

    protected $fillable = [
        'business_id','name','minimum_amount','maximum_amount','duration','duration_unit','interest_rate',
        'interest_calculation_method','fixed_interest_amount','repayment_frequency','grace_period_days',
        'late_payment_penalty_type','late_payment_penalty_value','processing_fee_type','processing_fee_value','processing_fee_payment_mode',
        'insurance_fee_type','insurance_fee_value','other_charges','collateral_required','guarantor_required',
        'payment_deadline_enabled','payment_deadline_time','status','created_by','updated_by',
    ];

    protected function casts(): array
    {
        return [
            'minimum_amount'=>'decimal:2','maximum_amount'=>'decimal:2','interest_rate'=>'decimal:6',
            'fixed_interest_amount'=>'decimal:2','late_payment_penalty_value'=>'decimal:6',
            'processing_fee_value'=>'decimal:6','insurance_fee_value'=>'decimal:6','other_charges'=>'decimal:2',
            'collateral_required'=>'boolean','guarantor_required'=>'boolean','payment_deadline_enabled'=>'boolean',
            'duration'=>'integer','grace_period_days'=>'integer',
        ];
    }

    public function processingFeePaymentModeLabel(): string
    {
        return self::PROCESSING_FEE_PAYMENT_MODES[$this->processing_fee_payment_mode ?: 'financed'] ?? 'Include in loan repayments';
    }

    public function business(): BelongsTo { return $this->belongsTo(Business::class); }
    public function branches(): BelongsToMany { return $this->belongsToMany(Branch::class, 'branch_loan_product'); }
    public function creator(): BelongsTo { return $this->belongsTo(User::class, 'created_by'); }
    public function loans(): HasMany { return $this->hasMany(Loan::class); }
}
