<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;

class InstallmentPayment extends Model
{
    protected $fillable = [
        'installment_id',
        'installment_number',
        'due_date',
        'amount_due',
        'amount_paid',
        'paid_date',
        'status',
        'late_fee',
        'payment_method',
        'reference',
        'notes',
    ];

    protected $casts = [
        'due_date' => 'date',
        'paid_date' => 'date',
        'amount_due' => 'decimal:2',
        'amount_paid' => 'decimal:2',
        'late_fee' => 'decimal:2',
    ];

    public function installment()
    {
        return $this->belongsTo(Installment::class);
    }

    // Check if payment is overdue
    public function isOverdue(): bool
    {
        if ($this->status === 'paid') {
            return false;
        }

        $gracePeriod = (int) config('settings.installment_grace_period_days', 3);
        $overdueDate = Carbon::parse($this->due_date)->addDays($gracePeriod);
        
        return Carbon::now()->isAfter($overdueDate);
    }

    // Calculate late fee
    public function calculateLateFee(): float
    {
        if (!$this->isOverdue() || $this->status === 'paid') {
            return 0;
        }

        $lateFeePercentage = (float) config('settings.installment_late_fee_percentage', 5);
        return ($this->amount_due * $lateFeePercentage) / 100;
    }

    // Get total amount due including late fee
    public function getTotalDue(): float
    {
        return $this->amount_due + $this->late_fee;
    }

    // Get remaining balance
    public function getRemainingBalance(): float
    {
        return $this->getTotalDue() - $this->amount_paid;
    }
}
