<?php
use Datatables as Dtables;
class ProductsController extends \BaseController {

	/**
	 * Display a listing of the resource.
	 * GET /products
	 *
	 * @return Response
	 */
	public function index()
	{
		if(!UserRole::has("list_product")) return Redirect::route('dashboard');
		/**
		 * Return only view loading data using ajax
		 */
		return View::make('products.index');
	}
	
	/**
	 * Get Products For Datatable Ajax Request
	 *
	 * @return Json
	 * @author Panith
	 **/
	public function productsList()
	{
		$stockId 	= Auth::user()->stock;
		$term 		= Input::get('term');
		$customers = DB::table('Outlets')
		               ->join('Products', 'Products.id', '=', 'Outlets.product_id')
		               ->join('Stocks', 'Stocks.id', '=', 'Outlets.stock_id')
		               ->where('Stocks.type', 'sale')
		               ->where(function($query) use($stockId,$term) {
				               $query->where('Outlets.stock_id',$stockId)
				                     ->where('Products.name','LIKE','%'.$term.'%')->orWhere('Products.name_kh','LIKE','%'.$term.'%');
		                })->select(['Products.id','Outlets.price','Products.name','Products.name_kh','Products.thumbnail'])->get();
		return Response::json(array(
					'customers'			=>	$customers,
					'error' 				=> false),
					200
				);
	}

	/**
	 * Get Product in stock up and down for display
	 * @return Datatable result
	 */
	public function getProducts() {
		$products = Product::getInStocks();
		if (Request::ajax())
		{
   	 return Datatables::of($products)
   	 				->editColumn('name', '{{ str_limit($name,50,"...") }}')
   	 				->editColumn('amount', '{{$amount}} {{ $unit }}')
   	 				->editColumn('price', '{{ money($price) }}')
   	 				->editColumn('price_wholesale', '{{ money($price_wholesale) }}')
            ->editColumn('action',
            		'
            		@if(UserRole::has("show_product"))
	            		<a href="{{ route("product.show", $id)}}" class="btn btn-default btn-xs"><i class="fa fa-th-list"></i> {{ trans("buttons.view") }}</a>
	            	@endif
	            	@if(UserRole::has("edit_product"))
	            		<a href="{{ route("product.edit", $id)}}" class="btn btn-info btn-xs"><i class="fa fa-edit"></i> {{ trans("buttons.edit") }}</a>
      					@endif
      					<a href="{{ route("products.duplicate", $id)}}" class="btn btn-success btn-xs"><i class="fa fa-copy"></i> {{ trans("products.copy") }}</a>
      					@if(UserRole::has("delete_product"))
	      					<a href="#" class="btn btn-xs btn-danger" data-toggle="modal" data-target="#myModal{{$id}}"><i class="fa fa-trash"></i></a>
      					@endif
			          @if(UserRole::has("print_barcode"))
			            <a class="btn btn-xs btn-danger" href="{{ URL::route("barcode",array($id,4)) }}" title="" target="_blank"><i class="fa fa-barcode"></i></a>
			          @endif
          			<div class="modal fade" id="myModal{{$id}}" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
							  <div class="modal-dialog modal-primary" role="document">
							    <div class="modal-content">
							      <div class="modal-header">
							        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
							        <h4 class="modal-title" id="myModalLabel">{{Trans("dashboard.crud.remove")}}</h4>
							      </div>
							      <div class="modal-body">
							        {{Trans("messages.delete-confirm", array("attribute" => $name))}}?
							      </div>
							      <div class="modal-footer">
							        <button type="button" class="btn btn-outline pull-left" data-dismiss="modal">{{Trans("dashboard.others.no")}}</button>
							        {{ Form::open(array("action" => array("product.destroy",$id),"method"=>"DELETE"))}}
							        {{ Form::hidden("_method", "DELETE") }}
							        <button type="submit" class="btn btn-outline">{{Trans("dashboard.others.yes")}}</button>
							        {{ Form::close() }}
							      </div>
							    </div>
							  </div>
							</div>
      				'
            )
            ->make(true);
     }
	}

