<?php

namespace App\Models;

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

class UserInvestment extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'investment_product_id',
        'amount',
        'capital_paid',
        'current_value',
        'total_profit',
        'status',
        'start_date',
        'expected_end_date',
        'actual_end_date',
        'payment_count',
        'next_payment_amount',
        'next_payment_date',
        'interest_rate',
        'total_interest_earned',
        'metadata',
        'notes',
    ];

    protected $casts = [
        'amount' => 'decimal:2',
        'capital_paid' => 'decimal:2',
        'current_value' => 'decimal:2',
        'total_profit' => 'decimal:2',
        'next_payment_amount' => 'decimal:2',
        'interest_rate' => 'decimal:2',
        'total_interest_earned' => 'decimal:2',
        'start_date' => 'datetime',
        'expected_end_date' => 'datetime',
        'actual_end_date' => 'datetime',
        'next_payment_date' => 'datetime',
        'metadata' => 'array',
    ];

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

    public function product()
    {
        return $this->belongsTo(InvestmentProduct::class, 'investment_product_id');
    }

    public function transactions()
    {
        return $this->hasMany(InvestmentTransaction::class);
    }

    public function interests()
    {
        return $this->hasMany(InvestmentInterest::class);
    }

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

    public function scopePending($query)
    {
        return $query->where('status', 'pending');
    }

    public function scopeCompleted($query)
    {
        return $query->where('status', 'completed');
    }

    /**
     * Calculer la valeur actuelle incluant les intérêts
     */
    public function calculateCurrentValue()
    {
        $earned = $this->total_interest_earned + $this->interests()
            ->where('status', 'pending')
            ->sum('amount');
        
        $this->current_value = $this->capital_paid + $earned;
        $this->total_profit = $earned;
        
        return $this;
    }

    /**
     * Obtenir le prochain versement attendu
     */
    public function getNextPaymentInfo()
    {
        if ($this->status !== 'pending' || !$this->next_payment_date) {
            return null;
        }

        return [
            'amount' => $this->next_payment_amount,
            'date' => $this->next_payment_date,
            'days_left' => Carbon::now()->diffInDays($this->next_payment_date),
            'is_overdue' => $this->next_payment_date->isPast(),
        ];
    }

    /**
     * Obtenir le pourcentage complété
     */
    public function getProgressPercentage()
    {
        if ($this->amount == 0) return 0;
        return round(($this->capital_paid / $this->amount) * 100, 2);
    }

    /**
     * Estimer le rendement à la fin
     */
    public function getEstimatedReturnAtEnd()
    {
        if (!$this->expected_end_date || !$this->capital_paid) {
            return 0;
        }

        $daysInvested = Carbon::now()->diffInDays($this->expected_end_date);
        if ($daysInvested <= 0) return $this->total_profit;

        // Calcul simple: (capital * taux * jours) / 365
        $estimated = ($this->capital_paid * $this->interest_rate * $daysInvested) / 36500;
        
        return round($estimated, 2);
    }
}
