<?php

class QuotationController extends \BaseController {

	/**
	 * Display a listing of the resource.
	 * GET /quotation
	 *
	 * @return Response
	 */
	public function index()
	{
		$customers = Customer::select(['id', DB::raw('CONCAT(first_name, " ", last_name) AS full_name')])->lists('full_name', 'id');
		$customers['none'] = trans("customers.general");
		return View::make('quotations.index', ['customers' => $customers]);
	}

	/**
	 * Show the form for creating a new resource.
	 * GET /quotation/create
	 *
	 * @return Response
	 */
	public function create()
	{
		return View::make('quotations.create');
	}

	/**
	 * Store a newly created resource in storage.
	 * POST /quotation
	 *
	 * @return Response
	 */
	public function store()
	{
		//
	}

	/**
	 * Display the specified resource.
	 * GET /quotation/{id}
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function show($id)
	{
		$quotation = Quotation::getQuotation($id);
		if (empty($quotation)) return Redirect::back();
		$preOrders = Quotation::getPreOrders($id);
		return View::make('quotations.show', ['quotation' => $quotation, 'preOrders' => $preOrders]);
	}

	/**
	 * Show the form for editing the specified resource.
	 * GET /quotation/{id}/edit
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id)
	{
		//
	}

	/**
	 * Update the specified resource in storage.
	 * PUT /quotation/{id}
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update($id)
	{
		//
	}

	/**
	 * Remove the specified resource from storage.
	 * DELETE /quotation/{id}
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id)
	{
		$preOrders = PreOrder::where('quotation_id', $id)->get();
		DB::beginTransaction();
		try {
			if (count($preOrders) > 0) {
				foreach ($preOrders as $order) {
					$preOrder = PreOrder::find($order->id);
					$preOrder->delete();
				}
			}
			$quotation = Quotation::find($id);
			$quotation->delete();
			DB::commit();
			return Redirect::back()->withMessage('messages.success-to-delete')
										 ->with('messageType', 'success');
		} catch (Exception $e) {
			DB::rollBack();
			return Redirect::back()->withMessage('messages.fail-to-delete')
										 ->with('messageType', 'danger');
		}
	}

	/**
	 * Get products in stock for create quotation
	 * @return ajax datatable
	 */
	public function getProductsInstock()
	{
		$products = Product::join('outlets', 'outlets.product_id', '=', 'products.id')
											 ->select(
											 				'products.id',
											 				'products.sku',
											 				'products.name', 
											 				'products.price',
											 				'outlets.available_amount'
											 	)->where('status', 'active');
   	 return Datatables::of($products)
   	 				->editColumn('name', '{{ str_limit($name,30,"...") }}')
   	 				->editColumn('available_amount', '{{$available_amount}}')
   	 				->editColumn('price', '{{ money($price) }}')
            ->editColumn('action',
            		'
            		<button class="btn btn-success btn-sm btn-add-cart" data-product-id="{{$id}}" data-sku="{{ $sku }}" data-price="{{ $price }}"><i class="fa fa-plus"></i> {{ trans("backend_sale.select") }}</button>
      				')->make(true);
	}

	/**
	 * View for load products and create quotation
	 * @param  int $id
	 * @return view 
	 */
	public function newQuotation($id = null)
	{
		$cusotomerId = $id > 0 ? $id : null;
		$invoiceId   = getQuotId($id);
		return View::make('quotations.create', ['invoiceId' => $invoiceId]);
	}

	/**
	 * Redirect when user select customer
	 * @return response
	 */
	public function postNewQuotaion()
	{
		$cId = Input::get('customer_id') != "none" ? Input::get('customer_id') : 0;
		if ($cId > 0) return Redirect::route('quotations.new', $cId);
		return Redirect::route('quotations.new');
	}

	public function addPreOrder()
	{
		// Assign Value to variables
		$invoiceId = Input::get('invoice_id');
		$productId = Input::get('product_id');
		$existOrder = PreOrder::where('quotation_id', $invoiceId)
													->where('product_id', $productId)->first();

		if ($existOrder) {
			$existOrder->amount += 1;
			$existOrder->save();
			return ['error' => false, 'msg' => trans('messages.success-to-update')];
		} else {
			$preOrder = new PreOrder;
			$preOrder->product_id = $productId;
			$preOrder->quotation_id = $invoiceId;
			$preOrder->price = Input::get('price');
			$preOrder->user_id = Auth::user()->id;
			$preOrder->stock_id = Auth::user()->stock_id;
			$preOrder->amount = 1;
			if ($preOrder->save()) return ['error' => false, 'msg' => trans('messages.success-to-create')];
			return ['error' => true, 'msg' => trans('messages.fail-to-create')];
		}
	}

	/**
	 * Load table preorder via ajax
	 * @return [type] [description]
	 */
	public function getPreOrderTable($id)
	{
		$products = Product::join('pre_orders', 'pre_orders.product_id', '=', 'products.id')
										   ->select(
										   			'products.id',
										   			'products.sku',
										   			'products.name',
										   			'pre_orders.price',
										   			'pre_orders.amount'
										   		)
											 ->where('quotation_id', $id)->get();
		$quotation = Quotation::find($id);
		return View::make('quotations.table_preorder', ['products' => $products, 'quotation' => $quotation]);
	}

	/**
	 * Update PreOrder
	 * @return [type] [description]
	 */
	public function updatePreOrder()
	{
		$productId =  Input::get('product_id');
		$invoiceId = Input::get('invoice_id');
		$qty       = Input::get('qty');
		$price     = Input::get('price');
		if ($qty <= 0) return ['error' => true, "msg" => "Amount must equal 1 or more than one"];
		$preOrder = PreOrder::where('product_id', $productId)->where('quotation_id', $invoiceId)->first();
		if (empty($preOrder)) return ['error' => true, 'msg' => trans('messages.fail-to-update')];
		$preOrder->amount = $qty;
		$preOrder->price  = $price;
		$product = Product::where('status', "draft")->where('id', $productId)->first();
		if ($product) {
			$product->price = $price;
			$product->save();
			$history = History::where('product_id', $productId)->first();
			$history->amount = $qty;
			$history->save();
		}
		if ($preOrder->save()) return ['error' => false, 'msg' => trans('messages.success-to-update')];
		return ['error' => true, 'msg' => trans('messages.fail-to-update')];
	}

	public function deletePreOrder()
	{
		$invoiceId = Input::get("invoice_id");
		$productId = Input::get("product_id");
		$preOrder  = PreOrder::where('product_id', $productId)
												->where('quotation_id', $invoiceId)->first();
		if (empty($preOrder)) return ['error' => true, 'msg' => trans('messages.fail-to-delete')];
		$product = Product::where('status', "draft")->where('id', $productId)->first();
		if ($product) {
			$history = History::where('product_id', $productId)->first();
			if ($history) $history->delete();
			$product->delete();
		}
		if ($preOrder->delete()) return ['error' => false, 'msg' => trans('messages.success-to-delete')];
		return ['error' => true, 'msg' => trans('messages.fail-to-delete')];
	}

	public function confirmPreOrder()
	{
		$invoiceId = Input::get('invoice_id');
		Session::put('printQuotation', $invoiceId);
		$quotation = Quotation::find($invoiceId);
		$invoiceUrl = route('printQuotation');
		$index = route('listQuotation');
		if (empty($quotation)) return Redirect::back();
		$quotation->status = "closed";
		$quotation->save();
    return '
      <script type="text/javascript">
        window.open("'.$invoiceUrl.'", "_blank");
        window.location = "'.$index.'";
      </script>
      ';
	}

	public function printQuotation($id = null)
	{
		$invoiceId = !empty(Session::get('printQuotation')) ? Session::get('printQuotation') : $id;
		$quotation = Quotation::getQuotation($invoiceId);
		if (empty($quotation)) return Redirect::back();
		$preOrders = Quotation::getPreOrders($invoiceId);
		//return ['data' => $quotation, 'data-1' => $preOrders];
		return View::make('invoices.invoice.qtest', ['quotation' => $quotation, 'preOrders' => $preOrders]);
	}

	/**
	 * List All Quotation
	 * @return mix
	 */
	public function listQuotation()
	{
		$quotations = Quotation::whereIn('status', ['closed', 'approved', 'cancel'])->orderBy('id', 'desc');
		if (!empty(Input::get('invoice_id'))) {
			$quotations->where('id', Input::get('invoice_id'));
		}
		if (!empty(Input::get('start_date')) && !empty(Input::get('end_date'))) {
			$quotations->whereBettween('created_at', [Input::get('start_date'), Input::get('end_date')]);
		}
		if (!empty(Input::get('type')) && Input::get('type') != "all") {
 			$quotations->where('status', Input::get('type'));
		}
		return View::make('quotations.list', ['quotations' => $quotations->paginate(5)]);
	}

	/**
	 * Convert Quotation to Invoice
	 * @return mix
	 */
	public function toInvoice()
	{
		/**
		 * Get Invoice ID and Quotation ID
		 * @var int
		 */
		$invoiceId = InvoiceHelper::getInvoiceID();
		$quotationId = (int) Input::get('quotation_id');
		$quotation = Quotation::find($quotationId);
		if (Input::get('btn-cancel')) {
			$quotation->status = "cancel";
			$quotation->save();
			return Redirect::back();
		} 
		$success = false;
		DB::beginTransaction();
		try {
			// Find product status draft
			// Add product to stock 
			// create new histories
			// Create order form product instock
			// Cancel Product
			// Get PreOders
			$preOrders = PreOrder::getOrders($quotationId);
			$invoice   = Invoice::find($invoiceId);
			// Create new Order with current invoice ID
			foreach ($preOrders as $order) {
				$product = Product::where('status', 'draft')->where('id', $order->product_id)->first();
				if ($product) {
				  $product->status = "active";
				  $product->save();
				}
				$outlet = Outlet::where('product_id', $order->product_id)->first();
				$newOrder = new Order;
				$newOrder->invoice_id = $invoiceId;
				$newOrder->product_id = $order->product_id;
				if ($order->amount > $outlet->available_amount) {
						if ($outlet->available_amount == 0) {
							$newOrder->amount = 0;
						} else {
							$amount = ($order->amount - $outlet->available_amount);
					 		$newOrder->amount = ($order->amount - $amount);
						}						
				} else {
						$newOrder->amount = $order->amount;
				}			
				$newOrder->sku = $order->sku;
				$newOrder->stock_id = Auth::user()->stock_id;
				$newOrder->price = $order->price;
				$newOrder->note  = "Create new order from quotation";
				$newOrder->user_id = Auth::user()->id;
				if ($newOrder->save()) {
					$outlet->on_hold += $order->amount;
					$outlet->available_amount -= $order->amount;
					$outlet->save();
					$success = true;
				}
			}
			if ($success) {
					$quotation->status = "approved";
					$invoice->customer_id = $quotation->customer_id;
					$quotation->save();
					$invoice->save();
					InvoiceHelper::updateTotal();
					DB::commit();
					return Redirect::route('sale');
			} else {
				DB::rollBack();
				return Redirect::back()->withMessage('quotations.msg_fail_to_convert')
										 ->with('messageType', 'danger');
			}
		
		} catch (Exception $e) {
			DB::rollBack();
			return dd($e->getMessage());
			return Redirect::back()->withMessage('quotations.msg_fail_to_convert')
										 ->with('messageType', 'danger');
		}
		// Check amount in stock stock of product if aviable create
		// update status quotation to approved
		// redirect to sale after success convert to invoice
		return ['ids' => [$invoiceId, $quotationId]];
	}

	public function newProduct()
	{
		$data = Input::except('_token');
		$productName = $data['product_name'];
		$sku = trim($data['sku']);
		$existBarcode = Product::where('sku', $sku)->first();
		if ($existBarcode) return ['error' => true, 'msg' => trans('quotations.existing_barcode')];
		DB::beginTransaction();
		try {
			$newProduct = new Product;
			$newProduct->sku = $data['sku'];
			$newProduct->amount = $data['amount'];
			$newProduct->thumbnail = \Config::get('app.ip').'uploads/none.jpg';
			$newProduct->name = $productName;
			$newProduct->name_kh = $productName;
			$newProduct->price   = $data['price'];
			$newProduct->status  = 'draft';
			$newProduct->is_service = 0;
			$newProduct->user_id    = Auth::user()->id;
			if ($newProduct->save()) {
				// Create New History 
				$history = new History;
				$history->product_id = $newProduct->id;
				$history->amount = $newProduct->amount;
				$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' 	=> $newProduct->id,
					'amount'			=> $newProduct->amount,
					'available_amount' => $newProduct->amount,
					'user_id'			=> Auth::user()->id,
					'price'				=> $newProduct->price,
					'sku'					=> $newProduct->sku,
					'stock_id'		=> Auth::user()->stock_id
			  ]);				
				// Create Outlet for draft
				$preOrder = new PreOrder;
				$preOrder->product_id = $newProduct->id;
				$preOrder->quotation_id = $data['quotation_id'];
				$preOrder->price = $newProduct->price;
				$preOrder->user_id = Auth::user()->id;
				$preOrder->stock_id = Auth::user()->stock_id;
				$preOrder->amount = $newProduct->amount;
				if ($preOrder->save() && $outlet->id && $history->id) {
					DB::commit();
					return ['error' => 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 ['error' => true, 'msg' => trans('messages.fail-to-create')];
		}
		
	}
}