<?php

namespace App\Models;
use Carbon\Carbon;
class Rebate extends BaseModel
{


    protected $table = 'rebates';
    protected $fillable = ['date', 'member_id', 'betting_amount', 'rebate_ratio',
        'amount', 'status', 'first_name', 'username', 'audited_by',
        'profit', 'huishui_percentage', 'huishui_restriction', 'huishui_amount',
    ];
    const STATUS_WEI_FAN_YONG = 0;//未返佣
    const STATUS_FAN_YONG = 1; //已返佣




    static function updateProfit($data)
    {
        $data['date'] = Carbon::now('America/New_York')->format('Y-m-d');
        $rebate = static::where('date', $data['date'])
            ->where('member_id', $data['member_id'])->first();
        $rebate->increment('profit', $data['profit']);
        return $rebate;
    }

    static function addOrUpdate($data)
    {
        $rebate = static::where('date', $data['date'])
            ->where('member_id', $data['member_id'])->first();
        if ($rebate) {
            $rebate->rebate_ratio = $data['rebate_ratio'];
            $rebate->first_name = $data['first_name'];
            $rebate->username = $data['username'];
            $rebate->save();
            $rebate->increment("betting_amount", $data['betting_amount']);
        } else {
            $rebate = static::create($data);
        }
        return $rebate;
    }


    protected function getHuishuiRestrictionAttribute($value)
    {
        if ($this->status == static::STATUS_WEI_FAN_YONG) {
            $huishui_restriction = Config::where('field', 'huishui_restriction')->first()->val;
            return $huishui_restriction;
        }
        return $value;

    }

    protected function getHuishuiPercentageAttribute($value)
    {
        if ($this->status == static::STATUS_WEI_FAN_YONG) {
            $huishui_percentage = Config::where('field', 'huishui_percentage')->first()->val;
            return $huishui_percentage;
        }
        return $value;
    }

    protected function getHuishuiAmountAttribute($value)
    {
        if ($this->status == static::STATUS_WEI_FAN_YONG) {
            $value = 0;
            $huishui_restriction = Config::where('field', 'huishui_restriction')->first()->val;
            $huishui_percentage = Config::where('field', 'huishui_percentage')->first()->val;
            $lose = $this->profit * -1;
            if ($lose >= $huishui_restriction) {
                $value = bcmul($lose, $huishui_percentage, 2); // 返利金额
            }
        }
        return $value;
    }
}