<?php 
class BackendSale extends BaseController {

	/**
	 * Return index of backend sale
	 * @return mix
	 */
	public function index($id) {
		$invoice = Invoice::find($id);
		if (empty($invoice)) return Redirect::route('sale');
		$products = DB::table('products as p')->join('orders as o', 'o.product_id', '=', 'p.id')
									->select('o.sku', 'p.name', 'o.amount', 'o.price')
									->where('o.invoice_id', $invoice->id)->get();

		if (count($products) <= 0) return Redirect::route('sale');
		return View::make("backend_sale.index")
								->with('invoice', $invoice)
								->with('products', $products);
	}

	/**
	 * Add new Product
	 */
	public function addProduct() {
		// Declare reusable variables
		$invoiceId = InvoiceHelper::getInvoiceID();
		$sku = trim(Input::get('sku'));
		$amount = Input::get('amount');
		DB::beginTransaction();
		try {
			// Check duplicate barcode in product
			$product = Product::where('sku', $sku)->first();
			if (!empty($product)) return ['error' => true, 'msg' => trans('backend_sale.exiting_sku')];
			// create new product
			$product = new Product;
			$product->sku  = $sku;
			$product->name = Input::get('name');
			$product->name_kh = Input::get('name');
			$product->price_in = Input::get('price');
			$product->price = Input::get('price');
			$product->price_wholesale = Input::get('price');
			$product->comment = Input::get('comment');
			$product->is_second_hand = true;
			$product->thumbnail = \Config::get('app.ip').'uploads/none.jpg';
			$product->ref_id = $invoiceId;
			if ($product->save()) {
				// Store Product buy
				$buy_product = BuyProduct::create([
					'invoice_id' => $invoiceId,
					'product_id' => $product->id,
					'qty'				=> $amount,
					'price'     => $product->price_in,
					'sku'       => $product->sku
				]);
				if ($buy_product) {
					DB::commit();
					return ['erorr' => false, 'msg' => trans('messages.success-to-create')];
				} else {
					DB::rollBack();
					return ['error' => true, 'msg' => trans('messages.fail-to-create')];
				}
			}
		} catch (Exception $e) {
			DB::rollBack();
			return ['data' => $e->getMessage()];
			return ['error' => true, 'msg' => trans('messages.fail-to-create')];
		}		
	}

	/**
	 * Get Product table
	 * @return [type] [description]
	 */
	public function getTableProducts() {
		$invoiceId = Input::get('invoiceId');
		$products = DB::table('products as p')
									->join('buy_products as bp', 'bp.product_id', '=', 'p.id')
									->select('p.id','p.sku', 'p.name', 'bp.qty', 'bp.price', 'bp.id as bp_id')
									->where('bp.invoice_id', $invoiceId)
									->get();
		return View::make('backend_sale.table', ['products' => $products, 'invoiceId' => $invoiceId]);
	}

	/**
	 * Get Product
	 * @return [type] [description]
	 */
	public function getProductSecondHand()
	{
			$products = DB::table('products')->join('outlets', 'outlets.product_id', '=', 'products.id')
										->select('products.name', 'products.price_in', "products.id", 'products.sku')
			              ->where('is_second_hand', true);
			 return Datatables::of($products)
   	 				->editColumn('price_in', '{{ money($price_in) }}')
            ->editColumn('action',
            	'
            		<div class="modal fade" tabindex="-1" role="dialog" id="selectProduct-{{$id}}">
								  <div class="modal-dialog modal-sm" 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">{{ $name }}</h4>
								      </div>
								      {{ Form::open(["route" => "buy.select", "class" => "form-select-p", "data-p-id" => $id, "data-sku" => $sku]) }}
								      <div class="modal-body">
								      	<div class="row">
													<div class="col-xs-12">
														<div class="form-group">
													    <label for="qty">{{ trans("products.amount") }}</label>
													    <input type="number" min="1" class="form-control" id="qty-{{$id}}" required="required" placeholder="{{ trans("products.amount") }}">
													  </div>
													</div>
								      	</div>
								      	<br />
								       	 <div class="row">
													<div class="col-xs-12">
														<div class="form-group">
											    <label for="qty">{{ trans("products.price_in") }}</label>
											    <input type="number" step="any" class="form-control" id="price-in-{{$id}}" required="required" placeholder="{{ trans("products.price_in") }}" value="{{$price_in}}">
											  </div>
													</div>
								       	 </div>
								      </div>
								      <div class="modal-footer">
								        <button type="button" class="btn btn-default" data-dismiss="modal">{{ trans("dashboard.crud.cancel")}}</button>
								        <button type="submit" class="btn btn-primary" data-product-id="{{$id}}">{{ trans("dashboard.ok") }}</button>
								      </div>
								      {{ Form::close() }}
								    </div>
								  </div>
								</div>
								<button type="button" class="btn btn-success btn-sm" data-toggle="modal" data-target="#selectProduct-{{$id}}">{{ trans("backend_sale.select") }}</button>
      				'
            )
            ->make(true);
	}

