<?php

class Outlet extends Eloquent {
	protected $fillable = [
              'product_id','amount',
              'user_id','sku','price',
              'stock_id','available_amount',
              'on_hold', 'location', 'note'
            ];

  protected $table = "Outlets";
  public function branch() {
    return $this->belongsTo('Branches');
  }
  public function users() {
    return $this->hasMany('Users');
  }
  public function products() {
    return $this->hasMany('Product');
  }
  public function scopeStock($query,$stock_id)
  {
    return $query->where('stock_id',$stock_id);
  }
  public function scopeSku($query,$sku)
  {
    return $query->where('sku',$sku);
  }
  public function scopeInStock($query)
  {
    return $query->where('Outlets.amount','>',0);
  }
  public static function scopeNotNull($query)
  {
    $query->where('product_id','<>','null');
  }
  public static function productByID($id)
  {
    $products = Product::getInStocks();
    return $products->where('o.id', $id)
                    ->first();
  }

  public static function item($id)
  {
    $item = Outlet::join('Products','Products.id','=','Outlets.product_id')
                    ->where('Outlets.product_id',$id)->first();
    return $item;
  }
  /**
   * Item in stock by id with current user
   * @param  [type] $id [description]
   * @return [type]     [description]
   */
  public static function itemByUserId($id) 
  {
    $product = DB::table('outlets as o')
                        ->join('products as p', 'p.id', '=', 'o.product_id')
                        ->select('o.*', 'p.is_service', 'p.thumbnail')
                        ->where('o.product_id', $id)
                        ->where('o.stock_id', Auth::user()->stock_id)
                        ->first();
    return $product;
  }

  /**
   * Find Item in stock by sku
   * @param  string $sku unique product id
   * @return object
   */
  public static function itemBySku($sku) {
    $outlet = self::join('products', 'products.id', '=', 'outlets.product_id')
                   ->select(
                    'outlets.id',
                    'outlets.sku',
                    'outlets.amount',
                    'outlets.on_hold',
                    'outlets.available_amount'
                  )
                   ->where('products.status', 'active')
                   ->where('outlets.stock_id', Auth::user()->stock_id)
                   ->where('outlets.sku', $sku)
                   ->first();
    return $outlet;
  }
}