	/**
	 * Export Products List To Excel
	 *
	 * @return void
	 * @author Panith
	 **/
	public function exportProductsToExcel() {
		ob_end_clean();
		ob_start();
		$products = Product::leftJoin("outlets", 'outlets.product_id', '=', 'products.id')
										->select(
										'products.sku', 
										'products.name', 
										'products.name_kh', 
										'products.price',
										'products.price_in',
										'products.price_wholesale',
										'products.min_amount',
										'products.max_amount',
										'products.unit_id',
										'products.item_location_id',
										'products.product_category_id'
									)->get();	
		Excel::create('products', function ($excel) use($products) {
			$excel->sheet("Export Products", function ($sheet) use($products) {
				$sheet->fromArray($products);
			});
		})->download('xls');
	}

	/**
	 * Uploads batch products with excel
	 * @return boolean True/False
	 */
	public function importProductsByExcel() {
		// $file = storage_path('exports/List.xls');
		ob_end_clean();
		ob_start();
		if(!Input::hasFile('excel_file')) {
			return Redirect::back();
		}
		$file = Input::file('excel_file');
        $existBacodes =  [];
		$x = Excel::load($file, function($reader) {
			// Getting all results

    	$results = $reader->toArray();

	    	foreach ($results as $result) {
	    		if(empty($result['thumbnail'])){
	    			$result['thumbnail'] = \Config::get('app.ip').'uploads/none.jpg';
	    		}
	    		else {
	    			$result['thumbnail'] = \Config::get('app.ip').'uploads/'.$result['thumbnail'];
	    		}
	    		$result['amount'] = (!$result['amount']) ? 0 : $result['amount'];
	    		// $existProduct = Product::where('sku',$result['sku'])->first();
	    		// if(!$existProduct) {
	    			DB::select("SET FOREIGN_KEY_CHECKS=0");
		    		$product = Product::create($result);
		    		// Add all product in to outlet
		    		$outlet  = Outlet::create([
		    			'product_id' => $product->id,
		    			'price'	=> $product->price,
		    			'sku'   => $product->sku,
		    			'amount' => $result['amount'],
		    			'available_amount' => $result['amount'],
		    			'stock_id' => Auth::user()->stock_id,
		    			'user_id'  => Auth::user()->id,
		    			'note' => "Import Products by Excel file"
		    		]);
		    		if($product && $result['amount'] > 0) {
		    			$history = new History;
							$history->product_id = $product->id;
							$history->amount = $result['amount'];
							$history->operation_type = "in"; 
							$history->user_id = Auth::user()->id;
							$history->operated_on = "product";
							$history->stock_id = Auth::user()->stock_id;
							$history->save();
		    		}
	    		}
	    	//}
		});
		return Redirect::back()->with('message','messages.success-to-create')->with('messageType','success');
	}

	/**
	 * Import Product form
	 * @return view
	 */
	public function importForm()
	{
		if(!UserRole::has('import_product')) return Redirect::route('dashboard');
		return View::make('products.import');
	}

	/**
	 * Show the form for creating a new resource.
	 * GET /products/create
	 *
	 * @return Response
	 */
	public function create()
	{
		if(!UserRole::has('create_product')) return Redirect::route('dashboard');
		$categories  		=	ProductCategory::all()->lists('name', 'id');
		$categories[0] = "None";
	  $item_locations =	ItemLocation::all()->lists('name', 'id');
		$item_locations[0] = "None";
		$suppliers 			=	Supplier::all()->lists('company_name', 'id');
		$suppliers[0] = "None";
		$units 			=	Unit::all()->lists('name', 'id');
		$units[0] = "None";
		$brands = Brand::lists('name', 'id');
		$brands[0] = "None";
		return View::make('products.create_v2')
						->with('categories', $categories)
						->with('item_locations', $item_locations)
						->withUnits($units)
						->withBrands($brands)
						->with('suppliers', $suppliers);
	}

