<?php
use Illuminate\Support\Facades\Config;
class Product extends Eloquent {

	public $timestamps = true;
	protected $fillable = array('sku','barcode_alternative','name', 'name_kh', 'price_in', 'price', 'price_wholesale', 'discount', 'product_category_id', 'thumbnail', 'min_amount', 'max_amount', 'user_id', 'is_service', 'expired_date', 'supplier_id', 'comment', 'item_location_id','ref_id','is_expiring','turn_off_notification','unit_id','feature_item', 'is_second_hand', 'location', 'brand_id', 'status');
	public static $rules = [
		'sku' => 'required',
		'name'	=> 'required',
		'price_in' => 'required',
		'price'		 => 'required',
		'price_wholesale' => 'required',
	];
	/**
	 * Result of reports
	 * @var [type]
	 */
	private static $results = [];

	private $queryObj = [];
	/**
	 * [$uploadPath description]
	 * @var string
	 */
	private static $uploadPath = "/uploads/products/";

	public function category()
	{
		return $this->belongsTo('ProductCategories');
	}

	public function user()
	{
		return $this->belongsTo('Users');
	}

	public function supplier()
	{
		return $this->belongsTo('Suppliers');
	}
	public function histories()
	{
		return $this->hasMany('Histories');
	}

		public function units()
	{
		return $this->belongsTo('Units');
	}
	/**
	* Product Before Expire
	* @param int number of month
	*/
	public function scopeBeforeExpire($query, $month = 3)
	{
	 $now = Carbon\Carbon::now();
	 $now->addMonths($month);
	 $products = $query->where('expired_date', '<', $now)->get();
	 return $products;
	}
	/**
	 * Get Amount with minimize amount
	 * @param  [type] $query
	 * @return Product Object        [description]
	 */
	public function scopeMinAmount($query)
	{
		$products = $query->whereRaw('Products.amount <= Products.min_amount')
                        ->whereRaw('Products.turn_off_notification is null')
                          ->orderBy('id','desc')->get();
		return $products;
	}
	/**
	* Products Recent Added
	* @param $limit int number of recent products has been added
	*/
	public function scopeRecentProducts($query, $limit = 5)
	{
		$products  = $query->take($limit)
											->where('status', 'active')
											->orderBy('created_at', 'desc')
											->get();
		if (!$products) return null;
		return $products;
	}
	/**
	 * [getPathUpload ]
	 * @return string path upload
	 */
	public static function getUploadPath()
	{
		return self::$uploadPath;
	}
	/**
	 * Sale History of products has been sold
	 * @param  int $id the id of productcategories table
	 * @return array of objects
	 */
	public static function saleHistory($id = null, $start = null, $end = null, $start_barcode = null, $end_barcode = null)
	{
		self::$results = DB::table('products as p')
                ->join('orders as o ', 'o.product_id', '=', 'p.id')
                ->join('productcategories as pc', 'pc.id', '=', 'p.product_category_id')
                ->select(
									'p.sku',
                  'p.name as name_en',
                  'p.name_kh',
                  'p.price',
				  'pc.name',
                  'o.created_at'
                )->where('o.sold', 1);
		if ($start && $end) self::$results->whereBetween('o.created_at', [$start, $end]);
		if ($start_barcode && $end_barcode) self::$results->whereBetween('p.sku', [$start_barcode, $end_barcode]);
		if ($id == 'all') {
			return self::$results->get();
		} else {
			self::$results->where('pc.id', $id);
		}
		return self::$results->get();
	}

	public static function getInStocks($type = "all")
	{
		$products = DB::table('products as p')
					  ->join('outlets as o', 'o.product_id', '=', 'p.id')
					  ->leftJoin('productcategories as pc', 'pc.id', '=', 'p.product_category_id')
					  ->leftJoin('units as u', 'u.id', '=', 'p.unit_id')
					  ->leftJoin('brands as b', 'b.id', '=', 'p.brand_id')
					  ->select([
					  		'p.id',
					  		'p.sku', 
					  		'p.name',
					  		'p.discount',
					  		'p.unit_id',
					  		'p.name_kh', 
					  		'p.price', 
					  		'p.price_wholesale',
					  		'p.expired_date',
					  		'p.thumbnail',
					  		'p.status',
					  		'pc.name as category',
					  		'u.name as unit',
					  		'o.product_id',
					  		'o.amount',
					  		'o.on_hold',
					  		'o.id as outlet_id',
					  		'o.available_amount',
					  		'o.stock_id',
					  		'b.name as brand'
					  ])->whereIn('p.status', ['active', 'inactive']);
		return $products;
	}

	public static function byId($id) 
	{
		$product = DB::table('Products')
							->join('Outlets', 'Outlets.product_id', '=', 'Products.id')
							->leftJoin('ProductCategories', 'Products.product_category_id', '=', 'ProductCategories.id')
	            ->leftJoin('Units', 'Products.unit_id', '=', 'Units.id')
	            ->leftJoin('itemLocations', 'Products.item_location_id', '=', 'itemLocations.id')
	            ->leftJoin('Suppliers', 'Products.supplier_id', '=', 'Suppliers.id')
	    				->select(
    							'products.*', 
    							'Outlets.amount',
    							'Outlets.on_hold',
    							'Outlets.available_amount',
    							'Outlets.id as outlet_id',
    							'Outlets.stock_id',
    							'ProductCategories.name AS category_name',
    							'itemLocations.name AS location_name',
    							'Units.name AS unit', 
    							'Suppliers.company_name AS supplier_name'
    							)
    				->where('Products.id','=',$id)
    				->wherein('Products.status', ['active', 'inactive'])
    				->first();
    return $product;
	}
}
