<?php

class History extends \Eloquent {
	protected $fillable = ['product_id','amount','operation_type','user_id','operated_on', 'ref_id'];
	public function products()
	{
		return $this->belongsTo('Products');
	}
	/**
	 * Create New Product History
	 * @param  int $product_id  ID of product has been purchase order
	 * @param  int $amount      Amount of product
	 * @return boolean 					true if success
	 */
	public static function poHistroy($product_id, $amount, $ref_id)
	{
		$history = new self;
		$history->product_id = $product_id;
		$history->amount = $amount;
		$history->operation_type = "in";
		$history->operated_on = "product";
		$history->user_id = Auth::user()->id;
		$history->ref_id = $ref_id;
		if($history->save()) {
			return true;
		}
		return false;
	}
	public static function stockHistory($pId, $data, $type = "in") {
		/*
		Add to Log Data
		*/
		$history = new History;
		$history->product_id = $pId;
		$history->amount = $data['amount'];
		$history->operation_type = $type;
		$history->user_id = Auth::user()->id;
		$history->operated_on = "stock";
		$history->stock_id = $data['stock_id'];
		if($history->save()) {
			return true;
		}
		return false;
	}
	/**
	 * Get Product Histories
	 * @return [type] [description]
	 */
	public static function getForProduct($id, $type = "product")
	{
		$histories = DB::table('Histories')
										->leftJoin('Products','Products.id','=','Histories.product_id')
										->where(function($query) use($id, $type) {
											$query->where('product_id','=',$id)
														->where('operated_on','=',$type);
										})->select('Histories.*','Products.name as pname')
										->orderBy('Histories.created_at', "DESC")->paginate(10);
		return $histories;
	}
}
