<?php

class PromotersController extends BaseController {

	protected $rules		 = array(
			'name' => 'required|max:50',
			'code' => 'required|max:50',
	);
	protected $messages	 = array(
			'name.required' => 'Неообходимо ввести название проекта',
			'code.required' => 'Неообходимо ввести код промоутера'
	);

	/**
	 * Constructor
	 */
	public function __construct() {
		// Establish Filters
		$this->beforeFilter('auth');
		$this->beforeFilter('hasRole:' . Role::ROLE_FRANCHISEES);
	}

	/**
	 * Display a listing of the resource.
	 *
	 * @return Response
	 */
	public function index() {
		return View::make('promoters.index')->with('promoters', Promoter::whereUserId(Sentry::getUser()->user_id?Sentry::getUser()->user_id:Sentry::getUser()->id)->orderBy('code', 'ASC')->get());
	}

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

	/**
	 * Store a newly created resource in storage.
	 *
	 * @return Response
	 */
	public function store() {
		$input			 = Input::all();
		$validation	 = Validator::make($input, $this->rules, $this->messages);

		if ($validation->fails()) {
			return Redirect::action('PromotersController@create')
											->withInput()
											->withErrors($validation->errors());
		}
		else {
			$input	 = Input::all();
			$promoter = Promoter::create(array(
									'name'		 => e($input['name']),
									'code'		 => e($input['code']),
									'user_id'	 => Sentry::getUser()->user_id?Sentry::getUser()->user_id:Sentry::getUser()->id
			));
			return Redirect::to('/promoters');
		}
	}

	/**
	 * Show the form for editing the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id) {
		$promoter = Promoter::find($id);
		if ($promoter == null || !is_numeric($id)) {
			return \App::abort(404);
		}

		return View::make('promoters.edit')->with('promoter', $promoter);
	}

	/**
	 * Update the specified resource in storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update($id) {
		$input			 = Input::all();
		$validation	 = Validator::make($input, $this->rules, $this->messages);

		if ($validation->fails()) {
			return Redirect::action('PromotersController@edit', $id)
											->withInput()
											->withErrors($validation->errors());
		}
		else {
			$promoter = Promoter::find($id);
			if ($promoter == null || !is_numeric($id)) {
				return \App::abort(404);
			}

			$promoter->name	 = e($input['name']);
			$promoter->code	 = e($input['code']);
			$promoter->save();
			return Redirect::to('/promoters');
		}
	}

	/**
	 * Remove the specified resource from storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id) {
		$promoter = Promoter::find($id);
		if ($promoter == null || !is_numeric($id)) {
			return \App::abort(404);
		}
		Promoter::destroy($id);
		return Redirect::to('/promoters');
	}

}