	/**
	 * Store a newly created resource in storage.
	 * POST /products
	 *
	 * @return Response
	 */
	public function store()
	{
		$sku = trim(Input::get('sku'));
		$existed_sku = Product::where('sku', $sku)->count();
		if ($existed_sku >= 1) {
            return Redirect::back()
                 ->withInput()
                 ->with('message','messages.duplicated_sku')
                 ->with('messageType','danger');
		}
    $data = Input::except('_token','submit', 'amount');
    if (!empty($data['max_amount']) && $data['max_amount'] > 0) {
         if (Input::get('amount') > $data['max_amount']) return Redirect::back()->withInput()->withMessage('messages.product_max_amout')->with('messageType', 'warning');
    }
		$success = false;
    DB::beginTransaction();
    $path = "uploads/products/";
    try {
		if(Input::get('product_category_id') == 0) $data['product_category_id'] = null;
		if(Input::get('item_location_id') == 0) $data['item_location_id'] = null;
		if(Input::get('supplier_id') == 0) $data['supplier_id'] = null;
		if(Input::get('unit_id') == 0) $data['unit_id'] = null;
    if(empty(Input::get('expired_date'))) $data['expired_date'] = null;
    if(empty(Input::get('turn_off_notification'))) $data['turn_off_notification'] = null;

		if(Input::hasFile('thumbnail')) {
			$data['thumbnail'] = Helper::uploadFile(Input::file('thumbnail'), $path);
		}
		else {
			if(!empty(Input::get("image_name"))) {
    		$destinationPath = public_path() . DIRECTORY_SEPARATOR . Product::getUploadPath();
    		$imageName = uniqid() . '.jpg';
				saveImage(Input::get("image_name"),$destinationPath,$imageName);
				$data['thumbnail'] = \Config::get('app.ip'). DIRECTORY_SEPARATOR . Product::getUploadPath() . $imageName;
    	    } else {
			    $data['thumbnail'] = \Config::get('app.ip').'uploads/none.jpg';
			}
		}
  		$data['user_id'] = Auth::user()->id;
      // run the validation rules on the inputs from the form
      $validator = Validator::make(Input::all(), [
          'name'      =>    'required',
          'name_kh'   =>    'required'
      ]);
      $messages = $validator->messages();
      if ($validator->fails())
          return Redirect::back()
  				->withInput()
  				->withErrors($validator)
  				->with('message','messages.fail-to-create')
  				->with('messageType','danger');
  		$product = Product::create($data);
  		$amount = Input::get('amount');
  		if($product) {
  			$history = new History;
  			$history->product_id = $product->id;
  			$history->amount = $amount;
  			$history->ref_id = $data['ref_id'];
  			$history->operation_type = "in";
  			$history->user_id = Auth::user()->id;
  			$history->operated_on = "product";
  			$history->stock_id = Auth::user()->stock_id;
  			$history->save();
  			$outlet = Outlet::create([
					'product_id' 	=> $product->id,
					'amount'			=> $amount,
					'available_amount' => $amount,
					'user_id'			=> Auth::user()->id,
					'price'				=> $product->price,
					'sku'					=> $product->sku,
					'stock_id'		=> Auth::user()->stock_id
			  ]);
  			if($history->id && $outlet->id) {
  				$success = true;
  			}
  			else{
  				$success = false;
  			}

  		}
    } catch (\Exception $e) {
    	return $e->getMessage();
    }
    if (!$success) {
        DB::rollback();
        if (Input::get('duplicate')) return Redirect::route('product.index')->withMessage('messages.success-to-create', 'success');
        return Redirect::back()->withInput()->with('message','messages.fail-to-create')->with('messageType','danger');
    } else {
    	DB::commit();
      return Redirect::back()->with('message','messages.success-to-create')->with('messageType','success');
    }
	}

