<?php
namespace App\Models;

use App\Traits\VisibleToAdmin;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Carbon\Carbon;

class LoanInstallment extends Model
{
    use HasFactory;
    use VisibleToAdmin;

    // This tells the trait how to reach the user who controls visibility
    protected function adminVisibilityRelation(): string
    {
        return 'loan.user';
    }

    protected $fillable = [
        'loan_id',
        'installment_number',
        'principal',
        'interest',
        'penalty',
        'total',
        'due_date',
        'paid_at',
        'status',
    ];

    protected $casts = [
        'due_date' => 'date',
        'paid_at' => 'datetime',
    ];

    /* =====================
     | Relationships
     ===================== */

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

    /* =====================
     | Helpers
     ===================== */

    public function isDue(): bool
    {
        return Carbon::today()->gte($this->due_date);
    }

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

    /* =====================
     | Scopes
     ===================== */

    public function scopePending(Builder $query)
    {
        return $query->where('status', 'pending');
    }

    public function scopeOverdue(Builder $query)
    {
        return $query->where('status', 'overdue');
    }

    public function scopeDueToday(Builder $query)
    {
        return $query->whereDate('due_date', today());
    }

    public function scopeUpcoming(Builder $query, int $days = 3)
    {
        return $query->whereBetween('due_date', [
            today(),
            today()->addDays($days)
        ]);
    }
}
