<?php

namespace App\Models;

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

class Wallet extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'balance',
        'total_earned',
        'total_withdrawn',
        'pending_withdrawal',
        'is_active',
    ];

    protected $casts = [
        'balance' => 'decimal:2',
        'total_earned' => 'decimal:2',
        'total_withdrawn' => 'decimal:2',
        'pending_withdrawal' => 'decimal:2',
        'is_active' => 'boolean',
    ];

    // الحد الأدنى للسحب
    const MIN_WITHDRAWAL_AMOUNT = 450000;

    /**
     * المستخدم المالك للمحفظة
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * معاملات المحفظة
     */
    public function transactions()
    {
        return $this->hasMany(WalletTransaction::class);
    }

    /**
     * طلبات السحب
     */
    public function withdrawalRequests()
    {
        return $this->hasMany(WithdrawalRequest::class);
    }

    /**
     * الحصول على محفظة المستخدم أو إنشاؤها
     */
    public static function getOrCreateForUser($userId)
    {
        return self::firstOrCreate(
            ['user_id' => $userId],
            [
                'balance' => 0.00,
                'total_earned' => 0.00,
                'total_withdrawn' => 0.00,
                'pending_withdrawal' => 0.00,
                'is_active' => true,
            ]
        );
    }

    /**
     * إضافة مبلغ للمحفظة
     */
    public function addBalance($amount, $source = 'referral_earning', $referenceType = null, $referenceId = null, $description = null)
    {
        if ($amount <= 0) {
            throw new \Exception('المبلغ يجب أن يكون أكبر من صفر');
        }

        $balanceBefore = $this->balance;
        $this->increment('balance', $amount);
        $this->increment('total_earned', $amount);
        $balanceAfter = $this->balance;

        // تحديث wallet_balance في جدول users
        $this->user->update(['wallet_balance' => $balanceAfter]);

        // إنشاء معاملة
        WalletTransaction::create([
            'wallet_id' => $this->id,
            'user_id' => $this->user_id,
            'type' => 'credit',
            'source' => $source,
            'amount' => $amount,
            'balance_before' => $balanceBefore,
            'balance_after' => $balanceAfter,
            'reference_type' => $referenceType,
            'reference_id' => $referenceId,
            'description' => $description,
            'status' => 'completed',
        ]);

        return $this;
    }

    /**
     * خصم مبلغ من المحفظة
     */
    public function deductBalance($amount, $source = 'withdrawal', $referenceType = null, $referenceId = null, $description = null)
    {
        if ($amount <= 0) {
            throw new \Exception('المبلغ يجب أن يكون أكبر من صفر');
        }

        if ($this->balance < $amount) {
            throw new \Exception('الرصيد غير كافي');
        }

        $balanceBefore = $this->balance;
        $this->decrement('balance', $amount);
        $this->increment('total_withdrawn', $amount);
        $balanceAfter = $this->balance;

        // تحديث wallet_balance في جدول users
        $this->user->update(['wallet_balance' => $balanceAfter]);

        // إنشاء معاملة
        WalletTransaction::create([
            'wallet_id' => $this->id,
            'user_id' => $this->user_id,
            'type' => 'debit',
            'source' => $source,
            'amount' => $amount,
            'balance_before' => $balanceBefore,
            'balance_after' => $balanceAfter,
            'reference_type' => $referenceType,
            'reference_id' => $referenceId,
            'description' => $description,
            'status' => 'completed',
        ]);

        return $this;
    }

    /**
     * التحقق من إمكانية السحب
     */
    public function canWithdraw($amount = null)
    {
        $availableBalance = $this->balance - $this->pending_withdrawal;
        
        if ($amount) {
            return $availableBalance >= self::MIN_WITHDRAWAL_AMOUNT && $amount <= $availableBalance;
        }
        
        return $availableBalance >= self::MIN_WITHDRAWAL_AMOUNT;
    }

    /**
     * الحصول على الرصيد المتاح للسحب
     */
    public function getAvailableBalanceForWithdrawal()
    {
        $available = $this->balance - $this->pending_withdrawal;
        return $available >= self::MIN_WITHDRAWAL_AMOUNT ? $available : 0;
    }
}
