<?php

class ProjectsController extends BaseController {

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

	/**
	 * Constructor
	 */
	public function __construct() {
		parent::__construct();
		// Establish Filters
		$this->beforeFilter('auth');
		parent::__construct();
		if ($this->user && !$this->user->isAdmin()) {
			if (!$this->user->hasAnyRole(array(Role::ROLE_PROJECTS_EDITOR, Role::ROLE_PRODUCTS_EDITOR))) {
				$this->beforeFilter('hasRole:' . Role::ROLE_PROJECTS_EDITOR);
				$this->beforeFilter('hasRole:' . Role::ROLE_PRODUCTS_EDITOR);
			}
		}
	}

	/**
	 * Display a listing of the resource.
	 *
	 * @return Response
	 */
	public function index() {
		$projects = null;
		if (Auth::user()->isSuperuser()) {
			$projects = Project::orderBy('name', 'ASC')->get();
		}
		elseif (Auth::user()->isAdmin() || Auth::user()->hasAnyRole(array(Role::ROLE_PROJECTS_EDITOR, Role::ROLE_PRODUCTS_EDITOR))) {
			$projects = Project::whereRaw('id IN (SELECT project_id FROM users_projects WHERE user_id=' . Auth::user()->id . ')')->orderBy('name', 'ASC')->get();
		}
		else {
			$projects = Project::where('user_id', Auth::user()->id)->orderBy('name', 'ASC')->get();
		}
		return View::make('projects.index')
										->with('user', $this->user)
										->with('pageProjects', $this->projects)
										->with('workProject', $this->workProject)
										->with('projects', $projects);
	}

	/**
	 * Show the form for creating a new resource.
	 *
	 * @return Response
	 */
	public function create() {
		return View::make('projects.create')
						->with('users', User::myUsers())
						->with('fines', Fine::all());
	}

	/**
	 * 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('ProjectsController@create')
											->withInput()
											->withErrors($validation->errors());
		}
		else {
			$input	 = Input::all();
			$project = Project::create(array(
									'name'							 => e($input['name']),
									'cache_on_delivery'	 => e($input['cache_on_delivery']),
									'cost_post_delivery' => e($input['cost_post_delivery']),
									'type'							 => e($input['type']),
									'usecrm'						 => e((isset($input['usecrm']) ? 1 : 0)),
									'usebudget'					 => e((isset($input['usebudget']) ? 1 : 0)),
									'usecheckcalls'			 => e((isset($input['usecheckcalls']) ? 1 : 0)),
									'usepayroll'				 => e((isset($input['usepayroll']) ? 1 : 0)),
									'user_id'						 => Auth::user()->id,
									'budget_close_day'	 => e((isset($input['budget_close_day']) ? $input['budget_close_day'] : 1))
			));

			if (isset($input['projectUsers'])) {
				$project->users()->attach(array_keys($input['projectUsers']));
			}

			if (isset($input['projectFines']) && count($input['projectFines'])) {
				$projectFines = array();
				foreach ($input['projectFines'] as $key => $value) {
					$projectFines[$key] = array('value' => $value);
				}
				$project->fines()->sync($projectFines);
			}

			return Redirect::to('/projects');
		}
	}

	/**
	 * Show the form for editing the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id) {
		$project = Project::find($id);
		if ($project == null || !is_numeric($id) || !$project->isMy() || !Auth::user()->isAdmin() && !Auth::user()->hasRole(Role::ROLE_PROJECTS_EDITOR)) {
			return \App::abort(404);
		}

		$currentUsers	 = $project->users->toArray();
		$projectUsers	 = array();
		foreach ($currentUsers as $user) {
			array_push($projectUsers, $user['id']);
		}

		$currentFines	 = $project->fines->toArray();
		$projectFines	 = array();
		foreach ($currentFines as $fine) {
			$projectFines[$fine['id']] = array('id' => $fine['id'], 'value' => $fine['value']);
		}

		return View::make('projects.edit')
										->with('users', User::myUsers())
										->with('fines', Fine::all())
										->with('projectFines', $projectFines)
										->with('project', $project)
										->with('projectUsers', $projectUsers);
	}

	/**
	 * 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('ProjectsController@edit', $id)
											->withInput()
											->withErrors($validation->errors());
		}
		else {
			$project = Project::find($id);
			if ($project == null || !is_numeric($id) || !$project->isMy() || !Auth::user()->isAdmin() && !Auth::user()->hasRole(Role::ROLE_PROJECTS_EDITOR)) {
				return \App::abort(404);
			}

			$project->name							 = e($input['name']);
			$project->cache_on_delivery	 = e($input['cache_on_delivery']);
			$project->cost_post_delivery = e($input['cost_post_delivery']);
			$project->type							 = e($input['type']);
			$project->usecrm						 = (isset($input['usecrm']) ? 1 : 0);
			$project->usebudget					 = (isset($input['usebudget']) ? 1 : 0);
			$project->usecheckcalls			 = (isset($input['usecheckcalls']) ? 1 : 0);
			$project->usepayroll				 = (isset($input['usepayroll']) ? 1 : 0);
			$project->budget_close_day	 = e((isset($input['budget_close_day']) ? $input['budget_close_day'] : 1));
			$project->save();

			if (isset($input['projectUsers'])) {
				$project->users()->sync(array_keys($input['projectUsers']));
			}
			else {
				$project->users()->detach();
			}

			if (isset($input['projectFines']) && count($input['projectFines'])) {
				$projectFines = array();
				foreach ($input['projectFines'] as $key => $value) {
					$projectFines[$key] = array('value' => $value);
				}
				$project->fines()->sync($projectFines);
			}
			else {
				$project->fines()->detach();
			}

			return Redirect::to('/projects');
		}
	}

	/**
	 * Remove the specified resource from storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id) {
		$project = Project::find($id);
		if ($project == null || !is_numeric($id) || !$project->isMy() || !Auth::user()->isAdmin() && !Auth::user()->hasRole(Role::ROLE_PROJECTS_EDITOR)) {
			return \App::abort(404);
		}
		Project::destroy($id);
		return Redirect::to('/projects');
	}

}
