<?php

namespace App\Models;

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

class PaymentSchedule extends Model
{
    use HasFactory;

    protected $table = 'paymentschedule';
    protected $primaryKey = 'scheduleid';

    protected $fillable = [
        'loannumber',
        'loanid',
        'interestamount',
        'principalamount',
        'totalamount',
        'paymentdate',
        'transactiontype',
        'status',
        'installment_number',
        'outstanding_principal',
        'outstanding_interest',
        'cumulative_principal_paid',
        'cumulative_interest_paid',
        'paid_date',
        'paid_principal',
        'paid_interest',
        'paid_penalty',
        'total_paid',
        'branchid',
        'companyid',
        'createdby',
        'updatedby'
    ];

    protected $casts = [
        'paymentdate' => 'datetime',
        'paid_date' => 'datetime',
        'interestamount' => 'decimal:2',
        'principalamount' => 'decimal:2',
        'totalamount' => 'decimal:2',
        'outstanding_principal' => 'decimal:2',
        'outstanding_interest' => 'decimal:2',
        'cumulative_principal_paid' => 'decimal:2',
        'cumulative_interest_paid' => 'decimal:2',
        'paid_principal' => 'decimal:2',
        'paid_interest' => 'decimal:2',
        'paid_penalty' => 'decimal:2',
        'total_paid' => 'decimal:2',
    ];

    /**
     * Relationship with DisbursedLoan
     */
    public function loan()
    {
        return $this->belongsTo(DisbursedLoan::class, 'loanid', 'loanid');
    }

    /**
     * Scope for scheduled payments
     */
    public function scopeScheduled($query)
    {
        return $query->where('status', 'scheduled');
    }

    /**
     * Scope for paid payments
     */
    public function scopePaid($query)
    {
        return $query->where('status', 'paid');
    }

    /**
     * Scope for upcoming payments
     */
    public function scopeUpcoming($query)
    {
        return $query->where('paymentdate', '>=', now())
                    ->where('status', 'scheduled');
    }

    /**
     * Scope for overdue payments
     */
    public function scopeOverdue($query)
    {
        return $query->where('paymentdate', '<', now())
                    ->where('status', 'scheduled');
    }
}