<?php

namespace App\Models;

use App\Enums\InstallmentStatus;
use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Installment extends Model
{
    use BelongsToTenant;

    protected $fillable = [
        'tenant_id', 'invoice_id', 'seq', 'due_date', 'amount',
        'paid_amount', 'status', 'paid_at', 'reminder_sent_at',
    ];

    protected function casts(): array
    {
        return [
            'status' => InstallmentStatus::class,
            'due_date' => 'date',
            'paid_at' => 'datetime',
            'reminder_sent_at' => 'datetime',
        ];
    }

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

    public function remaining(): int
    {
        return max(0, $this->amount - $this->paid_amount);
    }

    public function isOverdue(): bool
    {
        return $this->status !== InstallmentStatus::Paid
            && $this->due_date->isPast()
            && ! $this->due_date->isToday();
    }

    public function scopeUnpaid(Builder $q): Builder
    {
        return $q->where('status', '!=', InstallmentStatus::Paid);
    }

    public function scopeOverdue(Builder $q): Builder
    {
        return $q->unpaid()->whereDate('due_date', '<', today());
    }

    public function scopeDueBetween(Builder $q, $from, $to): Builder
    {
        return $q->unpaid()->whereDate('due_date', '>=', $from)->whereDate('due_date', '<=', $to);
    }
}
