<?php

namespace App\Models;

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

class LoanReschedule extends Model
{
    use HasFactory;

    protected $fillable = [
        'loan_id',
        'reschedule_type',
        'old_amount',
        'new_amount',
        'old_duration',
        'new_duration',
        'old_interest_rate',
        'new_interest_rate',
        'reschedule_date',
        'reason',
        'status',
        'approved_by',
        'approved_at',
        'approval_notes',
    ];

    protected $casts = [
        'old_amount' => 'decimal:2',
        'new_amount' => 'decimal:2',
        'old_interest_rate' => 'decimal:2',
        'new_interest_rate' => 'decimal:2',
        'reschedule_date' => 'date',
        'approved_at' => 'datetime',
    ];

    public function loan(): BelongsTo
    {
        return $this->belongsTo(Loan::class);
    }

    public function approver(): BelongsTo
    {
        return $this->belongsTo(User::class, 'approved_by');
    }

    public function isPending(): bool
    {
        return $this->status === 'pending';
    }

    public function isApproved(): bool
    {
        return $this->status === 'approved';
    }

    public function isRejected(): bool
    {
        return $this->status === 'rejected';
    }

    public function approve(User $user, string $notes = null): void
    {
        $this->update([
            'status' => 'approved',
            'approved_by' => $user->id,
            'approved_at' => now(),
            'approval_notes' => $notes,
        ]);
    }

    public function reject(User $user, string $notes = null): void
    {
        $this->update([
            'status' => 'rejected',
            'approved_by' => $user->id,
            'approved_at' => now(),
            'approval_notes' => $notes,
        ]);
    }

    // Accessors
    public function getFormattedRescheduleTypeAttribute()
    {
        return str_replace('_', ' ', ucfirst($this->reschedule_type));
    }

    public function getAmountDifferenceAttribute()
    {
        return $this->new_amount - $this->old_amount;
    }

    public function getDurationDifferenceAttribute()
    {
        return $this->new_duration - $this->old_duration;
    }

    public function getInterestRateDifferenceAttribute()
    {
        return $this->new_interest_rate - $this->old_interest_rate;
    }
}