<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Carbon\Carbon;

class SavingsLock extends Model
{
    protected $table = 'savings_locks';
    
    protected $fillable = [
        'user_id',
        'amount',
        'lock_duration_months',
        'interest_rate',
        'total_interest_earned',
        'locked_at',
        'unlock_at',
        'is_unlocked',
        'unlocked_at',
        'status'
    ];

    protected $casts = [
        'amount' => 'decimal:2',
        'interest_rate' => 'decimal:2',
        'total_interest_earned' => 'decimal:2',
        'locked_at' => 'datetime',
        'unlock_at' => 'datetime',
        'unlocked_at' => 'datetime',
        'is_unlocked' => 'boolean'
    ];

    // Relations
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    // Scopes
    public function scopeActive($query)
    {
        return $query->where('status', 'active');
    }

    public function scopeUnlocked($query)
    {
        return $query->where('is_unlocked', true);
    }

    // Méthodes
    /**
     * Vérifier si le blocage a expiré
     */
    public function isExpired(): bool
    {
        return now()->gte($this->unlock_at);
    }

    /**
     * Jours jusqu'au déblocage
     */
    public function daysUntilUnlock(): int
    {
        return max(0, now()->diffInDays($this->unlock_at, false));
    }

    /**
     * Débloquer automatiquement
     */
    public function autoUnlock(): void
    {
        if ($this->isExpired() && !$this->is_unlocked) {
            $this->update([
                'is_unlocked' => true,
                'unlocked_at' => now(),
                'status' => 'unlocked'
            ]);
        }
    }

    /**
     * Calculer les intérêts accumulés
     */
    public function calculateAccumulatedInterest(): float
    {
        $monthsElapsed = $this->locked_at->diffInMonths(now());
        $monthsTotal = min($monthsElapsed, $this->lock_duration_months);
        
        $monthlyInterest = ($this->amount * $this->interest_rate) / 100 / 12;
        return $monthlyInterest * $monthsTotal;
    }

    /**
     * Total à recevoir au déblocage
     */
    public function getTotalAtUnlock(): float
    {
        $interest = $this->calculateAccumulatedInterest();
        return floatval($this->amount) + $interest;
    }

    /**
     * Forfait de déblocage anticipé (10%)
     */
    public function getEarlyUnlockPenalty(): float
    {
        return floatval($this->amount) * 0.10;
    }

    /**
     * Montant net après pénalité
     */
    public function getNetAfterPenalty(): float
    {
        $interest = $this->calculateAccumulatedInterest();
        $penalty = $this->getEarlyUnlockPenalty();
        return floatval($this->amount) + $interest - $penalty;
    }
}