	/**
	 * Display the specified resource.
	 * GET /products/{id}
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function show($id)
	{
		if(!UserRole::has('show_product')) return Redirect::route('dashboard');
		$histories = History::getForProduct($id);
		$product = Product::byId($id);
		$previous = Product::where('id', '<', $product->id)->where('status', '<>', 'draft')->max('id');
    $next 		= Product::where('id', '>', $product->id)->where('status', '<>', 'draft')->min('id');
		if (Request::wantsJson())
		{
			$product->thumbnail = asset('uploads/products/'.$product->thumbnail);
			return Response::json(array(
				'product'			=>	$product,
				'error' 				=> false),
				200
			);
		}
		return View::make('products.show', [
					'product' => $product,
					'histories'=>$histories,
					'previous' => $previous,
					'next'     => $next
				]);
	}
	/**
	 * Show the form for editing the specified resource.
	 * GET /products/{id}/edit
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id)
	{
		if(!UserRole::has("edit_product"))
			return Redirect::route('dashboard');
		$product = Product::find($id);
		$categories  		=	ProductCategory::all()->lists('name', 'id');
		$categories[0] = "None";
	  $item_locations =	ItemLocation::all()->lists('name', 'id');
		$item_locations[0] = "None";
		$suppliers 			=	Supplier::all()->lists('company_name', 'id');
		$suppliers[0] = "None";
		$units 			=	Unit::all()->lists('name', 'id');
		$units[0] = "None";
		$brands = Brand::lists('name', 'id');
		$brands[0] = "None";
		return View::make('products.edit_v2')
						->with('product', $product)
						->with('categories', $categories)
						->with('item_locations', $item_locations)
						->withUnits($units)
						->withBrands($brands)
						->with('suppliers', $suppliers);
	}

	/**
	 * Update the specified resource in storage.
	 * PUT /products/{id}
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update($id)
	{
		if(!UserRole::has("edit_product"))
			return Redirect::route('dashboard');
		$thisSKU = Product::find($id);
		if (($thisSKU->sku != Input::get('sku')) && 
				ifExist('Product', 'sku', Input::get('sku'))) {
					return Redirect::back()
				                 ->with('message', 'duplicated_sku')
				                 ->with('messageType', 'danger')->withInput();
		}
		$success = false;
    DB::beginTransaction();
    $path = "uploads/products/";
    try {
    	$data = Input::except('_token','amount', 'submit');
	    if(Input::get('product_category_id') == 0) $data['product_category_id'] = null;
			if(Input::get('item_location_id') == 0) $data['item_location_id'] = null;
			if(Input::get('supplier_id') == 0) $data['supplier_id'] = null;
			if(Input::get('unit_id') == 0) $data['unit_id'] = null;
      if(empty(Input::get('expired_date'))) $data['expired_date'] = null;
      if(empty(Input::get('turn_off_notification'))) $data['turn_off_notification'] = null;

			$product = Product::find($id);
			if(Input::hasFile('thumbnail')) {
				$data['thumbnail'] = Helper::uploadFile(Input::file('thumbnail'), $path);
			} else {
				if(!empty(Input::get("image_name"))) {
		    	    $destinationPath = public_path() . DIRECTORY_SEPARATOR . Product::getUploadPath();
		    	    $imageName = uniqid() . '.jpg';
				    saveImage(Input::get("image_name"),$destinationPath,$imageName);
				    $data['thumbnail'] = \Config::get('app.ip'). DIRECTORY_SEPARATOR . Product::getUploadPath() . $imageName;
		        } else {
					$data['thumbnail'] = $product->thumbnail;
				}
			}
        // run the validation rules on the inputs from the form
      $validator = Validator::make(Input::all(), [
          'name'      =>    'required',
          'name_kh'   =>    'required'
      ]);
      $messages = $validator->messages();
      if($validator->fails()) return Redirect::back()
          ->withInput()
          ->withErrors($messages)
          ->withMessage('messages.fail-to-update')
          ->with('messageType', "danger");
			$product = $product->update($data);
			if (!empty(Input::get('location'))) {
				$outlet = Outlet::where('product_id', $id)->first();
				$outlet->location = Input::get('location');
				$outlet->save();
			}
			if(UserRole::has('change_product_price')) {
				$outlet = Outlet::where('product_id','=',$id)->update(['sku'=> $data['sku'],'price'=>$data['price']]);
			}
			$order = Order::where('product_id','=',$id)->update(['sku'=> $data['sku']]);
			if($product) {
				$success = true;
			}
      } catch (\Exception $e) {
      	return dd($e->getMessage());
      }
      if (!$success) {
          DB::rollback();
          return Redirect::back()
						->withInput()
						->with('message','messages.fail-to-update')
						->with('messageType','danger');
      } else {
      	DB::commit();
        return Redirect::back()
					->withInput()
					->with('message','messages.success-to-update')
					->with('messageType','success');
      }
	}

	/**
	 * Update Reference
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public static function updateRef($id)
	{
		$history = History::find($id);
		$history->ref_id = Input::get('ref_id');
		$history->save();
		if($history) {
			return Response::json(array(
				'message'=> "Successfully updated",
				'error' => false),
				200
			);
		}
		else {
			return Response::json(array(
				'messageType'=>'success-bg',
				'message'=> "Something Went Wrong",
				'error' => true),
				200
			);
		}
	}

  /**
  * Add Product Category for select2
  */
  public static function addProductCategory() {
    $categoryName = Input::get("category_name");
    $existCategory = ProductCategory::where('name', $categoryName)->first();
    if($existCategory) {
      return Response::json(array(
        'msg'=> trans('products.category_existing'),
        'error' => true),
        200
      );
    }
    else {
      $addCategory = ProductCategory::create([
        'name' => $categoryName
      ]);
      if($addCategory) {
        return Response::json(array(
          'category' => $addCategory,
          'error' => false,
          'msg'   =>  trans('messages.success-to-create')),
          200
        );
      }
    }
  }

