<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class UserWallet extends Model
{
    protected $fillable = [
        'user_id',
        'currency',
        'balance',
        'locked_balance',
    ];

    protected $casts = [
        'balance' => 'decimal:8',
        'locked_balance' => 'decimal:8',
    ];

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

    /**
     * Get available balance (balance - locked_balance)
     */
    public function getAvailableBalanceAttribute()
    {
        return $this->balance - $this->locked_balance;
    }

    /**
     * Lock amount for trading
     */
    public function lockAmount($amount)
    {
        if ($this->available_balance < $amount) {
            throw new \Exception('Insufficient balance');
        }

        $this->balance -= $amount;
        $this->locked_balance += $amount;
        $this->save();
    }

    /**
     * Unlock amount (cancel order)
     */
    public function unlockAmount($amount)
    {
        $this->balance += $amount;
        $this->locked_balance -= $amount;
        $this->save();
    }

    /**
     * Complete trade (remove from locked)
     */
    public function completeTrade($amount)
    {
        $this->locked_balance -= $amount;
        $this->save();
    }

    /**
     * Add to balance
     */
    public function addBalance($amount)
    {
        $this->balance += $amount;
        $this->save();
    }

    /**
     * Subtract from balance
     */
    public function subtractBalance($amount)
    {
        if ($this->balance < $amount) {
            throw new \Exception('Insufficient balance');
        }

        $this->balance -= $amount;
        $this->save();
    }
}
