<?php

class UserController extends BaseController {

	public function __construct() {
		//Check CSRF token on POST
		$this->beforeFilter('csrf', array('on' => 'post'));
		$this->beforeFilter('guest', array('only' => array('showRegistration', 'showLogin', 'login')));
		$this->beforeFilter('auth', array('only' => array('index', 'show', 'edit', 'update', 'destroy')));
		$this->beforeFilter('hasRole:' . Role::ROLE_PROJECT_MANAGER, array('only' => array('index', 'destroy')));
	}

	public function index() {
		if (Auth::user()->isSuperuser()) {
			$users = User::withTrashed()
							->orderBy('user_id', 'ASC')
							->orderBy('first_name', 'ASC')
							->orderBy('last_name', 'ASC')
							->get();
		}
		else {
			$users = Auth::user()->getMyUsers();
		}

		return View::make('users.index')->with('users', $users);
	}

	public function show($id) {
		if (Auth::user()->id != $id && !Auth::user()->hasRole(Role::ROLE_PROJECT_MANAGER)) {
			return App::abort(404);
		}

		$user = User::withTrashed()->find($id);

		return View::make('users.show')->with('user', $user);
	}

	public function create() {
		$allRoles		 = Role::orderBy('name', 'ASC')->get();
		$allProjects = Project::orderBy('name', 'ASC')->get();

		return View::make('users.create')->with('allRoles', $allRoles)->with('allProjects', $allProjects);
	}

	public function edit($id) {
		if (Auth::user()->id != $id && !Auth::user()->hasRole(Role::ROLE_PROJECT_MANAGER)) {
			return App::abort(404);
		}

		$user = User::withTrashed()->find($id);

		$currentRoles	 = $user->roles->toArray();
		$userRoles		 = array();
		foreach ($currentRoles as $role) {
			array_push($userRoles, $role['id']);
		}
		$allRoles = Role::orderBy('name', 'ASC')->get();

		$currentProjects = User::find($id)->projects->toArray();
		$userProjects		 = array();
		foreach ($currentProjects as $project) {
			array_push($userProjects, $project['id']);
		}
		$allProjects = Project::orderBy('name', 'ASC')->get();

		return View::make('users.edit')
										->with('user', $user)
										->with('userRoles', $userRoles)
										->with('allRoles', $allRoles)
										->with('userProjects', $userProjects)
										->with('allProjects', $allProjects);
	}

	public function update($id) {
		if (!is_numeric($id)) {
			return App::abort(404);
		}

		if (Auth::user()->id != $id && !Auth::user()->hasRole(Role::ROLE_PROJECT_MANAGER)) {
			return App::abort(404);
		}

		$input = Input::all();

		$validator = Validator::make(
										$input, array(
								'first_name' => 'required',
								'last_name'	 => 'required',
										), array(
								'first_name.required'	 => 'Необходимо указать имя.',
								'last_name.required'	 => 'Необходимо указать фамилию.',
										)
		);

		if ($validator->fails()) {
			return Redirect::action('UserController@edit', array($id))
											->withInput()
											->withErrors($validator->errors());
		}

		$user = User::withTrashed()->find($id);

		$user->first_name	 = e($input['first_name']);
		$user->last_name	 = e($input['last_name']);
		$user->phone			 = e($this->preparePhone($input['phone']));
		$user->save();

		if (Auth::user()->hasRole(Role::ROLE_PROJECT_MANAGER)) {
			$user->update(Input::only(array(
									'sip_login',
									'sip_password',
									'sip_number',
									'pay_salary',
									'pay_salary_day',
									'pay_percent_all',
									'pay_percent_margin',
									'pay_percent_margin_all',
									'work_day_start_at',
									'work_day_start_at_weekend',
									'late_fee'
			)));
			$user->payroll					       = Input::has('payroll') ? 1 : 0;
			//$user->hide_for_salary_project = Input::has('hide_for_salary_project') ? 1 : 0;
			$user->checkcalls				       = Input::has('checkcalls') ? 1 : 0;
			$user->performsusertasks       = Input::has('performsusertasks') ? 1 : 0;
			$user->use_sms_password	       = Input::has('use_sms_password') ? 1 : 0;
			$user->save();

			if (isset($input['roles'])) {
				$user->roles()->sync(array_keys($input['roles']));
			}
			else {
				$user->roles()->detach();
			}

			if (isset($input['projects'])) {
				$user->projects()->sync(array_keys($input['projects']));
			}
			else {
				$user->projects()->detach();
			}
		}

		Session::flash('success', trans('users.success_edit'));

		if (Auth::user()->hasRole(Role::ROLE_PROJECT_MANAGER)) {
			return Redirect::action('UserController@index');
		}

		return Redirect::action('UserController@show', array($id));
	}

