<?php

namespace App\Models;

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

class PoolShare extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'amount',
        'global_sales',
        'user_contribution',
        'percentage',
        'period_start',
        'period_end',
        'status',
        'notes',
        'paid_at',
    ];

    protected $casts = [
        'amount' => 'float',
        'global_sales' => 'float',
        'user_contribution' => 'float',
        'percentage' => 'float',
        'period_start' => 'datetime',
        'period_end' => 'datetime',
        'paid_at' => 'datetime',
    ];

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

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

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

    public function scopeForPeriod($query, $start, $end)
    {
        return $query->whereBetween('period_start', [$start, $end]);
    }

    // Méthodes
    public function markAsPaid()
    {
        $this->update([
            'status' => 'paid',
            'paid_at' => now(),
        ]);

        // Créditer le portefeuille de l'utilisateur
        if ($this->user && $this->user->wallet) {
            $balanceBefore = $this->user->wallet->balance;
            $this->user->wallet->increment('balance', $this->amount);
            $this->user->wallet->increment('total_earned', $this->amount);
            $balanceAfter = $balanceBefore + $this->amount;

            // Créer une transaction wallet
            \App\Models\WalletTransaction::create([
                'wallet_id' => $this->user->wallet->id,
                'user_id' => $this->user->id,
                'type' => 'pool_share',
                'amount' => $this->amount,
                'balance_before' => $balanceBefore,
                'balance_after' => $balanceAfter,
                'currency' => 'XOF',
                'status' => 'completed',
                'description' => "Pool de partage - Période du {$this->period_start->format('d/m/Y')} au {$this->period_end->format('d/m/Y')}",
                'reference' => 'POOL-' . $this->id . '-' . time(),
            ]);
        }
    }
}