	/**
	 * Edit Product
	 * @return [type] [description]
	 */
	public function editProduct()
	{
		$data = Input::all();
		$bproduct = BuyProduct::where('product_id', $data['productId'])
		                      ->where('invoice_id', $data['invoiceId'])->first();
		$bproduct->qty = $data['qty'];
		if ($bproduct->save()) {
			return ['error' => false, 'msg' => trans('messages.success-to-update')];
		}
		return ['error' => true, 'msg' => trans('messages.fail-to-update')];
	}

	/**
	 * Delete Product
	 * @return [type] [description]
	 */
	public function deleteProduct()
	{
		$data = Input::all();
		$bproduct = BuyProduct::where('product_id', $data['productId'])
													->where('invoice_id', $data['invoiceId'])->first();
		$product = Product::find($data['productId']);
		$histories = History::where('product_id', $data['productId'])->get();
		if (count($histories) > 0) {
			$bproduct->delete();
			return ['error' => false, 'msg' => trans('messages.success-to-delete')];
		} else {
			$bproduct->delete();
			$product->delete();
			return ['error' => false, 'msg' => trans('messages.success-to-delete')]; 
		}
		return ['error' => false, 'msg' => trans('messages.fail-to-delete')];
	}

	/**
	 * Select Product
	 * @return [type] [description]
	 */
	public function selectProduct()
	{
		$invoiceId = InvoiceHelper::getInvoiceID();
		$productId = Input::get('productId');
		$product   = Product::find($productId);
		$qty       = Input::get('qty');
		$exitBp = BuyProduct::where('product_id', $productId)
		                    ->where('invoice_id', $invoiceId)->first();
		if ($exitBp) return ['error' => true, 'msg' => trans('backend_sale.product_existing')];
			$buy_product = BuyProduct::create([
											'invoice_id' => $invoiceId,
											'product_id' => $productId,
											'qty'				=> $qty,
											'price'     => Input::get('price'),
											'sku'       => Input::get('sku')
										]);
		if ($buy_product) {
			return ['error' => false, 'msg' => trans('messages.success-to-create')];
		} 
		return ['error' => true, 'msg' => trans('messages.fail-to-create')];
	}

	/**
	 * Load product
	 * @param  [type] $id 
	 * @return [type]     
	 */
	public function loadP($id)
	{
		$products = DB::table('products as p')
									->join('buy_products as bp', 'bp.product_id', '=', 'p.id')
									->select('p.id','p.sku', 'p.name', 'bp.qty', 'bp.price', 'bp.id as bp_id')
									->where('bp.invoice_id', $id)
									->get();
		$output = "";
		if (count($products) > 0) {

				foreach($products as $p) {
					$output .= '
					<li class="clearfix total-buy">
						<div class="amount-text">
							<p>'. $p->name.'  [ '. money($p->price). ' ] <span class="badge">'. $p->qty .'</span></p>
						</div>
						<div class="amount-price tax">'. money($p->qty * $p->price) .'
						</div>
					</li>
					';
				}
		}
		return $output;
	}
}