	public function showLogin() {
		return View::make('users.login');
	}

	public function login() {
		$input = Input::only('email', 'password', 'noremember');

		$remember = true;
		if (!array_key_exists('noremember', $input)) {
			$remember = false;
		}

		$validator = Validator::make(
										$input, array(
								'email'		 => 'required|email',
								'password' => 'required|min:3'
										), array(
								'email.required'		 => 'Необходимо указать электронную почту',
								'email.email'				 => 'Необходимо указать электронную почту',
								'password.required'	 => 'Необходимо указать пароль',
								'password.min'			 => 'Пароль не должен быть короче 3 символов',
										)
		);

		if ($validator->fails()) {
			$result = array('status' => 'error', 'errorMessages' => $validator->errors());
			return Response::json($result);
		}
		else {
			if (!Auth::attempt(array('email' => $input['email'], 'password' => $input['password']), $remember)) {
				$result = array(
						'status'				 => 'error',
						'errorMessages'	 => array(
								'email'		 => array(''),
								'password' => array(trans('users.login_error'))
						)
				);
				return Response::json($result);
			}
		}

		$intendedUrl = Session::get('url.intended', url('/'));
		Session::forget('url.intended');

		$result = array('status' => 'success', 'url' => $intendedUrl);
		return Response::json($result);
	}

	public function logout() {
		Auth::logout();
		return Redirect::to('/');
	}

	public function showRegistration() {
		if (Input::has('referral_id')) {
			$referral_id = Input::get('referral_id');
			if (is_numeric($referral_id)) {
				Session::put("referral_id", $referral_id);
				$coockie = Cookie::forever('referral_id', $referral_id);
				return Redirect::to('register')->withCookie($coockie);
			}
		}
		if (Input::has('project') && Input::has('type')) {
			$project = Input::get('project');
			$type = Input::get('type');
			
			Session::put("project", $project);
			Session::put("type", $type);
		}

		return View::make('users.registration');
	}

