<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Support\Str;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;


    protected static function booted()
    {
        static::creating(function ($model) {
            $model->access_key = Str::uuid();
        });


    }

    /**
     * The attributes that are mass assignable.
     *
     * @var string[]
     */
    protected $fillable = [
        'name',
        'surname',
        'first_name',
        'email',
        'photo',
        'phone',
        'country',
        'city',
        'email_verified',
        'verification_link',
        'address',
        'status',
        'zip',
        'password',
        'refer_by',
        'my_referer_code',
        'account_tx_ref',
        'crypto_account_number',
        'crypto_account_code',
        'crypto_customer_id',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];
    protected $casts = [
        'kyc_info' => 'array'
    ];

    public function wallets()
    {
        return $this->hasMany(Wallet::class,'user_id')->where('user_type',1);
    }

    public function transactions()
    {
        return $this->hasMany(Transaction::class)->where('user_type',1);
    }


    protected static function boot(){
        parent::boot();
        static::created(function($user){
            LoginLogs::create([
                'user_id' => auth()->id(),
                'ip' => @loginIp()->geoplugin_request,
                'country' => @loginIp()->geoplugin_countryName,
                'city' => @loginIp()->geoplugin_city,
            ]);
        });
    }

    public function dailyLimit()
    {
        $rate = defaultCurr()->rate;
        return  $this->transactions()->where('remark','transfer_money')->whereDate('created_at',Carbon::now())->selectRaw("SUM(amount / $rate) as total")->get()->sum('total');
    }

    public function monthlyLimit()
    {
        $rate = defaultCurr()->rate;
        return  $this->transactions()->where('remark','transfer_money')->whereMonth('created_at',Carbon::now()->month)->selectRaw("SUM(amount / $rate) as total")->get()->sum('total');
    }

    public function cashOutDailyLimit()
    {
        $rate = defaultCurr()->rate;
        return  $this->transactions()->where('remark','cash_out')->whereDate('created_at',Carbon::now())->selectRaw("SUM(amount / $rate) as total")->get()->sum('total');
    }

    public function cashOutMonthlyLimit()
    {
        $rate = defaultCurr()->rate;
        return  $this->transactions()->where('remark','cash_out')->whereMonth('created_at',Carbon::now()->month)->selectRaw("SUM(amount / $rate) as total")->get()->sum('total');
    }

    public function getMerchantAccessKey($uid){
        return Merchant::where('id',$uid)->pluck('access_key')->first();
    }
    public function getUserAccessKey($uid){
        return $this::where('id',$uid)->pluck('access_key')->first();
    }
    public function getRefererId($uid){
        return User::where('my_referer_code',$uid)->pluck('id')->first();
    }

    public function getMyWallet(){
        return Wallet::where('user_id',Auth()->user()->id)->first();
    }
    public function getTotalRefer(){
        return User::where('refer_by',Auth()->user()->id)->count();
    }


    public function saveToClientWallet($amount,$user, $type){
        $getWallet =Wallet::where('user_id', $user)->first();
        if($type=='Pending') {
            $walletBalance = $getWallet->pending_balance;
            $getWallet->pending_balance = $walletBalance + $amount;

        }elseif($type=='Balance'){
            $walletBalance = $getWallet->balance;
            $getWallet->balance = $walletBalance + $amount;
           // dd($getWallet->balance);
        }elseif($type=='ReferPending'){
            $walletBalance = $getWallet->pending_refer_bonus;
            $getWallet->pending_refer_bonus = $walletBalance + $amount;
        }elseif($type=='Refer'){
            $walletBalance = $getWallet->refer_bonus_balance;
            $getWallet->refer_bonus_balance = $walletBalance + $amount;
        }
        $getWallet->save();

    }

    public function saveToClientWalletBonus($amount,$user, $type, $earnfrom, $rfUser=null){
        $getWallet =Wallet::where('user_id', $user)->first();
        if($type=='balance'){
            $pendingBalance = $getWallet->pending_balance - $amount;
            $walletBalance = $getWallet->balance;
            $getWallet->balance = $walletBalance + $amount;
            $getWallet->pending_balance = $pendingBalance;
        }elseif($type=='refer'){

           // $pendingBalance = $getWallet->pending_refer_bonus - $amount;
            $walletBalance = $getWallet->refer_bonus_balance;
            $getWallet->refer_bonus_balance = $walletBalance + $amount;
           // $getWallet->pending_refer_bonus = $pendingBalance;
            $refer = new ReferBonus();
            $refer->owner_id = $user;
            $refer->earn_from=$earnfrom;
            $refer->refer_user = $rfUser;
            $refer->amount = $amount;
            $refer->created_by = Auth()->user()->id;
            $refer->save();

        }
        $getWallet->save();

    }

    public function getTotalWalletBalance(){
        $wallet = $this->getMyWallet();
        return $wallet->balance + $wallet->refer_bonus_balance;
    }



    public function getUserWallet($userId){
        return Wallet::where('user_id',$userId)->first();
    }

    public function getUserAssets($userId){
        return VirtualAccounts::where('user_id',$userId)->get();
    }


    public function saveToClientWalletCrypto($amount,$user, $type){
        $getWallet =Wallet::where('user_id', $user)->first();
        if(empty($getWallet)){
            $countries = Country::query();
            // $name = $countries->pluck('name')->toArray();
            $currency = $countries->where('name',Auth()->user()->country)->value('currency_id');
          $getWallet=  Wallet::create([
                'user_id' => $user,
                'user_type' => 1,
                'currency_id' => $currency,
                'balance' => 0
            ]);
        }
        if($type=='Pending') {
            $walletBalance = $getWallet->pending_balance;
            $getWallet->pending_balance = $walletBalance + $amount;
        }elseif($type=='Balance'){
            $walletBalance = $getWallet->balance;
            $getWallet->balance = $walletBalance + $amount;
        }elseif($type=='ReferPending'){
            $walletBalance = $getWallet->pending_refer_bonus;
            $getWallet->pending_refer_bonus = $walletBalance + $amount;
        }elseif($type=='Refer'){
            $walletBalance = $getWallet->refer_bonus_balance;
            $getWallet->refer_bonus_balance = $walletBalance + $amount;
        }
        $getWallet->save();

    }

    public function CryptoAccount($coin, $user_id){
        return VirtualAccounts::where('user_id',$user_id)->where('blockchain_code',$coin)->first();
    }



}