  /**
   * Update Amount in stock
   * @param  int $id product id
   * @return mix
   */
	public static function updateAmount($id)
	{
		//return Input::all();
		$product = Outlet::where('product_id', $id)->first();
    $amount = Input::get('amount');
    if ($product->max_amount > 0) {
        if (($amount+$product->amount) > $product->max_amount) 
        	return Redirect::back()->withInput()
                        ->withMessage('messages.product_max_amout')
                        ->with('messageType', 'warning');
    }
    $stock_id = Auth::user()->stock_id;
		if(Input::get('add')){
      $outlet = Outlet::where('product_id', $id)->first();
      $outlet->amount += $amount;
      $outlet->available_amount += $amount;
			$history = new History;
			$history->product_id = $outlet->product_id;
			$history->amount = $amount;
			$history->operation_type = "in";
			$history->user_id = Auth::user()->id;
			$history->operated_on = "product";
			$history->stock_id = $stock_id;
      if ($outlet->save() && $history->save()) return Redirect::back()
                ->with('message','messages.success-to-update')
                ->with('messageType','success');
		}
		else {
			if($product->amount < $amount)
				return Redirect::back()->with('message', "messages.not_enought_amount")->with('messageType', 'danger');
      $outlet = Outlet::where('product_id', $id)->first();
      $outlet->amount -= $amount;
      $outlet->available_amount -= $amount;
			$history = new History;
			$history->product_id = $outlet->product_id;
			$history->amount = $amount;
			$history->operation_type = "out";
			$history->user_id = Auth::user()->id;
			$history->operated_on = "product";
			$history->stock_id = $stock_id;
      if ($outlet->save() && $history->save()) return Redirect::back()
                ->with('message','messages.success-to-update')
                ->with('messageType','success');
		}
    return Redirect::back()->withInput()->with('message','messages.fail-to-update')->with('messageType','danger');
	}
	/**
	 * Remove the specified resource from storage.
	 * DELETE /products/{id}
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id)
	{
		if(!UserRole::has("delete_product"))
			return Redirect::route('dashboard');
		$outlet = Outlet::where('product_id', $id)->first();
		$order = Order::where('product_id', $id)->get();
		if (count($order) > 0) return Redirect::back()->withMessage('messages.not_allow_to_delete')->with('messageType', "warning");
		$histories = History::where("product_id", $id)->get();
		if (count($histories) > 0) {
			foreach ($histories as $history) {
				$h = History::find($history->product_id);
				if (!empty($h)) {
					$h->delete();
				}				
			}
		} 
		$product = Product::find($id)->delete();
		if ($product) {
			return Redirect::back()->withInput()->with('message','messages.success-to-delete')->with('messageType','success');
		} else {
			return Redirect::back()->withInput()->with('message','messages.fail-to-delete')->with('messageType','danger');
		}
	}

	/**
	 * Print Barcod
	 * @param  [type] $id     [description]
	 * @param  [type] $amount [description]
	 * @return [type]         [description]
	 */
	public function printBarCode($id , $amount=NULL) {
		if ($amount) {
			$amount=$amount;
		}
		else {
			$amount=4;
		}
		$product=Product::find($id);
		$barcode="";
		$price =$product->price-(($product->price*$product->discount)/100);
		for ($i=1; $i <= $amount; $i++) {
			$mprice = (Helper::getConfig('invoice_currency') == "riel") ? money($price*Helper::getConfig('invoice_rate'))  : money($price) ;
			$barcode .="<div class='barcode' style='float:left; margin-top:20px; text-align:center; padding-right:30px; font-size:12px;'><div align='center'>".DNS1D::getBarcodeHTML($product->sku, "C93",2,70)."</div>".$product->sku ."<br/>".$product->name."<hr>
			<span style='padding-left:10px;text-align:center; font-size:12px; line-height:22px; font-weight:bold;'>".Trans('products.price')." :".$mprice."</span></div>";
		}
		return "
		<script>
		window.onload = function() { window.print(); }
		</script>
		<style>
		body {
  				margin: 0;
  				font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
  				font-size: 12px;
				}
		@media print {
			.barcode > div div {
                -webkit-print-color-adjust: exact;
    		}
    		body {
  				margin: 0;
  				font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
				}
    	}
    </style>".$barcode;
	}
	/**
	 * Product Before Expired
	 * @return [type] [description]
	 */
	public function getProductsBeforeExpire()
	{
		$products = Product::beforeExpire();
		return View::make('products.before_expire')->withProducts($products);
	}

