<?php

use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;

class User extends \Cartalyst\Sentry\Users\Eloquent\User implements UserInterface, RemindableInterface {

	protected $softDelete	 = true;

	/**
	 * The database table used by the model.
	 *
	 * @var string
	 */
	protected $table = 'users';

	/**
	 * The attributes excluded from the model's JSON form.
	 *
	 * @var array
	 */
	protected $hidden = array('password');

	/**
	 * Get the unique identifier for the user.
	 *
	 * @return mixed
	 */
	public function getAuthIdentifier() {
		return $this->getKey();
	}

	/**
	 * Get the password for the user.
	 *
	 * @return string
	 */
	public function getAuthPassword() {
		return $this->password;
	}

	/**
	 * Get the e-mail address where password reminders are sent.
	 *
	 * @return string
	 */
	public function getReminderEmail() {
		return $this->email;
	}

	public function getRememberToken() {
		return $this->remember_token;
	}

	public function setRememberToken($value) {
		$this->remember_token = $value;
	}

	public function getRememberTokenName() {
		return 'remember_token';
	}

	public function payments() {
		return $this->hasMany('Payment')->orderBy('created_at', 'DESC')->take(15);
	}
	
	public function projects() {
		return $this->belongsToMany('Project', 'users_projects')->orderBy('name', 'ASC');
	}

	public function roles() {
		return $this->belongsToMany('Role', 'users_roles')->orderBy('name', 'ASC');
	}
	public function projectNews() {
		return $this->belongsToMany('ProjectNews', 'project_news_viewed');
	}

	public function hasRole($roleId) {
		if (is_numeric($roleId)) {
			if ($this->hasAccess('admin')) {
				return true;
			}
			$userRoles = $this->roles->toArray();
			foreach ($userRoles as $role) {
				if ($role['id'] == $roleId) {
					return true;
				}
			}
		}
		return false;
	}

	public function hasAnyRole($roles) {
		if (is_array($roles)) {
			foreach ($roles as $roleId) {
				if (is_numeric($roleId)) {
					if ($this->hasAccess('admin')) {
						return true;
					}
					$userRoles = $this->roles->toArray();
					foreach ($userRoles as $role) {
						if ($role['id'] == $roleId) {
							return true;
						}
					}
				}
			}
		}
		return false;
	}

	public function scopeMyUsers() {
		if (Sentry::getUser()->hasAccess('admin')) {
			$users = User::orderBy('user_id', 'ASC')
							->orderBy('first_name', 'ASC')
							->orderBy('last_name', 'ASC')
							->paginate(100);
		}
		else {
			$users = User::where(function ($query) {
								$query->where('id', Sentry::getUser()->id)
								->orWhere('user_id', Sentry::getUser()->id);
							})
							->orderBy('user_id', 'ASC')
							->orderBy('first_name', 'ASC')
							->orderBy('last_name', 'ASC')
							->paginate(100);
		}
		$users->each(function ($user) {
			if ($user->id == 1) {
				$user->status = 'Суперадминистратор';
			}
			elseif (!$user->user_id) {
				$user->status = 'Администратор';
			}
			else {
				$user->status = 'Пользователь';
			}
		});
		return $users;
	}

	public function scopeAllUsers() {
		$users = User::withTrashed()
						->orderBy('id', 'ASC')
						->paginate(100);

		$users->each(function ($user) {
			if ($user->id == 1) {
				$user->status = 'Суперадминистратор';
			}
			elseif (!$user->user_id) {
				$user->status = 'Администратор';
			}
			else {
				$user->status = 'Пользователь';
			}
		});

		return $users;
	}

	public function changeMoney($amount, $comment) {
		if ($this->hasRole(Role::ROLE_FRANCHISEES)) {
			$payment = new Payment(array('amount' => $amount, 'comment' => $comment));
			$payment = $this->payments()->save($payment);

			$this->money += $amount;
			$this->save();
		}
	}

	public function getFrozenMoney() {
		$result = Partner::whereUserId($this->id)->whereIn('status', array(Partner::STATUS_PRODUCTION_WAIT, Partner::STATUS_PRODUCTION_PROCESS, Partner::STATUS_PRODUCTION_SUCCESS))->get(array(DB::raw('COALESCE(SUM(franchisees_cost), 0) as money ')))->first()->toArray();
		return $result['money'];
	}

		public function createNews($name, $content) {
	    $news = ProjectNews::create(array('type_id'=>1, 'name'=>$name, 'content'=> $content, 'access_user_id'=>$this->id));
		  $project = Project::find(9);
		  $news->project()->associate($project);
      $news->save();
	}
}
