<?php

namespace App\Models;

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

class Savings extends Model
{
    use HasFactory;

    protected $table = 'savings';

    protected $fillable = [
        'user_id',
        'savings_plan_id',
        'amount',
        'interest_amount',
        'total_interest_earned',
        'total_paid',
        'paid_count',
        'total_payable_times',
        'should_pay',
        'capital_back',
        'capital_returned',
        'status',
        'last_paid_at',
        'next_pay_at',
    ];

    protected $casts = [
        'amount'                => 'decimal:2',
        'interest_amount'       => 'decimal:2',
        'total_interest_earned' => 'decimal:2',
        'total_paid'            => 'decimal:2',
        'paid_count'            => 'integer',
        'total_payable_times'   => 'integer',
        'should_pay'            => 'decimal:2',
        'capital_back'          => 'boolean',
        'capital_returned'      => 'boolean',
        'last_paid_at'          => 'datetime',
        'next_pay_at'           => 'datetime',
    ];

    /**
     * Get the user that owns this savings.
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Get the savings plan.
     */
    public function savingsPlan()
    {
        return $this->belongsTo(SavingsPlan::class, 'savings_plan_id');
    }

    /**
     * Get all interest logs for this savings.
     */
    public function interestLogs()
    {
        return $this->hasMany(SavingsInterestLog::class, 'savings_id');
    }

    /**
     * Scope to only running savings.
     */
    public function scopeRunning($query)
    {
        return $query->where('status', 'running');
    }

    /**
     * Scope to savings due for interest payment.
     */
    public function scopeDueForPayment($query)
    {
        return $query->where('status', 'running')
                     ->where('next_pay_at', '<=', now());
    }

    /**
     * Check if this savings is lifetime (never ends).
     */
    public function isLifetime()
    {
        return is_null($this->total_payable_times);
    }

    /**
     * Check if this savings has completed all payments.
     */
    public function isCompleted()
    {
        if ($this->isLifetime()) {
            return false;
        }

        return $this->paid_count >= $this->total_payable_times;
    }
}