	public function store() {
		$input = Input::all();

		$input['phone']		 = $this->preparePhone($input['phone']);
		$input['user_id']	 = Auth::check() ? Auth::user()->id : DB::raw('NULL');

		$validator = Validator::make(
										$input, array(
								'first_name' => 'required',
								'last_name'	 => 'required',
								'email'			 => 'required|email|unique:users',
								'password'	 => 'required|min:3|confirmed'
										), array(
								'first_name.required'	 => 'Необходимо указать имя',
								'last_name.required'	 => 'Необходимо указать фамилию',
								'email.required'			 => 'Необходимо указать электронную почту',
								'email.email'					 => 'Необходимо указать электронную почту',
								'email.unique'				 => 'Электронная почта уже используется',
								'password.required'		 => 'Необходимо указать пароль',
								'password.min'				 => 'Пароль не должен быть короче 3 символов',
								'password.confirmed'	 => 'Пароль не совпадает с подтверждением',
										)
		);

		if ($validator->fails()) {
			$result = array('status' => 'error', 'errorMessages' => $validator->errors());
			return Response::json($result);
		}
		else {
			$sessionProject = Session::get('project');
			$sessionType    = Session::get('type');
			
			if($sessionProject && $sessionType){
				$user = User::create(
												array(
														'email'			 => e($input['email']),
														'password'	 => e(Hash::make($input['password'])),
														'phone'			 => e($input['phone']),
														'first_name' => e($input['first_name']),
														'last_name'	 => e($input['last_name']),
														'user_id'		 => 2 // id виртуального пользователя для отслеживания самостоятельной регистрации сотрудников в з/п проектах
												)
			  );
				// привязываем проект к пользователю
				$budgetProjects = []; // собираем массив вида "мд5(id)":"id"
				foreach ( Project::whereUsebudget(1)->get() as $project ){
					$budgetProjects[md5($project->id)] = $project->id;
				}
				$projectId = 0;
				if (array_key_exists($sessionProject, $budgetProjects)) {
					$projectId = $budgetProjects[$sessionProject];
					$user->projects()->attach($projectId);
				  $user->salaryProjects()->attach($projectId);
				}
				
				// привязываем роль к пользователю
				$roles = [];
				foreach ( Role::all() as $role ){
					$roles[md5($role->id)] = $role->id;
				}
				if (array_key_exists($sessionType, $roles)) {
					$roleId = $roles[$sessionType];
				  $user->roles()->attach($roleId);
				}
			}else{
				$user = User::create(
												array(
														'email'			 => e($input['email']),
														'password'	 => e(Hash::make($input['password'])),
														'phone'			 => e($input['phone']),
														'first_name' => e($input['first_name']),
														'last_name'	 => e($input['last_name']),
														'user_id'		 => $input['user_id']
												)
			  );
			}

			$user->signUpInit($input['password']);

			if (!Auth::check()) {
				if (!Auth::attempt(array('email' => $input['email'], 'password' => $input['password']))) {
					$result = array(
							'status'				 => 'error',
							'errorMessages'	 => array(
									'email'		 => array(''),
									'password' => array(trans('users.login_error'))
							)
					);
					return Response::json($result);
				}
				$result = array('status' => 'success');
				return Response::json($result);
			}
			else {
				$user->update(Input::only(array(
										'sip_login',
										'sip_password',
										'sip_number',
										'pay_salary',
										'pay_salary_day',
										'pay_percent_all',
										'pay_percent_margin',
										'pay_percent_margin_all',
										'work_day_start_at',
										'work_day_start_at_weekend',
										'late_fee'
				)));
				$user->payroll					       = Input::has('payroll') ? 1 : 0;
				$user->checkcalls				       = Input::has('checkcalls') ? 1 : 0;
				$user->performsusertasks       = Input::has('performsusertasks') ? 1 : 0;
				$user->use_sms_password	       = Input::has('use_sms_password') ? 1 : 0;
				$user->save();

				if (isset($input['roles'])) {
					$user->roles()->sync(array_keys($input['roles']));
				}
				else {
					$user->roles()->detach();
				}

				if (isset($input['projects'])) {
					$user->projects()->sync(array_keys($input['projects']));
				}
				else {
					$user->projects()->detach();
				}
			}
			return Redirect::to('/users');
		}
	}

	public function change($id) {
		if (!is_numeric($id)) {
			return App::abort(404);
		}

		if (Auth::user()->id != $id && !Auth::user()->hasRole(Role::ROLE_PROJECT_MANAGER)) {
			return App::abort(404);
		}

		$user = User::find($id);

		$input = Input::all();

		$validator = Validator::make(
										$input, array(
								'newPassword'							 => 'required|min:3|confirmed',
								'newPassword_confirmation' => 'required'
										), array(
								'newPassword.required'							 => 'Необходимо ввести новый пароль.',
								'newPassword.min'										 => 'Пароль должен быть не короче 3 символов.',
								'newPassword.confirmed'							 => 'Пароль не совпадает с подтверждением.',
								'newPassword_confirmation.required'	 => 'Необходимо подтвердить пароль.'
										)
		);

		if ($validator->fails()) {
			return Redirect::action('UserController@edit', array($id))
											->withInput()
											->withErrors($validator->errors());
		}
		else {
			$result = $user->changePassword($input);

			if ($result['success']) {
				Session::flash('success', $result['message']);
				return Redirect::to('users');
			}
			else {
				Session::flash('error', $result['message']);
				return Redirect::action('UserController@edit', array($id))
												->withInput();
			}
		}
	}

	public function destroy($id) {
		if (!is_numeric($id) || !Auth::user()->isAdmin()) {
			return App::abort(404);
		}

		$user = User::withTrashed()->find($id);

		if ($user->deleted_at) {
			$user->restore();
			return Response::json(array('status' => 'restored'));
		}
		else {
			$user->delete();
			return Response::json(array('status' => 'deleted'));
		}
	}

}
