<?php

class OrdersController extends \BaseController {

	/**
	 * Display a listing of the resource.
	 * GET /orders
	 *
	 * @return Response
	 */
	public function index($category=NULL)
	{
		if(!user_can('can_sale'))
			return Redirect::route('dashboard');
		$draftInvoices = Invoice::draft()
														->FromStock()
														->leftJoin('Customers','Customers.id','=','Invoices.customer_id')
														->where('Invoices.user_id',Auth::user()->id)
														->select(['Invoices.*','Customers.first_name'])
														->orderBy('Invoices.updated_at','DESC')->paginate(10);
	
		$draftInvoicesNoTotal = Invoice::where('status', 'draft')
											 ->where('total', 0)
											 ->get();
		$invoiceId = InvoiceHelper::getInvoiceID();
		$categories = ProductCategory::all();
		$orders = Order::leftJoin('Products','Products.id','=','Orders.product_id')
									 ->where('invoice_id',$invoiceId)
									 ->select(['Orders.*','Products.name','Products.name_kh','Products.thumbnail','Products.sku'])->get();
		$stockId = Auth::user()->stock_id;
		$productsFromOutlet = Outlet::inStock()
                                ->leftJoin('Products','Products.id','=','Outlets.product_id')
                                ->where('Outlets.stock_id','=',$stockId)
                                ->where('Products.status', 'active')
                                ->orderBy('Products.feature_item','DESC');


		if(!empty($category) && $category != "all") {
			$productsFromOutlet->where('Products.product_category_id','=',$category);
      $category = $category;
		}
    if (!empty(Input::get('q'))) {
      $pattern = "%".Input::get("q")."%";
      $productsFromOutlet->where(function ($query) use($pattern) {
        $query->where("Products.name", "LIKE", $pattern)
              ->orWhere("Products.name_kh", "LIKE", $pattern);
      });
    }
		$view = View::make('sale.index')
			->with('invoiceId', $invoiceId)
			->with('draftInvoices',$draftInvoices)
			->with("draftInvoicesNoTotal", $draftInvoicesNoTotal)
			->with('orders',$orders)
			->with('category',$category)
			->with('categories',$categories)
			->with('total',	InvoiceHelper::getTotal())
			->with('tax',	Helper::getConfig('invoice_tax'))
			->with('grand_total',	InvoiceHelper::calculateTax())
			->with('total_riel', 	InvoiceHelper::calculateTax()*Helper::getConfig('invoice_rate'))
			->with('productsFromOutlet',$productsFromOutlet->paginate(16));

		$invoice = Invoice::find($invoiceId);
		if(!empty($invoice->customer_id)){
			$customer = Customer::getFullName()->where('id',$invoice->customer_id)->lists('full_name', 'id');
			$view = $view->with('customer',$customer);
		}

		return $view;
	}
	public function fetchOrder()
	{
		$invoiceId = InvoiceHelper::getInvoiceID();
		$orders = Order::leftJoin('Products','Products.id','=','Orders.product_id')->where('invoice_id',$invoiceId)->select(['Orders.*','Products.name','Products.name_kh','Products.thumbnail'])->get();
		$orderList = "";
		foreach($orders as $order){
				$orderList .= '<li class="clearfix" data-toggle="modal" data-target=".item-list-modal" data-item-id="item'.$order->product_id.'"  data-order-id="'.$order->id.'" data-product-id="'.$order->product_id.'">';
				$orderList .= '<div class="product-img">'.HTML::image($order->thumbnail, "", array("class" => "img-circle")).'</div>';
				$orderList .= '<div class="product-text clearfix">';
							$orderList .= '<div class="product-name">';
								$orderList .= '<p>';
	   							$orderList .= '<span class="title">'.str_limit($order->name,30,"...") .'</span>';
								   $amountBadge = $order->amount;
	   							$orderList .= '<span class="badge bg-blue '.$amountBadge.'">'.$order->amount .'</span>';
	   						$orderList .= '</p>';
								$orderList .= '<p class="details">'.str_limit($order->name_kh,30,"...").'</p>';
							$orderList .= '</div>';
							$orderList .= '<div class="product-price"><span class="price-val" data-price='.$order->price.'>'.money($order->price).'</span>';
								$classOrder = ($order->discount > 0) ? 'badge bg-red' : "";
								$orderList .= '<span class="discounted '.$classOrder.'">';
									if($order->discount > 0):
										$orderList .= "-".$order->discount."%";
									endif;
								$orderList .= '</span><input type="hidden" class="discount-val" value="'.$order->discount.'">';
							$orderList .= '</div>';
						$orderList .= '</div>';
			   	$orderList .= '</li>';
		}
			return $orderList;
	}

	/**
	 * Show the form for creating a new resource.
	 * GET /orders/create
	 *
	 * @return Response
	 */
	public function create()
	{
		//
	}

