<?php

namespace App;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

class Master extends Model
{
  public function saveModel($request, $folio)
  {
    $model = $this->getModel();
    ($model::withoutGlobalScope('by_user')->get()->count() > 0) ? $this->folio = $folio . $model::withoutGlobalScope('by_user')->get()->first()->id : $this->folio = $folio . 0;
    $this->created_by_id = $request->user()->id;
    if ($this->currency_id == 1) {
      $this->total_mn = $this->total * $this->exchange_rate;
      $this->total_me = $this->total;
    } else {
      $this->total_mn = $this->total;
      $this->total_me = $this->total / $this->exchange_rate;
    }
    $this->save();
    $this->load('created_by');
    return $this;
  }

  public function updateDetails($request)
  {
    $this->details()->delete();
    $this->details()->createMany($request->get('details'));
    $this->update($request->all());
    if ($this->currency_id == 1) {
      $this->total_mn = $this->total * $this->exchange_rate;
      $this->total_me = $this->total;
    } else {
      $this->total_mn = $this->total;
      $this->total_me = $this->total / $this->exchange_rate;
    }
    $this->save();
    $this->load('details');
    return $this;
  }

  protected static function boot()
  {
      parent::boot();
      static::addGlobalScope('order', function (Builder $builder) {
          $builder->orderBy('created_at', 'dsc');
      });
      static::addGlobalScope('by_user', function (Builder $builder) {
          $authUser = \JWTAuth::parseToken()->authenticate();
          if (!$authUser->hasRole('Admin')) {
            $builder->where('created_by_id', $authUser->id);
          }
      });
  }
}
