<?php

class StocksController extends \BaseController {

	/**
	 * Display a listing of the resource.
	 * GET /stocks
	 *
	 * @return Response
	 */
	public function index()
	{
		if(!UserRole::has('list_stock')) return Redirect::route('dashboard');
		$stocks = DB::table('Stocks')
						->leftJoin('Branches', 'Stocks.branch_id', '=', 'Branches.id')
						->select('Stocks.*', 'Branches.name AS branch_name')
						->orderBy('Stocks.id')
						->get();
		return View::make('stocks.index')->with('stocks',$stocks);
	}

	/**
	 * Show the form for creating a new resource.
	 * GET /stocks/create
	 *
	 * @return Response
	 */
	public function create()
	{
		if(!UserRole::has('create_stock')) return Redirect::route('dashboard');
		if(Stock::getNumber() == "one" && count(Stock::all()) >=1 ) return Redirect::route('dashboard');
		if(Branch::getNumber() == "one") {
			$branches = Branch::take(1)->lists('name', 'id');
		} else {
			$branches = Branch::all()->lists('name', 'id');
		}
		return View::make('stocks.create')->with('branches',$branches);
	}

	/**
	 * Store a newly created resource in storage.
	 * POST /stocks
	 *
	 * @return Response
	 */
	public function store()
	{
		$data = Input::all();
		$validator = Validator::make(Input::all(),['name' => 'unique:stocks']);
		if ($validator->fails())
		return Redirect::back()
					->withInput()
          ->withMessage('messages.fail-to-create')
          ->with('messageType', 'danger')
          ->withErrors($validator->messages());
		$stocks = Stock::create($data);
		if($stocks)
			return Redirect::back()
				->withInput()
				->with('message','messages.success-to-create')
				->with('messageType','success');
		else
			return Redirect::back()
				->withInput()
				->with('message','messages.fail-to-create')
				->with('messageType','danger');
	}

	/**
	 * Display the specified resource.
	 * GET /stocks/{id}
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function show($id)
	{
		$stock = Stock::find($id);
		return View::make('stocks.show')->with('stock',$stock);
	}

	public function getStockProducts($id) {
		$outlets = Stock::productsByID($id);
   	 	return Datatables::of($outlets)

   	 				->editColumn('price_in', '{{ money($price_in) }}')
            		->editColumn('created_at', function ($outlet) {
                return $outlet->created_at ? with(new \Carbon\Carbon($outlet->created_at))->format('m/d/Y') : '';
            })
            ->editColumn('created_by','{{ getField("User","id",$user_id,"first_name")}}')
            ->editColumn('action',
            	'
	            	{{link_to_route("outlets.show", Trans("buttons.view"), [$outlet_id], ["class" => "btn btn-xs btn-default"]) }}
      				'
            )
            ->make(true);
	}
	/**
	 * Show the form for editing the specified resource.
	 * GET /stocks/{id}/edit
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id)
	{
		if(!UserRole::has('edit_stock')) return Redirect::route('dashboard');
		$stock = Stock::find($id);
		if(empty($stock)) return Redirect::back();
		$branches = Branch::lists('name','id');
		return View::make('stocks.edit')
			->with('branches',$branches)
			->withStock($stock);
	}

	/**
	 * Update the specified resource in storage.
	 * PUT /stocks/{id}
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update($id)
	{
		$data = Input::all();
		$stock = Stock::find($id);
		$validator = Validator::make(Input::all(),['name' => 'unique:stocks,name,'.$stock->id]);
		if ($validator->fails())
		return Redirect::back()
					->withInput()
          ->withMessage('messages.fail-to-create')
          ->with('messageType', 'danger')
          ->withErrors($validator->messages());

		$stock = $stock->update($data);
		if($stock)
			return Redirect::back()
				->withInput()
				->with('message','messages.success-to-update')
				->with('messageType','success');
		else
			return Redirect::back()
				->withInput()
				->with('message','messages.fail-to-update')
				->with('messageType','danger');
	}

	/**
	 * Remove the specified resource from storage.
	 * DELETE /stocks/{id}
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id)
	{
		$stock = Stock::find($id);
		if(empty($stock)) return Redirect::back()
			->with('message','messages.fail-to-delete')
			->with('messageType','danger');
		if($this->getProductInStock($id) > 0) {
			return Redirect::back()
				->with('message','messages.not_allow_to_delete')
				->with('messageType','warning');
		}
		if($stock->delete()) {
			return Redirect::route('stocks.index')
				->with('message','messages.success-to-delete')
				->with('messageType','success');
		} else {
			return Redirect::back()
				->with('message','messages.fail-to-delete')
				->with('messageType','danger');
		}
	}
	/**
	 * Add Product To Stock
	 */
	public static function addStock()
	{
		$success = false;
		$data = Input::all();
    DB::beginTransaction();
    try {
			$product = Product::find($data['product_id']);
			if($product->amount < $data['amount'] && $product->is_service == false) {
				return Redirect::back()->withInput()->with('message','messages.not_enought_amount')->with('messageType','danger');
			}
			$product_id = $product->id;
			$stock_id		= $data['stock_id'];
			$existed_item = Outlet::where(function($query) use($product_id,$stock_id) {
				$query->where('product_id','=',$product_id)
				->where('stock_id','=',$stock_id);
			})->first();
			if($existed_item) {
				$outlet = Outlet::find($existed_item->id)->update([
					'product_id' 	=> $product->id,
					'amount'			=> $existed_item->amount + $data['amount'],
					'available_amount'			=> $existed_item->available_amount + $data['amount'],
					'user_id'			=> Auth::user()->id,
					'price'				=> $product->price,
					'sku'					=> $product->sku,
					'stock_id'		=> $data['stock_id']
				]);
			}
			else {
				$outlet = Outlet::create([
					'product_id' 	=> $product->id,
					'amount'			=> $data['amount'],
					'available_amount' => $data['amount'],
					'user_id'			=> Auth::user()->id,
					'price'				=> $product->price,
					'sku'					=> $product->sku,
					'stock_id'		=> $data['stock_id']
				]);
			}

			if($outlet) {
				/*
				Deduct From Warehouse
				 */
				$adjustProduct = Product::find($data['product_id']);
				$adjustProduct->amount =	$adjustProduct->amount - $data['amount'];
				$adjustProduct->save();

				/*
				Add to Log Data
				 */
				$history = new History;
				$history->product_id = $product->id;
				$history->amount = $data['amount'];
				$history->operation_type = "in";
				$history->user_id = Auth::user()->id;
				$history->operated_on = "stock";
				$history->stock_id = $data['stock_id'];
				$history->save();
				if($history->id) {
					$success = true;
				}
				else{
					$success = false;
				}

			}
    } catch (\Exception $e) {
    	return dd($e->getMessage());
    }
    if (!$success) {
        DB::rollback();
        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');
    }
	}
	private function getProductInStock($stock_id)
	{
		$product = DB::table('products as p')
									->join('outlets as o', 'o.product_id', '=', 'p.id')
									->join('stocks as s', 'o.stock_id', '=', 's.id')
									->select('o.amount')
									->where('s.id', $stock_id)
									->get();
		if(empty($product)) return 0;
		return count($product);
	}
}
