<?php

namespace App\Models;

use App\Models\Scopes\ParentBranchScope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;

class LoanInstallment extends Model
{
    protected $fillable = [
        'loan_id','schedule_version','is_active','loan_restructuring_id','installment_number','principal','interest','fees','amount_due','due_date','amount_paid','remaining','status',
        'principal_paid','interest_paid','fees_paid','penalty_due','penalty_paid',
    ];

    protected function casts(): array
    {
        return [
            'schedule_version'=>'integer','is_active'=>'boolean','principal'=>'decimal:2','interest'=>'decimal:2','fees'=>'decimal:2','amount_due'=>'decimal:2','amount_paid'=>'decimal:2',
            'remaining'=>'decimal:2','principal_paid'=>'decimal:2','interest_paid'=>'decimal:2','fees_paid'=>'decimal:2',
            'penalty_due'=>'decimal:2','penalty_paid'=>'decimal:2','due_date'=>'date',
        ];
    }

    protected static function booted(): void
    {
        static::addGlobalScope(new ParentBranchScope('loans', 'loan_id'));
    }

    public function loan(): BelongsTo { return $this->belongsTo(Loan::class); }
    public function restructuring(): BelongsTo { return $this->belongsTo(LoanRestructuring::class, 'loan_restructuring_id'); }
    public function paymentAllocations(): HasMany { return $this->hasMany(LoanPaymentAllocation::class); }
    public function penaltyCharges(): HasMany { return $this->hasMany(LoanPenaltyCharge::class)->orderBy('effective_date')->orderBy('id'); }
    public function excuse(): HasOne { return $this->hasOne(LoanInstallmentExcuse::class); }
}
