<?php

namespace App\Models;

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

class InstallmentPayment extends Model
{
    use HasFactory;

    protected $fillable = [
        'installment_plan_id', 'invoice_id', 'installment_number',
        'due_amount', 'paid_amount', 'due_date', 'paid_date',
        'status', 'payment_notes'
    ];

    protected $casts = [
        'due_amount' => 'decimal:2',
        'paid_amount' => 'decimal:2',
        'due_date' => 'date',
        'paid_date' => 'date',
    ];

    public function installmentPlan()
    {
        return $this->belongsTo(InstallmentPlan::class);
    }

    public function invoice()
    {
        return $this->belongsTo(Invoice::class);
    }

    public function updateStatus()
    {
        if ($this->paid_amount == 0) {
            $this->status = 'pending';
        } elseif ($this->paid_amount < $this->due_amount) {
            $this->status = 'partially_paid';
        } elseif ($this->paid_amount >= $this->due_amount) {
            $this->status = 'paid';
            $this->paid_date = $this->paid_date ?? now();
        }
        
        $this->save();
    }
}