<?php

namespace App\Models;

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

class SavingsPlan extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'invest_type',
        'minimum_amount',
        'maximum_amount',
        'fixed_amount',
        'interest_type',
        'interest_rate',
        'time_setting_id',
        'return_type',
        'repeat_times',
        'capital_back',
        'compound_interest',
        'hold_capital',
        'featured',
        'status',
    ];

    protected $casts = [
        'minimum_amount'    => 'decimal:2',
        'maximum_amount'    => 'decimal:2',
        'fixed_amount'      => 'decimal:2',
        'interest_rate'     => 'decimal:2',
        'repeat_times'      => 'integer',
        'capital_back'      => 'boolean',
        'compound_interest' => 'boolean',
        'hold_capital'      => 'boolean',
        'featured'          => 'boolean',
        'status'            => 'boolean',
    ];

    /**
     * Get the time setting for this plan.
     */
    public function timeSetting()
    {
        return $this->belongsTo(SavingsTimeSetting::class, 'time_setting_id');
    }

    /**
     * Get all savings (investments) for this plan.
     */
    public function savings()
    {
        return $this->hasMany(Savings::class, 'savings_plan_id');
    }

    /**
     * Scope to only active plans.
     */
    public function scopeActive($query)
    {
        return $query->where('status', true);
    }

    /**
     * Scope to only featured plans.
     */
    public function scopeFeatured($query)
    {
        return $query->where('featured', true);
    }

    /**
     * Calculate interest for a given amount.
     */
    public function calculateInterest($amount)
    {
        if ($this->interest_type === 'percent') {
            return round(($amount * $this->interest_rate) / 100, 2);
        }

        // Fixed interest
        return round($this->interest_rate, 2);
    }

    /**
     * Get invest limit display string.
     */
    public function getInvestLimitAttribute()
    {
        if ($this->invest_type === 'fixed') {
            return '$' . number_format($this->fixed_amount, 2);
        }

        return '$' . number_format($this->minimum_amount, 2) . ' - $' . number_format($this->maximum_amount, 2);
    }

    /**
     * Get interest display string.
     */
    public function getInterestDisplayAttribute()
    {
        if ($this->interest_type === 'percent') {
            return number_format($this->interest_rate, 2) . ' %';
        }

        return number_format($this->interest_rate, 2) . ' USD';
    }
}