	/**
	 * Store a newly created resource in storage.
	 * POST /orders
	 *
	 * @return Response
	 */
	public function store()
	{
		if(!empty(trim(Input::get('sku')))) {
			/*   Get Stock ID from user authentication */
			$stockId = Auth::user()->stock_id;
			/*   Check if the given SKU is correct*/
			$outletItem = Outlet::itemBySku(Input::get('sku'));
			/*   If there is no item found in that stock, return "No found" */
			if(!$outletItem):
				return Response::json(array(
						'message'		=> trans('sale.product_not_found'),
						'error' 		=> true),
						200
					);
			endif;
			/*   By the way, Assign ProductID to the found Product */
			$productId = $outletItem->product_id;
		}
		else {
			$productId = trim(Input::get('productId'));
		}
		/*   Retrieve Invoice ID */
		$invoiceId = InvoiceHelper::getInvoiceID();

		/*   Check if the Outlet contains item with given ID */
			$outlet_product = Outlet::itemByUserId($productId);
		/*   Check if the Outlet doesn't contain item with given ID, return "not found" */
		if(!$outlet_product) {
			return Response::json(array(
					'message'		=> "No Products Found",
					'error' 		=> true),
					200
				);
		}
		/*   Check if the Item have already added to cart with the given Invoice */
		$orderedItem = Order::itemExisting($invoiceId, $productId);
		$price = (Input::has('price') && Input::get("price") > 0) ? Input::get("price") : $outlet_product->price;
		/* If Product Existed in cart */
		if($orderedItem) {
			$amount 	= (Input::has('amount')) ? trim(Input::get('amount')) : $orderedItem->amount + 1;
			$discount = (Input::has('discount')) ? trim(Input::get('discount')) : $orderedItem->discount;
			if(Input::has('wholesale')) {
				$wholesalePrice = getField('Product','id',$outlet_product->product_id,'price_wholesale');
				$price = (Input::has('price')) ? trim(Input::get('price')-calculateDiscount(Input::get('price'),$discount)) : $wholesalePrice-calculateDiscount($wholesalePrice,$discount);
			}
			else {
				$price = (Input::has('price')) ? trim(Input::get('price')-calculateDiscount(Input::get('price'),$discount)) : $outlet_product->price-calculateDiscount($outlet_product->price,$discount);
			}
			$outlet = Outlet::where('product_id', $productId)->first();

			if($amount > ($outlet_product->available_amount + $orderedItem->amount) 
					&& $outlet_product->is_service == false) {
				return Response::json(array(
						'message'		=> trans('sale.not_enough_item', ['attribute' => $outlet_product->amount]),
						'error' 		=> true,
						'out_of_stock'	=>	true
						),
						200
					);
			}
			if ($outlet_product->is_service == false) {
				$outlet->on_hold = $amount;
				$outlet->available_amount = $outlet->amount - $outlet->on_hold;
				$outlet->save();	
			}
			DB::table('Orders')->where('id',$orderedItem->id)->update([
				'amount' 	=>	$amount,
				'price' 	=>	$price,
				'discount' 	=>	$discount,
			]);
			$order = Order::orderedProduct($orderedItem->id);
			$asset_url = $order->thumbnail;
			InvoiceHelper::updateTotal();
			$tax = Helper::getConfig('invoice_tax');
			$tax = (!empty($tax) && $tax <=0) ? 0 : $tax;
			return Response::json(array(
					'message'		=> trans('sale.update_success'),
					'order'			=>	$order,
					'total'			=>	InvoiceHelper::getTotal(),
					'total_riel'			=> InvoiceHelper::calculateTax()*Helper::getConfig('invoice_rate'),
					'grand_total'			=>	InvoiceHelper::calculateTax(),
					'tax'							=>	$tax,
					'update_item'			=>	true,
					'asset_url'	=> $asset_url,
					'error' 		=> false),
					200
				);
		}
		else {
				if($outlet_product->available_amount < 1 && $outlet_product->is_service == false) {
					return Response::json(array(
							'message'		=> trans('sale.no_item'),
							'error' 		=> true),
							200
						);
				}
			if(Input::has('wholesale')) {
				$price = getField('Product','id',$outlet_product->product_id,'price_wholesale');
			}
				$amount = !empty(Input::get('amount')) ? Input::get('amount') : 1;
				$newsale = new Order;
				$newsale->invoice_id = $invoiceId;
				$newsale->product_id = $outlet_product->product_id;
				$newsale->amount = $amount;
				$newsale->sku = $outlet_product->sku;
				$newsale->discount = $outlet_product->discount;
				$newsale->stock_id = Auth::user()->stock_id;
				$newsale->price = $price - calculateDiscount($price,$outlet_product->discount);
				$newsale->user_id = Auth::user()->id;
				// Add on hold for handle product out of stock
				if ($newsale->save()) {
					$outlet = Outlet::where('product_id', $productId)->first();
					if ($outlet_product->is_service == false) {
						$outlet->on_hold += $amount;
						$outlet->available_amount -= $amount;
						$outlet->save();
					}
				}
				$order = Order::orderedProduct($newsale->id);
				$asset_url = asset('uploads/products/'.$order->thumbnail);
				InvoiceHelper::updateTotal();
				return Response::json(array(
					'message'		=>  trans('sale.order_success'),
					'order'			=>	$order,
					'total'			=>	InvoiceHelper::getTotal(),
					'total_riel'			=> InvoiceHelper::calculateTax()*Helper::getConfig('invoice_rate'),
					'update_item'			=>	false,
					'grand_total'			=>	InvoiceHelper::calculateTax(),
					'tax'							=>	Helper::getConfig('invoice_tax'),
					'asset_url'	=> $asset_url,
					'error' 		=> false),
					200
				);
		}
	}

