<?php

class UnitsController extends \BaseController {

	/**
	 * Display a listing of the resource.
	 * GET /units
	 *
	 * @return Response
	 */
	public function index()
	{
		if(!UserRole::has('add_unit')) return Redirect::route('dashboard');
		$units = Unit::all();
		return View::make('Units.create')->withUnits($units);
	}
	/**
	 * Store a newly created resource in storage.
	 * POST /units
	 *
	 * @return Response
	 */
	public function store()
	{
		$validator = Validator::make(Input::all(), Unit::$rules);
		if ($validator->fails()) return Redirect::back()
														 	->withInput()
															->withMessage("messages.duplicated_name")
															->with('messageType', 'danger');

		$unit = Unit::create(['name' => Input::get('name')]);
		if ($unit) return Redirect::back()
														 	->withInput()
															->withMessage("messages.success-to-create")
															->with('messageType', 'success');
		// Fail to create unit
		return Redirect::back()->withInput()
											     ->withMessage("messages.fail-to-create")
													 ->with('messageType', 'danger');

	}

	/**
	 * Show the form for editing the specified resource.
	 * GET /units/{id}/edit
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id)
	{
		if(!UserRole::has('edit_unit')) return Redirect::route('dashboard');
		$units = Unit::all();
		$unit = Unit::find($id);
		if (empty($unit)) return Redirect::route("units.index");
		return View::make('Units.edit')->withUnit($unit)->withUnits($units);
	}

	/**
	 * Update the specified resource in storage.
	 * PUT /units/{id}
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update($id)
	{
		$unit = Unit::find($id);
		$validator = Validator::make(Input::all(), Unit::$rules);
		if ($unit->name == Input::get('name')) {
			$unit->name = Input::get('name');
		} else {
			if ($validator->fails()) return Redirect::back()
																->withInput()
																->withMessage("messages.duplicated_name")
																->with('messageType', 'danger');
		}

		$unit->name = Input::get('name');
		$result = $unit->save();
		if ($result) return Redirect::route('units.index')
																->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 /units/{id}
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id)
	{
		$unit = Unit::find($id);
		$result = $unit->delete();
		if ($result) return Redirect::route('units.index')
																->with('message','messages.success-to-delete')
																->with('messageType','success');
		return Redirect::back()->withInput()
										->with('message','messages.fail-to-delete')
										->with('messageType','danger');
	}

}
