<?php

namespace App\Models;

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

class UserBalance extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'account_id',
        'balance',
        'mining',
        'profit',
        'bonus',
        'total_deposited',
        'total_withdrawn',
    ];

    protected $casts = [
        'balance' => 'decimal:2',
        'profit' => 'decimal:2',
        'bonus' => 'decimal:2',
        'total_deposited' => 'decimal:2',
        'total_withdrawn' => 'decimal:2',
    ];

    /**
     * Generate unique account ID
     */
    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            if (empty($model->account_id)) {
                $model->account_id = 'ACC-' . strtoupper(substr(uniqid(), -8));
            }
        });
    }

    /**
     * Get the user who owns this balance
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Get total available balance
     */
    public function getTotalBalanceAttribute()
    {
        return $this->balance + $this->profit + $this->bonus;
    }

    /**
     * Get withdrawable balance (excluding bonus)
     */
    public function getWithdrawableBalanceAttribute()
    {
        return $this->balance + $this->profit;
    }

    /**
     * Credit balance
     */
    public function credit($amount, $type = 'balance')
    {
        $this->increment($type, $amount);
    }

    /**
     * Debit balance
     */
    public function debit($amount, $type = 'balance')
    {
        if ($this->$type >= $amount) {
            $this->decrement($type, $amount);
            return true;
        }
        return false;
    }
}