	/**
	 * Prodcut Min amount
	 * @return [type] [description]
	 */
	public function getProductMin()
	{
		$products = Outlet::join('products', 'products.id', '=', 'outlets.product_id')
                    ->select([
                    	"products.id",
                      "products.sku",
                      "products.name",
                      "products.min_amount", 
                      "outlets.amount",
                      "products.max_amount"
                      ])
                    ->whereRaw('products.min_amount > outlets.amount')
                    ->paginate(10);
		return View::make('products.min_product')->withProducts($products);
	}




	/**
	* Add Quick Unit
	*/
	public function addUnit()
	{
	  $unitName = Input::get('unit_name');
	  $exisUnit = Unit::where('name', $unitName)->first();
	  if ($exisUnit) return [
	    'error' => true,
	    'msg'   =>  trans('products.unit_existing')
	  ];
	  $newUnit = Unit::create(['name' => $unitName]);
	  if ($newUnit) return [
	    'error' => false,
	    'unit'  =>  $newUnit->name,
	    'id'    =>  $newUnit->id,
	    'msg'  =>  trans('messages.success-to-create')
	  ];
	  return ['error' => true, 'msg' => trans('messages.fail-to-create')];
	}

	/**
	* Add Quick Item Location
	*/
	public function addItemLocation()
	{
	  $itemLocation = Input::get('item_location_name');
	  $existItem  = ItemLocation::where('name', $itemLocation)->first();
	  if ($existItem) return [
	    'error' => true,
	    'msg' =>  trans('products.item_location_existing')
	  ];
	  $item = ItemLocation::create([
	    'name'  =>  $itemLocation,
	    'description' =>  "Created when add or update product",
	    'picture' => \Config::get('app.ip').'uploads/none.jpg'
	  ]);
	  if ($item) return [
	    'error' => false,
	    'msg' =>  trans('messages.success-to-create'),
	    'item_location_name'  =>  $item->name,
	    'id'  => $item->id
	  ];
	  return ['error' => false, 'msg' => trans('messages.fail-to-create')];
	}

