<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Http\Traits\Timezone;

class Withdrawal extends Model
{
    use HasFactory, Timezone;
    protected $casts = [
        'created_at' => 'datetime:d-m-Y H:i:s'
    ];
    protected $fillable = [
        'user_id',
        'currency_id',
        'wallet_id',
        'blockchain',
        'blockchain_address',
        'transaction_hash',
        'amount',
        'exchange_amount',
        'exchange_rate',
        'withdrawal_fee',
        'received_amount',
        'account_type',
        'primary_account_first_name',
        'primary_account_last_name',
        'joint_account_first_name',
        'joint_account_last_name',
        'business_name',
        'account_holder',
        'bank_name',
        'iban_number',
        'bank_branch_name',
        'bic_swift_number',
        'bank_address',
        'status',
        'pre_approved_by',
        'approved_by',
        'reference_no',
        'batch_id',
        'ticket_id',
        'due_date',
        'reason'
    ];

    protected $appends = ['wallet_log_balance'];

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id')->with('details');
    }

    public function currency()
    {
        return $this->belongsTo(Currency::class, 'currency_id');
    }

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

    public function walletLog()
    {
        return $this->hasOne(WalletLog::class, 'unique_id');
    }

    public function preApprovedBy()
    {
        return $this->belongsTo(User::class, 'pre_approved_by')->with('details');
    }

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

    public function getWalletLogBalanceAttribute()
    {
        if ($this->status == 1) {
            $walletBalance = WalletLog::where([
                    'unique_id' => $this->id,
                    'action' => WalletLog::ACTION_WITHDRAW,
                    'wallet_id' => $this->wallet_id
                ])->whereNotNull('data->withdrawal')->first();
            return $walletBalance ? $walletBalance->balance : null;
        }

        return null;
    }
}