	/**
	 * Remove the specified resource from storage.
	 * DELETE /orders/{id}
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id)
	{
		$order = Order::find($id);
		$outlet = Outlet::where('product_id', $order->product_id)->first();
		if (!empty($outlet)) {
			$outlet_product = Outlet::itemByUserId($order->product_id);
			if ($outlet_product->is_service == false) {
				$outlet->on_hold -= $order->amount;
				$outlet->available_amount += $order->amount;
				$outlet->save();
			}
			$order->delete();
		}
		InvoiceHelper::updateTotal();
		return Response::json(array(
			'message'		=> trans('sale.delete_success'),
			'total'			=>	InvoiceHelper::getTotal(),
			'total_riel'			=> InvoiceHelper::calculateTax()*Helper::getConfig('invoice_rate'),
			'grand_total'			=>	InvoiceHelper::calculateTax(),
			'tax'							=>	Helper::getConfig('invoice_tax'),
			'update_item'			=>	true,
			'error' 		=> false),
			200
		);
	}
	public function discard()
	{
		$invoiceID = InvoiceHelper::getInvoiceID();
		$orders = DB::table('Orders')->where('invoice_id',$invoiceID)->get();
		$success = false;
		if (count($orders) > 0) {
			foreach ($orders as $order) {
				$oldOrder = Order::find($order->id);
				$outlet = Outlet::where('product_id', $order->product_id)->first();
				$outlet_product = Outlet::itemByUserId($order->product_id);
				if ($outlet_product->is_service == false) {
					$outlet->on_hold -= $order->amount;
					$outlet->available_amount += $order->amount;
					$outlet->save();
				}
				if ($oldOrder->delete()) {
					$success = true;
				}
			}
		}
		if($success):
			InvoiceHelper::updateTotal();
			Invoice::find($invoiceID)->delete();
		endif;
		return Redirect::back();
	}
  public function getProductPriceIn($id)
  {
      $product = DB::table('products')
                  ->select('price_in')
                  ->where('id', $id)->first();
      if($product) return $product->price_in;
      return null;
  }

   /**
     * New Order Product
     * @return array
     */
    public function newOrderProduct()
    {
    	$sku = trim(Input::get('sku'));
    	$invoiceId = InvoiceHelper::getInvoiceID();
    	$outlet  = Outlet::where('sku', $sku)->first();
    	if ($outlet) {
    		$ordered = Order::where('product_id', $outlet->product_id)->where('invoice_id', $invoiceId)->first();
    		$product = Product::find($outlet->product_id);
    		if ($ordered) return ['error' => false, 'obj' => $ordered, 'amount' => $ordered->amount, 'p_name' => $product->name];
    		if ($outlet->available_amount <= 0) {
    			return ['error' => true, 'message' => trans('sale.sold_out')];
    		}
    		return ['error' => false, 'obj' => $outlet, 'amount' => 0, 'p_name' => $product->name];

    	} 
    	return ['error' => true, 'pnf' => "true", 'message' => trans('sale.product_not_found'),];
    }

    /**
     * Check Price IN
     * @return array
     */
   	public function checkPriceIn()
   	{
   		$productId  = Input::get('productId');
   		$price 			= Input::get('price');
   		$amount 		= Input::get('amount');
   		$discount   = Input::get('discount');
			if ($price < $this->getProductPriceIn($productId)) {
				return ['error' => true, 'lower_price' => true, 'productId' => $productId, 'price'	=>	$price, 'amount' => $amount, 'discount' => $discount, 'title' => trans('sale.price_in_is', ['attribute' => money($this->getProductPriceIn($productId))]), 'message' => trans("sale.msg_sale_lower_price_in")]; 
			}
			return ['error' => false, 'productId' => $productId, 'price' => $price, 'amount' => $amount, "discount" => $discount];
   	}

}
