<?php

namespace App\Models;

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

class SavingsWallet extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'balance',
        'total_deposited',
        'total_interest_earned',
        'is_locked',
        'lock_duration_months',
        'locked_at',
        'unlock_at',
        'interest_rate'
    ];

    protected $casts = [
        'balance' => 'decimal:2',
        'total_deposited' => 'decimal:2',
        'total_interest_earned' => 'decimal:2',
        'is_locked' => 'boolean',
        'locked_at' => 'datetime',
        'unlock_at' => 'datetime',
        'interest_rate' => 'decimal:2'
    ];

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

    public function unlockRequests()
    {
        return $this->hasMany(UnlockRequest::class);
    }

    public function interestHistory()
    {
        return $this->hasMany(SavingsInterestHistory::class);
    }

    /**
     * Vérifier si le wallet est débloqué
     */
    public function isUnlocked()
    {
        if (!$this->is_locked) {
            return true;
        }
        
        if ($this->unlock_at && now()->greaterThanOrEqualTo($this->unlock_at)) {
            $this->unlock();
            return true;
        }
        
        return false;
    }

    /**
     * Débloquer automatiquement
     */
    public function unlock()
    {
        $this->update([
            'is_locked' => false,
            'locked_at' => null,
            'unlock_at' => null,
            'lock_duration_months' => null
        ]);
    }

    /**
    /**
     * Bloquer pour une période
     */
    public function lock($durationMonths, $interestRate)
    {
        // Convertir en integer au cas où ce serait une string
        $durationMonths = (int) $durationMonths;
        
        $this->update([
            'is_locked' => true,
            'lock_duration_months' => $durationMonths,
            'locked_at' => now(),
            'unlock_at' => now()->addMonths($durationMonths),
            'interest_rate' => $interestRate
        ]);
    }

    /**
     * Vérifier si retrait possible
     */
    public function canWithdraw($amount)
    {
        return $this->isUnlocked() && $this->balance >= $amount;
    }

    /**
     * Calculer les jours restants
     */
    public function daysUntilUnlock()
    {
        if (!$this->is_locked || !$this->unlock_at) {
            return 0;
        }
        
        return max(0, now()->diffInDays($this->unlock_at, false));
    }

    /**
     * Obtenir le pourcentage de progression
     */
    public function lockProgress()
    {
        if (!$this->is_locked || !$this->locked_at || !$this->unlock_at) {
            return 100;
        }

        $totalDays = $this->locked_at->diffInDays($this->unlock_at);
        $daysPassed = $this->locked_at->diffInDays(now());
        
        return min(100, ($daysPassed / max($totalDays, 1)) * 100);
    }
}