	/**
	* Add Quick Supplier
	*/
	public function addSupplier()
	{
	  $supplierName = Input::get('company_name');
	  $tel          = Input::get('tel');
	  $existSupplier = Supplier::where('company_name', $supplierName)->orWhere('tel', $tel)->first();
	  if ($existSupplier) return [
	    'error' => true,
	    'msg'   =>  trans('products.supplier_existing')
	  ];
	  $supplier = Supplier::create([
	    'company_name' => $supplierName,
	    'tel'          => $tel,
	    'logo'         => \Config::get('app.ip').'uploads/none.jpg',
	    'contact_photo' =>  \Config::get('app.ip').'uploads/none.jpg'
	  ]);
	  if ($supplier) return [
	    'error' => false,
	    'msg'   => trans('messages.success-to-create'),
	    'company_name'  =>  $supplier->company_name,
	    'id'  =>  $supplier->id
	  ];
	  return ['error' =>  false, 'msg' => trans('messages.fail-to-create')];
	}

	public function prdouctMinExcel()
	{
		ob_end_clean();
		ob_start();
		$products = Outlet::join('products', 'products.id', '=', 'outlets.product_id')
                    ->select([
                      "products.sku",
                      "products.name",
                      "products.min_amount", 
                      "outlets.amount",
                      "products.max_amount",
                      DB::raw('max_amount - amount as order_amount')])
                    ->whereRaw('products.min_amount > outlets.amount')
                    ->get();
		Excel::create('min_products', function ($excel) use($products) {
			$excel->sheet("Min Product", function ($sheet) use($products) {
				$sheet->fromArray($products);
			});
		})->download('xls');
	}

	public function productSale()
	{
		$products = Product::getInStocks();
   	 return Datatables::of($products)
   	 				->editColumn('thumbnail', '
				      	{{ HTML::image($thumbnail, "title", [
		              "width" => "70px",
		              "class" => "grow thumbnail"
				      	])}}
   	 					')
   	 				->editColumn('amount', '{{$amount}} {{ $unit }}')
   	 				->editColumn('price', '{{ money($price) }}')
   	 				->editColumn('price_wholesale', '{{ money($price_wholesale) }}')
   	 				->editColumn('type', '{{ $type ? "Second" : "New" }}')
            ->editColumn('action',
            		'
            		<button class="btn btn-success btn-add-cart" data-id="{{$id}}"><i class="fa fa-plus"></i> {{ trans("backend_sale.select") }}</button>
      				')->make(true);
	}

	public function addBrand()
	{
		$brandName = Input::get('brand_name');
	  $exisBrand = Brand::where('name', $brandName)->first();
	  if ($exisBrand) return [
	    'error' => true,
	    'msg'   =>  trans('products.brand_existing')
	  ];
	  $newBrand = Brand::create([
	  	'name' => $brandName,
	  	'logo'	=>	\Config::get('app.ip').'uploads/brands/none.png'
	  ]);
	  if ($newBrand) return [
	    'error' => false,
	    'brand'  =>  $newBrand->name,
	    'id'    =>  $newBrand->id,
	    'msg'  =>  trans('messages.success-to-create')
	  ];
	  return ['error' => true, 'msg' => trans('messages.fail-to-create')];
	}

	public function duplicate($id)
	{
		$product = Product::find($id);
		$categories  		=	ProductCategory::all()->lists('name', 'id');
		$categories[0] = "None";
	  $item_locations =	ItemLocation::all()->lists('name', 'id');
		$item_locations[0] = "None";
		$suppliers 			=	Supplier::all()->lists('company_name', 'id');
		$suppliers[0] = "None";
		$units 			=	Unit::all()->lists('name', 'id');
		$units[0] = "None";
		$brands = Brand::lists('name', 'id');
		$brands[0] = "None";
		return View::make('products.duplicate')
						->with('product', $product)
						->with('categories', $categories)
						->with('item_locations', $item_locations)
						->withUnits($units)
						->withBrands($brands)
						->with('suppliers', $suppliers);
	}

	public function checkUniqueSku()
	{
		$sku = trim(Input::get('sku'));
		if (empty($sku)) return ['error' => true, 'messages' => trans('validation.required', ['attribute' => trans("products.sku")])];
		$existingSku = Product::where("sku", $sku)->first();
		if ($existingSku) return ['error' => true, 'messages' => trans('products.sku_existing')];
		return ['error' => false, 'messages' => trans('products.available')];
	}
}
?>