<?php

namespace App\Models;

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

class LoanWriteOff extends Model
{
    public const STATUSES = ['pending', 'approved', 'rejected'];

    protected $fillable = [
        'write_off_number','loan_id','customer_id','branch_id','original_principal','original_total_repayment',
        'principal_outstanding','interest_outstanding','fees_outstanding','penalties_outstanding','write_off_amount',
        'recovered_amount','recoverable_balance','reason','status','accounting_journal_number',
        'requested_by','requested_at','approved_by','approved_at','rejected_by','rejected_at','decision_comments',
    ];

    protected function casts(): array
    {
        return [
            'original_principal'=>'decimal:2','original_total_repayment'=>'decimal:2',
            'principal_outstanding'=>'decimal:2','interest_outstanding'=>'decimal:2','fees_outstanding'=>'decimal:2',
            'penalties_outstanding'=>'decimal:2','write_off_amount'=>'decimal:2','recovered_amount'=>'decimal:2',
            'recoverable_balance'=>'decimal:2','requested_at'=>'datetime','approved_at'=>'datetime','rejected_at'=>'datetime',
        ];
    }

    public function loan(): BelongsTo { return $this->belongsTo(Loan::class); }
    public function customer(): BelongsTo { return $this->belongsTo(Customer::class); }
    public function branch(): BelongsTo { return $this->belongsTo(Branch::class); }
    public function requester(): BelongsTo { return $this->belongsTo(User::class, 'requested_by'); }
    public function approver(): BelongsTo { return $this->belongsTo(User::class, 'approved_by'); }
    public function rejecter(): BelongsTo { return $this->belongsTo(User::class, 'rejected_by'); }
    public function documents(): HasMany { return $this->hasMany(LoanWriteOffDocument::class)->orderBy('id'); }
    public function recoveries(): HasMany { return $this->hasMany(LoanWriteOffRecovery::class)->orderByDesc('recovery_date')->orderByDesc('id'); }
}
