<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laratrust\Traits\LaratrustUserTrait;
use App\Menu;
use App\MenuLog;
use App\Exceptions\MenuException;
use Illuminate\Support\Facades\Mail;

class User extends Authenticatable
{
    use LaratrustUserTrait;
    use Notifiable;

    protected $fillable = [
        'name', 'email', 'password',
    ];
    protected $hidden = [
        'password', 'remember_token',
    ];

    protected $casts = [
      'is_verified' =>  'boolean',
    ];

    public function beli(Menu $menu)
    {

      if($menu->stock < 1){
        throw new MenuException("Menu $menu->title sudah habis.");
      }
      // cek apakah buku ini sedang dipinjam oleh user
      if($this->beliLogs()->where('menu_id',$menu->id)->where('dibatalkan', 0)->count() > 9)
    {
      throw new MenuException("Menu $menu->title sudah melebihi 10 porsi dan sedang diproses.");
    }
      $beliLog = BeliLog::create(['user_id'=>$this->id, 'menu_id'=>$menu->id]);
      return $beliLog;
    }

  public function beliLogs()
    {
      return $this->hasMany('App\BeliLog');
  }

  public function generateVerificationToken()
  {
    $token = $this->verification_token;
    if (!$token) {
      $token = str_random(40);
      $this->verification_token = $token;
      $this->save();
    }
return $token;
  }

  public function sendVerification()
  {
    $token  = $this->generateVerificationToken();
    $user = $this;
    Mail::send('auth.emails.verification',compact('user','token'),function ($m) use ($user)
    {
      $m->to($user->email, $user->name)->subject('Verifikasi Akun GeMakan');
    });
  }

  public function verify()
  {
    $this->is_verified  = 1;
    $this->verification_token = null;
    $this->save();
  }

}
