<?php

namespace App\Models;

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

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

    protected $fillable = [
        'restructuring_number','loan_id','branch_id','previous_schedule_version','new_schedule_version','principal_outstanding',
        'interest_outstanding','fees_outstanding','penalties_outstanding','total_outstanding','previous_schedule','new_schedule',
        'reason','status','requested_by','requested_at','approved_by','approved_at','rejected_by','rejected_at','decision_comments',
    ];

    protected function casts(): array
    {
        return [
            'previous_schedule_version'=>'integer','new_schedule_version'=>'integer','principal_outstanding'=>'decimal:2',
            'interest_outstanding'=>'decimal:2','fees_outstanding'=>'decimal:2','penalties_outstanding'=>'decimal:2','total_outstanding'=>'decimal:2',
            'previous_schedule'=>'array','new_schedule'=>'array','requested_at'=>'datetime','approved_at'=>'datetime','rejected_at'=>'datetime',
        ];
    }

    public function loan(): BelongsTo { return $this->belongsTo(Loan::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(LoanRestructuringDocument::class)->orderBy('id'); }
}
