public function getCreateTonDauThang(){
		$list_month = ReceiptMonth::select('month','year')
									->distinct()->where('month','>',0)
									->orderBy('year','ASC')
									->orderBy('month','ASC')
									->get()->toArray();
		foreach ($list_month as $key => $value) {
			$check = TonDauThang::where('month','=',$value['month'])
								->where('year','=',$value['year'])
								->get()->first();
			if(!$check){
				if($key==0){
					$arr_insert = array();
					$list_instock = Mproduct::where('module_type','=','in_stock')
									->get()->toArray();

					foreach ($list_instock as $key2 => $value2) {
						$arr_insert[$key2]['m_product_id'] = $value2['id'];
						$arr_insert[$key2]['quantity'] = $value2['quantity']*$value2['specification'];
						$arr_insert[$key2]['month'] = $value['month'];
						$arr_insert[$key2]['year'] = $value['year'];
					}
					TonDauThang::insert($arr_insert);
				}else{
					$arr_insert = array();
					$list_prev_month = TonDauThang::where('month','=',$list_month[$key-1]['month'])
												->where('year','=',$list_month[$key-1]['year'])
												->get();
					foreach ($list_prev_month as $key2 => $value2) {
						$arr_insert[$value2['m_product_id']]['m_product_id'] = $value2['m_product_id']; 
						$arr_insert[$value2['m_product_id']]['quantity'] = $value2['quantity']; 
						$arr_insert[$value2['m_product_id']]['month'] = $list_month[$key]['month']; 
						$arr_insert[$value2['m_product_id']]['year'] = $list_month[$key]['year']; 
					}
					$list_product_po = Mproduct::select('m_products.*')
												->where('module_type','=','App\Purchaseorder')
												->leftJoin('purchaseorders','module_id','=','purchaseorders.id')
												->whereRaw('MONTH(`purchaseorders`.`date`)='.$list_month[$key-1]['month'])
												->whereRaw('YEAR(`purchaseorders`.`date`)='.$list_month[$key-1]['year'])
				 	                         ->get()->toArray();
					foreach ($list_product_po as $key2 => $value2) {
						$arr_insert[$value2['m_product_id']]['m_product_id'] = $value2['id'];
						$arr_insert[$value2['m_product_id']]['quantity'] = $value2['quantity']*$value2['specification'];
						$arr_insert[$value2['m_product_id']]['month'] = $value['month'];
						$arr_insert[$value2['m_product_id']]['year'] = $value['year'];
					}

					$list_product_rpo = Mproduct::select('m_products.*')
												->where('module_type','=','App\ReturnPurchaseorder')
												->leftJoin('return_purchaseorders','module_id','=','return_purchaseorders.id')
												->whereRaw('MONTH(`return_purchaseorders`.`date`)='.$list_month[$key-1]['month'])
												->whereRaw('YEAR(`return_purchaseorders`.`date`)='.$list_month[$key-1]['year'])
				 	                         ->get()->toArray();
				 	foreach ($list_product_rpo as $key2 => $value2) {
						if(isset($arr_insert[$value2['m_product_id']])){
							$arr_insert[$value2['m_product_id']]['quantity'] -= $value2['quantity']*$value2['specification'];
						}
					}

					$list_product_so = Mproduct::select('m_products.*')
												->where('module_type','=','App\Saleorder')
												->leftJoin('saleorders','module_id','=','saleorders.id')
												->whereRaw('MONTH(`saleorders`.`date`)='.$list_month[$key-1]['month'])
												->whereRaw('YEAR(`saleorders`.`date`)='.$list_month[$key-1]['year'])
				 	                         ->get()->toArray();
				 	foreach ($list_product_so as $key2 => $value2) {
						if(isset($arr_insert[$value2['m_product_id']])){
							$arr_insert[$value2['m_product_id']]['quantity'] -= $value2['quantity']*$value2['specification'];
						}
					}

					$list_product_rpo = Mproduct::select('m_products.*')
												->where('module_type','=','App\ReturnPurchaseorder')
												->leftJoin('return_purchaseorders','module_id','=','return_purchaseorders.id')
												->whereRaw('MONTH(`return_purchaseorders`.`date`)='.$list_month[$key-1]['month'])
												->whereRaw('YEAR(`return_purchaseorders`.`date`)='.$list_month[$key-1]['year'])
				 	                         ->get()->toArray();
				 	foreach ($list_product_rpo as $key2 => $value2) {
						if(isset($arr_insert[$value2['m_product_id']])){
							$arr_insert[$value2['m_product_id']]['quantity'] += $value2['quantity']*$value2['specification'];
						}
					}
					TonDauThang::insert($arr_insert);
				}
			}
		}
		echo "Done !";
		die;
	}
	public function postUpdateMproduct(Request $request){
		$arr_return= array('status'=>'error','invest'=>0);
		$id = $request->has('id')?$request->input('id'):0;
		$log="";
		if($id){
			$mproduct = MProduct::find($id);
			$mproduct_po = Mproduct::find($mproduct->m_product_id);
			if($request->has('oum_id')  && $mproduct->oum_id != $request->input('oum_id')){
				$old = Oum::find($mproduct->oum_id);
				$new = Oum::find($request->input('oum_id'));
				if($old){
					$log .= 'đơn vị từ "'.$old->name.'" thành "'.$new->name.'" ';
				}else{
					$log .= 'đơn vị từ " " thành "'.$new->name.'" ';
				}
			}
			if($request->has('sell_price')  && $mproduct->sell_price != $request->input('sell_price')){
				$log .= 'giá bán từ "'.$mproduct->sell_price.'" thành "'.$request->input('sell_price').'" ';
			}
			if($request->has('specification')  && $mproduct->specification != $request->input('specification')){
				$log .= 'quy cách từ "'.$mproduct->specification.'" thành "'.$request->input('specification').'" ';
			}
			if($request->has('quantity')  && $mproduct->quantity != $request->input('quantity')){
				$log .= 'số lượng từ "'.$mproduct->quantity.'" thành "'.$request->input('quantity').'" ';
			}
			$mproduct->oum_id =  $request->has('oum_id')?$request->input('oum_id'):0;
			$mproduct->origin_price =  $request->has('origin_price')?$request->input('origin_price'):0;
			$mproduct->specification =  $request->has('specification')?$request->input('specification'):0;
			$old_quantity = $mproduct->quantity ;
			$mproduct->quantity =  $request->has('quantity')?$request->input('quantity'):0;
			$product_stock = ProductStock::where('m_product_id','=',$mproduct_po->id)->first();
			$so_luong_con = $product_stock->in_stock;
			$product_stock->in_stock = $product_stock->in_stock - ($mproduct->quantity*$mproduct->specification);
			$mproduct->invest = $mproduct->specification* $mproduct->quantity* $mproduct->origin_price;
			if($product_stock->in_stock >=0){
				if( !$mproduct->status){
					if($mproduct->save()){
						$product = Product::find($mproduct->product_id);
						Log::create_log(\Auth::user()->id,'App\ReturnPurchaseorder','cập nhật '.$log.' sản phẩm '.$product->sku.' đơn hàng trả nhà cung cấp số '.session('current_returnpurchaseorder'));
						$arr_return['status'] = 'success';
						$arr_return['invest'] = number_format( $mproduct->invest );
					}else{
						$arr_return['message'] = 'Saving fail !';
					}
				}else{
					$arr_return['message'] = 'Đơn hàng đã hoàn thành không thể cập nhật';
				}
			}else{
				$arr_return['message'] = 'Số lượng trả '.$mproduct->name.' lớn hơn số lượng đã nhập<br/> Số lượng đã nhập là '.$so_luong_con.' cái';
			}
		}

		$id = session('current_returnpurchaseorder');
		//Init array
		$list_product = array();

		//Get value
		$returnpurchaseorder = ReturnPurchaseorder::find(session('current_returnpurchaseorder'));
		$list_product = MProduct::select('m_products.*','products.sku','products.name')->where('module_type','=','App\ReturnPurchaseorder')
						->where('module_id','=',$id)
						->where('company_id','=',$returnpurchaseorder['company_id'])
						->leftJoin('products','products.id','=','m_products.product_id')
						->addSelect('oums.name as oum_name')
						->leftJoin('oums','oums.id','=','m_products.oum_id')
						->get()->toArray();
		\Cache::put('list_product_rpo'.\Auth::user()->id, $list_product, 30); 
		$returnpurchaseorder->updated_by = \Auth::user()->id;
		$returnpurchaseorder->save();
		self::getListProduct();
		return $arr_return;
	}
	public function postUpdateMproduct(Request $request){
		$arr_return= array('status'=>'error','amount'=>0);
		$id = $request->has('id')?$request->input('id'):0;
		$log="";
		if($id){
			$mproduct = MProduct::find($id);
			$mproduct_po = Mproduct::find($mproduct->m_product_id);
			$mproduct_so = Mproduct::find($mproduct->m_product_id_so);

			$mproduct_rso_before = Mproduct::where('m_product_id_so','=',$mproduct_so->id)
							->where('module_type','=','App\\ReturnSaleorder')
							->where('company_id','=',$mproduct->company_id)
							->get();
			$mproduct_so->con_lai = $mproduct_so->quantity * $mproduct_so->specification;
			
			foreach ($mproduct_rso_before as $key => $value) {
				$mproduct_so->con_lai -=  $value->quantity * $value->specification;
			}
			$so_luong_con = $mproduct_so->con_lai;
			if($request->has('oum_id')  && $mproduct->oum_id != $request->input('oum_id')){
				$old = Oum::find($mproduct->oum_id);
				$new = Oum::find($request->input('oum_id'));
				if($old){
					$log .= 'đơn vị từ "'.$old->name.'" thành "'.$new->name.'" ';
				}else{
					$log .= 'đơn vị từ " " thành "'.$new->name.'" ';
				}
			}
			if($request->has('sell_price')  && $mproduct->sell_price != $request->input('sell_price')){
				$log .= 'giá bán từ "'.$mproduct->sell_price.'" thành "'.$request->input('sell_price').'" ';
			}
			if($request->has('specification')  && $mproduct->specification != $request->input('specification')){
				$log .= 'quy cách từ "'.$mproduct->specification.'" thành "'.$request->input('specification').'" ';
			}
			if($request->has('quantity')  && $mproduct->quantity != $request->input('quantity')){
				$log .= 'số lượng từ "'.$mproduct->quantity.'" thành "'.$request->input('quantity').'" ';
			}

			$mproduct->oum_id =  $request->has('oum_id')?$request->input('oum_id'):0;
			$mproduct->sell_price =  $request->has('sell_price')?$request->input('sell_price'):0;
			$mproduct->specification =  $request->has('specification')?$request->input('specification'):0;
			$old_quantity = $mproduct->quantity ;
			$mproduct->quantity =  $request->has('quantity')?$request->input('quantity'):0;
			$check_return = ($mproduct_so->con_lai - $mproduct->quantity*$mproduct->specification) >=0;

			$mproduct->origin_price = $mproduct_so->origin_price;
			$mproduct->amount = $mproduct->specification* $mproduct->quantity* $mproduct->sell_price;
			$mproduct->invest = $mproduct->specification* $mproduct->quantity* $mproduct->origin_price;
			// if($product_stock->in_stock >=0){
				if( $check_return ){
					if($mproduct->save()){
						$product = Product::find($mproduct->product_id);
						Log::create_log(\Auth::user()->id,'App\ReturnSaleorder','cập nhật '.$log.' sản phẩm '.$product->sku.' đơn hàng đại lý trả số '.session('current_returnsaleorder'));
						$arr_return['status'] = 'success';
						$arr_return['amount'] = number_format( $mproduct->amount );
					}else{ 
						$arr_return['message'] = 'Saving fail !';
					}
				}else{
					$arr_return['message'] = 'Số lượng sản phẩm trả về lớn hơn số lượng còn lại trong kho <br/> Số lượng còn lại trong kho là '.$so_luong_con.' cái';
				}
			// }else{
			// 	$arr_return['message'] = 'Số lượng trả hàng lớn hơn số lượng đã bán';
			// }
		}

		//Init array
		$list_product = array();
		//Get value
		$returnsaleorder = ReturnSaleorder::find(session('current_returnsaleorder'));
		$list_product = MProduct::select('m_products.*','products.sku','products.name')->where('module_type','=','App\ReturnSaleorder')
						->where('module_id','=',$id)
						->where('company_id','=',$returnsaleorder['company_id'])
						->leftJoin('products','products.id','=','m_products.product_id')
						->addSelect('oums.name as oum_name')
						->leftJoin('oums','oums.id','=','m_products.oum_id')
						->get()->toArray();

		\Cache::put('list_product_rso'.\Auth::user()->id, $list_product, 30);

		
		$returnsaleorder->updated_by = \Auth::user()->id;
		$returnsaleorder->save();
		self::getListProduct();
		return $arr_return;
	}
	public function postListRevenueDistributeYear(Request $request){
		DB::enableQueryLog();
		$list_order = array();
		$year = $request->has('year')?$request->input('year'):0;
		$begin = date('Y-m-d H:i:s',strtotime('1-1-'.$year));
		$end = date('Y-m-d H:i:s',strtotime('1-1-'.($year+1)));
		$key_order = 1;
		$arr_company = array();
		$list_so = Mproduct::select('m_products.*','companies.name','products.id','saleorders.date','ncc.company_id')
					->addSelect(DB::raw(' sum(amount) as sum_amount , sum(invest) as sum_invest'))
					->leftJoin('products','products.id','=','m_products.product_id')
					
					->leftJoin('saleorders',function($join){
						$join->on('saleorders.id','=','m_products.module_id')
							->where('module_type','=','App\Saleorder');
					})
					->leftJoin(DB::raw('(select id,company_id from m_products where module_type="App\\\\Purchaseorder" or module_type="in_stock") as ncc'),'ncc.id','=','m_products.m_product_id')
					->leftJoin('companies','companies.id','=','ncc.company_id')
					->where('saleorders.date','>=',$begin)
					->where('saleorders.date','<',$end)
					->where('saleorders.status','=',1)
					->groupBy('ncc.company_id')
					->get()->toArray();
		foreach ($list_so as $key => $value) {
			$list_order[$key_order]['id'] = $value['id'];
			$list_order[$key_order]['name'] = $value['name'];
			$list_order[$key_order]['date'] =  $value['date'];
			$list_order[$key_order]['sum_amount'] =  $value['sum_amount'];
			$list_order[$key_order]['sum_invest'] =  $value['sum_invest'];
			$list_order[$key_order]['khoang_giam'] =  0;
			$list_order[$key_order]['lai'] =  $list_order[$key_order]['sum_amount'] - $list_order[$key_order]['sum_invest'];
			$list_order[$key_order]['loi_nhuan'] = $list_order[$key_order]['lai'] - $list_order[$key_order]['khoang_giam'];
			$list_order[$key_order]['updated_at'] = $value['updated_at'];
			$arr_company[$key_order] = $value['company_id'];
			$key_order++;
		}
		$list_rso = Mproduct::select('m_products.*','products.name','products.id','return_saleorders.date','ncc.company_id')
					->addSelect(DB::raw(' sum(amount) as sum_amount , sum(invest) as sum_invest'))
					->leftJoin('products','products.id','=','m_products.product_id')
					->leftJoin('return_saleorders',function($join){
						$join->on('return_saleorders.id','=','m_products.module_id')
							->where('module_type','=','App\ReturnSaleorder');
					})
					->leftJoin(DB::raw('(select id,company_id from m_products where module_type="App\\\\Purchaseorder" or module_type="in_stock") as ncc'),'ncc.id','=','m_products.m_product_id')
					->leftJoin('companies','companies.id','=','ncc.company_id')
					->where('return_saleorders.date','>=',$begin)
					->where('return_saleorders.date','<',$end)
					->where('return_saleorders.status','=',1)
					->groupBy('ncc.company_id')
					->get()->toArray();
		foreach ($list_rso as $key => $value) {
			$check_in_array = array_search($value['company_id'], $arr_company);
			if($check_in_array){
				$list_order[$check_in_array]['sum_amount'] -=  $value['sum_amount'];
				$list_order[$check_in_array]['sum_invest'] -=  $value['sum_invest'];
				$list_order[$check_in_array]['khoang_giam'] -=  (abs($value['sum_amount']) - abs($value['sum_invest']));
				$list_order[$check_in_array]['loi_nhuan'] = $list_order[$check_in_array]['lai'] + $list_order[$check_in_array]['khoang_giam'];
			}else{
				$list_order[$key_order]['id'] = $value['id'];
				$list_order[$key_order]['name'] = $value['name'];
				$list_order[$key_order]['date'] =  $value['date'];
				$list_order[$key_order]['sum_amount'] =  -$value['sum_amount'];
				$list_order[$key_order]['sum_invest'] =  -$value['sum_invest'];
				$list_order[$key_order]['khoang_giam'] =  - (abs($list_order[$key_order]['sum_amount']) - abs($list_order[$key_order]['sum_invest']));
				$list_order[$key_order]['lai'] =  0;
				$list_order[$key_order]['loi_nhuan'] = $list_order[$key_order]['lai'] + $list_order[$key_order]['khoang_giam'];
				$list_order[$key_order]['updated_at'] = $value['updated_at'];
				$key_order++;
			}
		}

		$date = array();
		foreach ($list_order as $key => $value) {
			$date[$key] = $value['date'];
		}
		array_multisort($date,SORT_ASC,$list_order);

		$arr_cache = [
					'year'=>$year,
					'list_order'=>$list_order,
				];

		\Cache::put('list_revenue_distribute_year'.\Auth::user()->id, $arr_cache, 30);
		return view('revenue.list-revenue-distribute-year',[
				'list_order' => $list_order
			]);
	}
	public function anyAddProduct(Request $request){
		$arr_return = array(
			"status"=>'success'
		);
		$id = $request->has('id')?$request->input('id'):0;
		$company_id = $request->has('company_id')?$request->input('company_id'):0;
		$module_id = session('current_purchaseorder');
		$module_type = 'App\Purchaseorder';
		$arr_product = session('product_of_po'.session('current_purchaseorder'));
		$arr_product_of_po = Mproduct::where('module_id','=',$module_id)
						->where('module_type','=',$module_type)
						->lists('product_id');
		$log = "";
		foreach ($arr_product as $key => $product_id) {
			if(!in_array($product_id, $arr_product_of_po)){
				$product = Product::find($product_id);
				$last_mproduct = Mproduct::where('product_id','=',$product_id)->get()->last();
				$mproduct = new MProduct;
				$mproduct->company_id	=	$company_id;
				$mproduct->product_id	=	$product_id;
				$mproduct->module_id	= 	$module_id;
				$mproduct->id	= 	$id;
				$mproduct->module_type	=	$module_type;
				if($last_mproduct){
					$mproduct->specification	=	$last_mproduct->specification;
					$mproduct->oum_id		=	$last_mproduct->oum_id;
					$mproduct->origin_price	=	$last_mproduct->origin_price;
				}else{
					$mproduct->specification	=	0;
					$mproduct->oum_id			=	0;
					$mproduct->origin_price		=	0;
				}

				$mproduct->save();
				$last_sellprice = SellPrice::where('product_id','=',$product_id)->orderBy('m_product_id','desc')->first();
				if($last_sellprice){
					$arr_sellprice = SellPrice::where('m_product_id','=',$last_sellprice->m_product_id)->get()->toArray();
					foreach ($arr_sellprice as $key => $value) {
						$sellprice = new SellPrice;
						$sellprice->name = $value['name'];
						$sellprice->price = $value['price'];
						$sellprice->m_product_id = $mproduct->id;
						$sellprice->product_id = $value['product_id'];
						$sellprice->save();
					}
				}

				if(!$product->check_in_stock){
					$product->check_in_stock = 1;
					$product->save();
				}
				if($log==""){
					$log .= "Thêm sản phẩm ".$product->sku;
				}else{
					$log .= ", ".$product->sku;
				}
			}
		}


		$log_delete = "";
		foreach ($arr_product_of_po as $key => $product_id) {
			if(!in_array($product_id, $arr_product)){
				$product = Product::find($product_id);
				$mproduct = MProduct::where('module_id','=',$module_id)
						->where('module_type','=',$module_type)
						->where('product_id','=',$product_id)->first()->toArray();

				$id_product = $mproduct['product_id'];
				$quantity = $mproduct['quantity'];
				$check = MProduct::where('module_id','=',$module_id)
						->where('module_type','=',$module_type)
						->where('product_id','=',$product_id)->delete();
				if($check){
					$product_stock = ProductStock::where('m_product_id','=',$mproduct['id'])->delete();
				}
				if($log==""){
					$log .= "xóa sản phẩm ".$product->sku;
				}else{
					$log .= ", ".$product->sku;
				}
			}
		}
		if($log_delete !="")
			Log::create_log(\Auth::user()->id,'App\Purchaseorder',$log.' và .'.$log_delete.' đơn hàng đại lý trả số '.session('current_purchaseorder'));
		else
			Log::create_log(\Auth::user()->id,'App\Purchaseorder',$log.'vào đơn hàng mua số '.session('current_purchaseorder'));
		$purchaseorder = Purchaseorder::find(session('current_purchaseorder'));
		$purchaseorder->updated_by = \Auth::user()->id;
		$purchaseorder->save();
		self::getListProduct();
		return $arr_return;
	}
	public function anyUpdateOrder(Request $request){
		$arr_return = ['status'=>'error'];
		$arr_order = $request->has('arr_order')?$request->input('arr_order'):array();
		$check = true;
		foreach ($arr_order as $key => $value) {
			if($check){
				$tmp = Mproduct::where('id','=',$value)->update(['order'=>$key]);
				$check = $check && $tmp;
			}
		}
		if($check){
			$arr_return['status'] = 'success';
		}else{
			$arr_return['message'] = 'Save error';
		}
		return $arr_return;
	}