<?php

class ProjectNewsController extends BaseController {

	protected $rules = array(
			'type'       => 'required',			
			'name'       => 'required',
			'content'    => 'required',
	);
	protected $messages	  = array(
			'type.required'   => 'Неообходимо выбрать категорию новости',
			'name.required'   => 'Неообходимо ввести название новости',
			'content.required'=> 'Неообходимо ввести текст новости'
	);
	private $project		 = null;

	/**
	 * Constructor
	 */
	public function __construct() {
		$id			 = Request::segment(2);
		$project = Project::find($id);
		if ($project == null || !is_numeric($id)) {
			return \App::abort(404);
		}
		else {
			$this->project = $project;
		}
		// Establish Filters
		if (Sentry::check()) {
			$user = User::find(Sentry::getUser()->id);
			if (!$user->hasAccess('admin') && !$user->hasAnyRole(array(Role::ROLE_PROJECTS_EDITOR, Role::ROLE_FRANCHISEES))) {
				$this->beforeFilter('hasRole:' . Role::ROLE_PROJECTS_EDITOR);
				$this->beforeFilter('hasRole:' . Role::ROLE_FRANCHISEES);
			}
		}
		else {
			$this->beforeFilter('auth');
		}
	}

	/**
	 * Display a listing of the resource.
	 *
	 * @return Response
	 */
	public function index() {
		if (Sentry::check()) {
			$user = User::find(Sentry::getUser()->id);
			if (!$user->hasAccess('admin') && !$user->hasRole(Role::ROLE_PROJECTS_EDITOR)) {
				return View::make('project_news.franchisees.index')->with('project', $this->project);
			}
		}
		return View::make('project_news.index')->with('project', $this->project);
	}

	//Меню маркетинга
	public function getMenuMarketing() {
		if (Sentry::check()) {
		  return View::make('project_news.marketing.menu')->with('project', $this->project);
		}
	}
	
	//Разделы маркетинга
  public function getPartMarketing($id) {
		if (is_numeric($id)) {
			$type = ProjectNewsTypes::where('id', '=', $id)->first();
			  if ($type != null) {
					return View::make('project_news.marketing.part')->with('id', $id)->with('project', $this->project);	
			  }
		}
	return \App::abort(404);
	}
	
	//Меню обучения
	public function getMenuTraining() {
		if (Sentry::check()) {
		  return View::make('project_news.training.menu')->with('project', $this->project);
		}
	}
	
	//Разделы обучения
	public function getPartTraining($id) {
		if (is_numeric($id)) {
			$type = ProjectNewsTypes::where('id', '=', $id)->first();
			  if ($type != null) {
					return View::make('project_news.training.part')->with('id', $id)->with('project', $this->project);
			  }
		}
	return \App::abort(404);
	}
	
	// Просмотр новости и запись в БД о просмотре
  public function show($projectId, $projectNewsId) {
		$projectNews = ProjectNews::find($projectNewsId);
		if ($projectNews == null || !is_numeric($projectNewsId) || $projectNews->project_id != $projectId) {
			return \App::abort(404);
		}
		$user = User::find(Sentry::getUser()->id);
		if ($user == null) {
			return \App::abort(404);
		}
		if (!$user->projectNews()->where('project_news_id', $projectNews->id)->where('user_id', $user->id)->first() ) {
			$user->projectNews()->attach($projectNews->id, array('user_id' => $user->id));
		}
		return View::make('project_news.show')
										->with('projectNews', $projectNews)
										->with('project', $this->project);
	}

	//Отметить все новости раздела как прочитанные
	public function setViewedAll($projectNewsType) { 
		$newsType = ProjectNewsTypes::find($projectNewsType);
		if ($newsType == null) {
			  return \App::abort(404);
		  }
		$user = User::find(Sentry::getUser()->id);
      if ($user == null) {
			  return \App::abort(404);
		 }
		$notViewedNews = ProjectNews::whereRaw("project_id = 9 AND type_id =".$newsType->id." AND project_news.access_user_id IN ('0', ".$user->id.') AND project_news.id NOT IN (SELECT project_news_viewed.project_news_id FROM  project_news_viewed WHERE user_id = '.$user->id.' )')->get();
		
		foreach ($notViewedNews as $news) {
		  if (!$user->projectNews()->where('project_news_id', $news->id)->where('user_id', $user->id)->first() ) {
			  $user->projectNews()->attach($news->id);
		  }
		}
		return Redirect::to(Session::get('urlBack'));
	}
	
	/**
	 * Show the form for creating a new resource.
	 *
	 * @return Response
	 */
	public function create() {
		return View::make('project_news.create')->with('project', $this->project);
	}

	/**
	 * 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('ProjectNewsController@create', array($this->project->id))
											->withInput()
											->withErrors($validation->errors());
		}
		else {
			$input				 = Input::all();
			$projectNews	 = new ProjectNews(array(
					'type_id'  => e($input['type']),
					'name'     => e($input['name']),
					'content'  => e($input['content'])
			));
			$projectNews	 = $this->project->projectNews()->save($projectNews);
			
      // отправка новостей на почту франчайзи
			$accessUserId = $projectNews->access_user_id;
			if ($accessUserId == 0) { // всем
			$usersForNewsSend = User::join('users_roles', function($join) {
							$join->on('users_roles.user_id', '=', 'users.id');
						})
						->where('users_roles.role_id', '=', Role::ROLE_FRANCHISEES)
						->select('users.*')
						->get();
			
			  foreach($usersForNewsSend as $userForNews){
			    $projectNews->sendNews($userForNews);
			  }
			}elseif ($accessUserId > 0){ // одному ( например о готовности заказа )
				$userForNews = User::find($accessUserId);
				$projectNews->sendNews($userForNews);
			}
			return Redirect::action('ProjectNewsController@index', array($this->project->id));
		}
	}

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

		return View::make('project_news.edit')
										->with('projectNews', $projectNews)
										->with('project', $this->project);
	}

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

		if ($validation->fails()) {
			return Redirect::action('ProjectNewsController@edit', array($projectId, $id))
											->withInput()
											->withErrors($validation->errors());
		}
		else {
			$projectNews = ProjectNews::find($id);
			if ($projectNews == null || !is_numeric($id) || $projectNews->project_id != $projectId) {
				return \App::abort(404);
			}

			$input		 = Input::all();
			$projectNews->type_id = e($input['type']);
			$projectNews->name = e($input['name']);
			$projectNews->content = e($input['content']);
			$projectNews->save();
			return Redirect::action('ProjectNewsController@index', array($projectId));
		}
	}

	/**
	 * Remove the specified resource from storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($projectId, $id) {
		$projectNews = ProjectNews::find($id);
		if ($projectNews == null || !is_numeric($id) || $projectNews->project_id != $projectId) {
			return \App::abort(404);
		}
		ProjectNews::destroy($id);
		return Redirect::action('ProjectNewsController@index', array($projectId));
	}

}
