<?php

namespace App\Traits;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;

trait hasCurrency
{
  use Currencies;

  protected static function BootHasCurrency()
  {
    if (!app()->runningInConsole()) {
      $currentUser = Auth::user();
      if (!$currentUser) return;
      static::creating(function ($model) use ($currentUser) {
        if (empty($model->currency_code) && Auth::check()) {
          $model->currency_code = currentCurrency();
        }
        $model->exchange_rate = config('money.' . $model->currency_code . '.rate');

        if ($model->currency_code && currentCurrency() != $model->currency_code) {
          foreach ($model->currency_attributes as $attribute) {
            $model->{$attribute} = $model->{$attribute} * $model->exchange_rate;
          }
        }
        else{
         if(isset($model->price ))$model->price = $model->price * $model->exchange_rate;
        }
      });

      static::updating(function ($model) use ($currentUser) {
        if ($model->currency_code && currentCurrency() != $model->currency_code) {
          foreach ($model->currency_attributes as $attribute) {
            $model->{$attribute} = $model->{$attribute} * $model->exchange_rate;
          }
        }

      });

      static::retrieved(function ($model) use ($currentUser) {
        if ($model->currency_code && currentCurrency() != $model->currency_code) {
          foreach ($model->currency_attributes as $attribute) {
            $model->{$attribute} = $model->{$attribute} / $model->exchange_rate;
          }
        }
      });
    }
  }
}
