<?php

namespace App\Domain\Financial\Models;

use App\Domain\Shared\Traits\Auditable;
use App\Domain\Shared\Traits\BelongsToAcademy;
use App\Domain\Shared\Traits\HasUuid;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use App\Domain\Shared\Traits\ScopedThroughBranch;

class PaymentPlan extends Model
{
    use HasUuid, BelongsToAcademy, Auditable, ScopedThroughBranch;

    /**
     * The parent whose branch this row inherits. A line item has no
     * branch of its own and must not grow one — a denormalised copy
     * here is a second source of truth that drifts the first time the
     * parent moves.
     */
    protected static string $branchScopeRelation = 'invoice';

    protected $fillable = [
        'academy_id',
        'invoice_id',
        'status',
        'total_installments',
        'paid_installments',
        'installment_amount',
        'frequency',
        'start_date',
        'next_due_date',
        'notes',
    ];

    protected function casts(): array
    {
        return [
            'total_installments' => 'integer',
            'paid_installments' => 'integer',
            'installment_amount' => 'integer',
            'start_date' => 'date',
            'next_due_date' => 'date',
        ];
    }

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

    public function installments(): HasMany
    {
        return $this->hasMany(Installment::class);
    }

    public function isComplete(): bool
    {
        return $this->paid_installments >= $this->total_installments;
    }

    public function isFinancialAudit(): bool
    {
        return true;
    }
}
