<?php

namespace App\Models;

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

class LoanRepayment extends Model
{
    use HasFactory;

    protected $fillable = [
        'loan_id', 'intercompany_loan_id',
        'payment_number', 'payment_date', 'due_date',
        'principal_amount', 'interest_amount', 'total_amount',
        'amount', 'principal_component', 'interest_component',
        'bank_account_id', 'super_admin_bank_account_id',
        'payment_method', 'reference_number', 'notes', 'receipt_path',
        'status', 'paid_at', 'paid_by', 'confirmed_by', 'confirmed_at',
        'processed_by', 'processed_at',
    ];

    protected $appends = ['principal_portion', 'interest_portion'];

    protected $casts = [
        'payment_date' => 'date',
        'due_date'     => 'date',
        'paid_at'      => 'datetime',
        'confirmed_at' => 'datetime',
        'processed_at' => 'datetime',
        'principal_amount'   => 'decimal:2',
        'interest_amount'    => 'decimal:2',
        'total_amount'       => 'decimal:2',
        'amount'             => 'decimal:2',
        'principal_component'=> 'decimal:2',
        'interest_component' => 'decimal:2',
    ];

    public function loan()
    {
        return $this->belongsTo(IntercompanyLoan::class, 'intercompany_loan_id')
            ?? $this->belongsTo(IntercompanyLoan::class, 'loan_id');
    }

    public function getIsOverdueAttribute(): bool
    {
        return $this->status === 'pending' && $this->due_date && now()->gt($this->due_date);
    }

    public function processor()
    {
        return $this->belongsTo(User::class, 'processed_by');
    }

    public function isOverdue()
    {
        return $this->status === 'scheduled' && $this->due_date->isPast();
    }

    public function getPrincipalPortionAttribute()
    {
        return $this->principal_amount ?? $this->principal_component ?? 0;
    }

    public function getInterestPortionAttribute()
    {
        return $this->interest_amount ?? $this->interest_component ?? 0;
    }
}
