<?php

namespace App\Models;

use App\Traits\LogsActivity;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Withdrawal extends Model
{
    use HasFactory, LogsActivity;

    /**
     * Champs à surveiller pour les logs d'audit
     */
    protected static array $logAttributes = [
        'status', 'amount', 'approved_by', 'rejection_reason'
    ];

    protected $fillable = [
        'user_id',
        'wallet_id',
        'reference',
        'amount',
        'fee',
        'net_amount',
        'currency',
        'status',
        'payment_method',
        'payment_details',
        'rejection_reason',
        'approved_by',
        'approved_at',
        'completed_at',
    ];

    protected $casts = [
        'amount' => 'decimal:2',
        'fee' => 'decimal:2',
        'net_amount' => 'decimal:2',
        'payment_details' => 'array',
        'approved_at' => 'datetime',
        'completed_at' => 'datetime',
    ];

    protected static function boot()
    {
        parent::boot();
        
        static::creating(function ($withdrawal) {
            if (empty($withdrawal->reference)) {
                $withdrawal->reference = 'WD' . strtoupper(uniqid());
            }
            if (empty($withdrawal->net_amount)) {
                $withdrawal->net_amount = $withdrawal->amount - $withdrawal->fee;
            }
        });
    }

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

    public function wallet()
    {
        return $this->belongsTo(Wallet::class);
    }

    public function approvedByUser()
    {
        return $this->belongsTo(User::class, 'approved_by');
    }

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

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

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

    public function approve($approvedBy)
    {
        $this->update([
            'status' => 'approved',
            'approved_by' => $approvedBy,
            'approved_at' => now(),
        ]);

        $this->wallet->decrement('balance', $this->amount);
        $this->wallet->increment('total_withdrawn', $this->amount);

        $txReference = $this->reference . '-APP';
        $this->wallet->transactions()->create([
            'user_id' => $this->user_id,
            'type' => 'withdrawal',
            'amount' => -$this->amount,
            'balance_before' => $this->wallet->balance + $this->amount,
            'balance_after' => $this->wallet->balance,
            'currency' => $this->currency,
            'status' => 'completed',
            'reference' => $txReference,
            'description' => 'Retrait approuvé (Ref: ' . $this->reference . ')',
            'withdrawal_id' => $this->id,
            'metadata' => [
                'withdrawal_reference' => $this->reference,
                'stage' => 'approved',
            ],
        ]);
    }

    public function reject($reason)
    {
        $this->wallet->decrement('pending_balance', $this->amount);
        
        $this->update([
            'status' => 'rejected',
            'rejection_reason' => $reason,
        ]);
    }

    public function complete()
    {
        $this->update([
            'status' => 'completed',
            'completed_at' => now(),
        ]);
    }

    public function getFormattedAmountAttribute()
    {
        return number_format($this->amount, 0, ',', ' ') . ' ' . $this->currency;
    }
}
