<?php

namespace App\Models;

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

class SavingsGoal extends Model
{
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'savings_account_id',
        'name',
        'target_amount',
        'target_date',
        'status',
        'notes',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'target_amount' => 'decimal:2',
        'target_date' => 'date',
    ];

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

    /**
     * Get the progress percentage towards the goal.
     */
    public function getProgressPercentageAttribute(): float
    {
        if ($this->target_amount > 0) {
            $currentAmount = $this->savingsAccount->current_balance;
            return round(min(100, ($currentAmount / $this->target_amount) * 100), 2);
        }

        return 0;
    }
}
