public function postUpdate(Request $request)
	{
		$arr_return = array(
					'status' => 'error',
					'message'=>''
				);
		$time =date('H:i:s', time());
		$id_return_purchaseorder = session('current_returnpurchaseorder') !== null ? session('current_returnpurchaseorder') : 0;
		if($id_return_purchaseorder){
			$returnpurchaseorder = ReturnPurchaseorder::find($id_return_purchaseorder);
			session(['current_returnpurchaseorder' => $returnpurchaseorder['id']]);
			$time = date('H:i:s', strtotime($returnpurchaseorder->date));
		}else{

			$returnpurchaseorder = new ReturnPurchaseorder;
			$returnpurchaseorder->date = date("Y-m-d H:i:s");
			$returnpurchaseorder->created_by = \Auth::user()->id;
			$returnpurchaseorder->save();
			Log::create_log(\Auth::user()->id,'App\ReturnPurchaseorder','Tạo mới đơn hàng trả nhà cung cấp số '.$returnpurchaseorder->id);
			session(['current_returnpurchaseorder' => $returnpurchaseorder->id]);
		}
		$log = '';
		$old_company_id = $returnpurchaseorder->company_id;
		if($returnpurchaseorder->status == 0){
			$address = Address::where('module_id','=',$returnpurchaseorder->id)
						->where('module_type','=','App\ReturnPurchaseorder')->first();
			if(!$address){
				$address = new Address;
			}
			if($request->has('company_id')  && $returnpurchaseorder->company_id != $request->input('company_id')){
				$old = Company::find($returnpurchaseorder->company_id);
				if(!$old){
					$old = (object) ['name'=>''];
				}
				$new = Company::find($request->input('company_id'));
				$log .= 'công ty từ "'.$old->name.'" thành "'.$new->name.'" ';
			}
			if($returnpurchaseorder->company_id == $request->input('company_id')){

				if($request->has('user_id')  && $returnpurchaseorder->user_id != $request->input('user_id')){
					$old = User::find($returnpurchaseorder->user_id);
					if(!$old){
						$old = (object) ['name'=>''];
					}
					$new = User::find($request->input('user_id'));
					$log .= 'người liên hệ từ "'.$old->name.'" thành "'.$new->name.'" ';
				}

				$old_date=date("Y-m-d",strtotime($returnpurchaseorder->date));
				$new_date = date("Y-m-d",strtotime($request->input('date')));
				if($request->has('date')  && $old_date != $new_date){
					$log .= 'ngày từ "'.$old_date.'" thành "'.$new_date.'" ';
				}

				if($request->has('company_phone')  && $returnpurchaseorder->company_phone != $request->input('company_phone')){
					$log .= 'số điện thoại từ "'.$returnpurchaseorder->company_phone.'" thành "'.$request->input('company_phone').'" ';
				}

				if($request->has('company_email')  && $returnpurchaseorder->company_email != $request->input('company_email')){
					$log .= 'email từ "'.$returnpurchaseorder->company_email.'" thành "'.$request->input('company_email').'" ';
				}
				if($request->has('address')  && $address->address != $request->input('address')){
					$log .= 'địa chỉ từ "'.$address->address.'" thành "'.$request->input('address').'" ';
				}
				if($request->has('town_city')  && $address->town_city != $request->input('town_city')){
					$log .= 'quận huyện từ "'.$address->town_city.'" thành "'.$request->input('town_city').'" ';
				}

				if($request->has('province_id')  && $address->province_id != $request->input('province_id')){
					$old = Province::find($address->province_id);
					$new = Province::find($request->input('province_id'));
					if(!$old){
						$old = (object) ['name'=>''];
					}
					$log .= 'tỉnh thành từ "'.$old->name.'" thành "'.$new->name.'" ';
				}
				if($request->has('country_id')  && $address->country_id != $request->input('country_id')){
					$old = Country::find($address->country_id);
					$new = Country::find($request->input('country_id'));
					if(!$old){
						$old = (object) ['name'=>''];
					}
					$log .= 'quốc gia từ "'.$old->name.'" thành "'.$new->name.'" ';
				}
			}
			$returnpurchaseorder->company_id = $request->has('company_id') ? $request->input('company_id') : 0;
			$returnpurchaseorder->user_id = $request->has('user_id') ? $request->input('user_id') : 0;
			$returnpurchaseorder->date = $request->has('date') ? date("Y-m-d H:i:s",strtotime($request->input('date').' '.$time)) : date("Y-m-d H:i:s");
			$returnpurchaseorder->company_phone = $request->has('company_phone') ? $request->input('company_phone') : '';
			$returnpurchaseorder->company_email = $request->has('company_email') ? $request->input('company_email') : '';
			$address_id = isset($returnpurchaseorder->address_id) ? $returnpurchaseorder->address_id : 0;

			

			$address->module_id  = $returnpurchaseorder->id;
			$address->module_type  = 'App\\ReturnPurchaseorder';
			$address->address  = $request->has('address') ? $request->input('address') : '';
			$address->town_city  = $request->has('town_city') ? $request->input('town_city') : '';
			$address->zip_postcode  = $request->has('zip_postcode') ? $request->input('zip_postcode') : '';
			$address->country_id  = $request->has('country_id') ? $request->input('country_id') : 0;
			$address->province_id  = $request->has('province_id') ? $request->input('province_id') : 0;
			$address->save();
			$returnpurchaseorder->address_id = $address->id;
		}else{
			$returnpurchaseorder->sum_amount = 0;
			$returnpurchaseorder->sum_invest = 0;
		}
		$old_status = $returnpurchaseorder->status;
		$returnpurchaseorder->status = $request->has('status')?1:0;
		$check_save_in_stock = true;
		if($returnpurchaseorder->status){
			$arr_mproduct = Mproduct::select('m_products.id','quantity','specification','name','m_product_id','invest')
							->where('module_id', '=', $returnpurchaseorder->id)
							->where('module_type', '=', 'App\ReturnPurchaseorder')
							->leftJoin('products','products.id','=','m_products.product_id')
							->get()->toArray();
			foreach ($arr_mproduct as $key => $mproduct) {
				$returnpurchaseorder->sum_amount = $returnpurchaseorder->sum_amount + $mproduct['invest'];
				$mproduct_po = Mproduct::find($mproduct['m_product_id']);
				$product_stock = ProductStock::where('m_product_id','=',$mproduct_po->id)->first();
				$product_stock->in_stock = $product_stock->in_stock -  ($mproduct['quantity']*$mproduct['specification']);
				if($product_stock->in_stock < 0){
					$check_save_in_stock = false;
					$arr_return['message'] .= 'Số lượng sản phẩm '.$mproduct['name'].' nhập vào lớn hơn số lượng đã nhập<br/><br/>';
				}
			}
		}else{
			if($old_status != $returnpurchaseorder->status){
				$arr_mproduct = Mproduct::select('m_products.id','quantity','specification','name','m_product_id')
								->where('module_id', '=', $returnpurchaseorder->id)
								->where('module_type', '=', 'App\ReturnPurchaseorder')
								->leftJoin('products','products.id','=','m_products.product_id')
								->get()->toArray();
				foreach ($arr_mproduct as $key => $mproduct) {
					$mproduct_po = Mproduct::find($mproduct['m_product_id']);
					$product_stock = ProductStock::where('m_product_id','=',$mproduct_po->id)->first();
					$product_stock->in_stock = $product_stock->in_stock + ($mproduct['quantity']*$mproduct['specification']);
					$product_stock->save();
				}
			}
		}

		if($check_save_in_stock){
			$returnpurchaseorder->updated_by = \Auth::user()->id;
			if($returnpurchaseorder->save()){
				Log::create_log(\Auth::user()->id,'App\ReturnPurchaseorder','Cập nhật '.$log.' đơn hàng trả nhà cung cấp số '.$returnpurchaseorder->id);
				if($returnpurchaseorder->status){
					foreach ($arr_mproduct as $key => $mproduct) {
						$mproduct_po = Mproduct::find($mproduct['m_product_id']);
						$product_stock = ProductStock::where('m_product_id','=',$mproduct_po->id)->first();
						$product_stock->in_stock = $product_stock->in_stock -  ($mproduct['quantity']*$mproduct['specification']);
						$product_stock->save();
					}
				}

				if($old_company_id != $returnpurchaseorder->company_id){
					Mproduct::where('module_id', '=', $returnpurchaseorder->id)
						->where('module_type', '=', 'App\ReturnPurchaseorder')
						->where('company_id','=',$old_company_id)
						->delete();
				}else{
					Mproduct::where('module_id', '=', $returnpurchaseorder->id)
						->where('module_type', '=', 'App\ReturnPurchaseorder')
						->update(['company_id' => $returnpurchaseorder->company_id ]);
				}
				$arr_return['status']= 'success';
			}else{
				$arr_return['message']= 'Saving fail !';
			}
		}
		return $arr_return;
	}
	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 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
			]);
	}