<?php

namespace Yajny\Member\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Cache;
use Yajny\Member\Traits\MemberScopes;
use Yajny\Traits\HasCurrency;

class UserPayoutMethods extends Model
{
    //
    // use Notifiable;
    use MemberScopes, SoftDeletes, HasCurrency;

    protected $table = 'user_payout_methods';
    protected $primaryKey = 'id';
    public $dateColumn = 'created_at';
    public $directTable = 'user_payout_methods';

    protected $fillable = ['method_code','account','name','verify_code','payout_data'];

    protected $appends = ['allowed_amounts'];

    protected $casts = [
        'payout_data' => 'object'
    ];

    public function info(){
        return $this->belongsTo('Yajny\Member\Models\PayoutMethods','method_code','code');
    }

    public function getAllowedAmountsAttribute()
    {
        $allowedAmounts = [];
        $allCurrencies = Cache::rememberForever('currencies', function () {
            return Currencies::all()->mapWithKeys(function ($currency) {
                return [$currency->iso_code => $currency];
            });
        });
        $currency = $allCurrencies[$this->info->default_currency] ?? $allCurrencies['USD'];
        foreach ($this->info->allowed_amounts ?? [] as $allowed_amount) {
            $isEligible = false;
            switch ($allowed_amount->condition->operator) {
                case '=':
                    $isEligible = ($this->payout_data->{$allowed_amount->condition->key} ?? null) == $allowed_amount->condition->value;
                    break;
                case '!=':
                    $isEligible = ($this->payout_data->{$allowed_amount->condition->key} ?? null) != $allowed_amount->condition->value;
                    break;
                case '>':
                    $isEligible = ($this->payout_data->{$allowed_amount->condition->key} ?? null) > $allowed_amount->condition->value;
                    break;
                case '<':
                    $isEligible = ($this->payout_data->{$allowed_amount->condition->key} ?? null) < $allowed_amount->condition->value;
                    break;
                case '>=':
                    $isEligible = ($this->payout_data->{$allowed_amount->condition->key} ?? null) >= $allowed_amount->condition->value;
                    break;
                case '<=':
                    $isEligible = ($this->payout_data->{$allowed_amount->condition->key} ?? null) <= $allowed_amount->condition->value;
                    break;
            }
            if ($isEligible) {
                $allowed_amount->cost_formatted = $this->currencyValueFormatted($allowed_amount->cost, $currency);
                $allowedAmounts[] = $allowed_amount;
            }
        }
        return $allowedAmounts ?: null;
    }
}
