<?php

namespace App\Models;

use App\Traits\Auditable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class Pledge extends Model
{
    use HasFactory, Auditable, SoftDeletes;

    protected $fillable = [
        'member_id',
        'year',
        'purpose',
        'amount',
        'paid_amount',
        'status',
    ];

    protected function casts(): array
    {
        return [
            'amount' => 'decimal:2',
            'paid_amount' => 'decimal:2',
        ];
    }

    /**
     * Get the remaining balance.
     */
    public function getRemainingAttribute(): float
    {
        return $this->amount - $this->paid_amount;
    }

    /**
     * Get the progress percentage.
     */
    public function getProgressAttribute(): int
    {
        if ($this->amount == 0) return 0;
        return (int) round(($this->paid_amount / $this->amount) * 100);
    }

    /**
     * Update status based on payments.
     */
    public function updateStatus(): void
    {
        if ($this->paid_amount >= $this->amount) {
            $this->status = 'Completed';
        } elseif ($this->paid_amount > 0) {
            $this->status = 'Partial';
        } else {
            $this->status = 'Pending';
        }
        $this->save();
    }

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

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