<?php

class BudgetCostsRequestsController extends BaseController {

	/**
	 * Constructor
	 */
	public function __construct() {
		// Establish Filters
		$this->beforeFilter('auth');

		if (Auth::check()) {
			$this->user	 = Auth::user();
			$this->projects = $this->user->budgetProjects;
		}
		$this->projectPrefix = 'budget';
		parent::__construct();

		$this->beforeFilter('csrf', array('only' => array('createOperation')));

		if ($this->user && Auth::user()->hasRole(Role::ROLE_BUDGET_OUTCOMING_REQUEST)) {
			$this->beforeFilter('hasRole:' . Role::ROLE_BUDGET_OUTCOMING_REQUEST);
		}
		else if ($this->user && Auth::user()->hasRole(Role::ROLE_BUDGET_CFO)) {
			$this->beforeFilter('hasRole:' . Role::ROLE_BUDGET_CFO);
		}
		else if ($this->user && Auth::user()->hasRole(Role::ROLE_BUDGET_ACCOUNTANT)) {
			$this->beforeFilter('hasRole:' . Role::ROLE_BUDGET_ACCOUNTANT);
		}
		else if ($this->user && Auth::user()->hasRole(Role::ROLE_BUDGET_ACC_SECRETARY)) {
			$this->beforeFilter('hasRole:' . Role::ROLE_BUDGET_ACC_SECRETARY);
		}
		if ($this->user && Auth::user()->hasRole(Role::ROLE_BUDGET_SIGN_COST_REQUEST) && !Auth::user()->isAdmin()) {
			$this->beforeFilter('hasRole:' . Role::ROLE_BUDGET_SIGN_COST_REQUEST);
		}
	}

	public function costsRequests() {
		$input = Input::all();
		
		if (!$this->user->budgetProjects->count()) {
			return Redirect::to('/');
		}
		if (!Auth::user()->hasAnyRole(array(Role::ROLE_BUDGET_OUTCOMING_REQUEST, Role::ROLE_BUDGET_CFO, Role::ROLE_BUDGET_ACCOUNTANT, Role::ROLE_BUDGET_ACC_SECRETARY))) {
			return Redirect::to('/');
		}
	
		if ( Auth::user()->hasRole(Role::ROLE_BUDGET_OUTCOMING_REQUEST) ) {
			return Redirect::to('budget/costsrequests/new');
		}else if ( Auth::user()->hasRole(Role::ROLE_BUDGET_CFO) ) {
			return Redirect::to('budget/costsrequests/new');
		}else if ( Auth::user()->hasAnyRole(array(Role::ROLE_BUDGET_ACCOUNTANT, Role::ROLE_BUDGET_ACC_SECRETARY)) ) {
			return Redirect::to('budget/costsrequests/agreed');
		}
	}

	public function checkCostsRequest() {
		$input = Input::all();
		
		// запрошенная сумма
		$requestedAmount = $input['requestedAmount'];
		// id проекта
		$projectId = $input['requestProjectId'];
		// проект
		$project = Project::find($projectId);
		// id статьи расхода
	  $costId = $input['costId'];
		// статья расхода
		$cost = BudgetCost::find($costId);
		// id группы
		$costGroupId = $cost->budget_cost_group_id;
		// группа
		$costGroup = BudgetCostGroup::find($costGroupId);
		// % Группы
		$costGroupProject = BudgetCostGroupProject::where('project_id', '=', $projectId)
						                                  ->where('budget_cost_group_id', '=', $costGroupId)
						                                  ->first();
		if($costGroupProject){
		  $costGroupPercent = $costGroupProject->amount/100;
		}
		else{
			$costGroupPercent = 0;
		}
		// бюджет проекта
		$projectAmount = $project->getCurrentBudgetMonthPlan();
		// бюджет группы
		$costGroupAmount = $projectAmount*$costGroupPercent/100;
		// расходы группы
		$groupFactSum = $costGroup->getGroupSum($projectId);
		//доступная сумма бюджета в рублях
		$availableSum = $costGroupAmount - $groupFactSum;
		
		if($costGroupAmount){
			// доступно % бюджета
			$available = ($costGroupAmount - $groupFactSum)*100/$costGroupAmount;
			// доступно % бюджета с учетом запрошенной суммы
			$availableAfter = ($costGroupAmount - $groupFactSum - $requestedAmount)*100/$costGroupAmount;
		}
		else{
			$available      = 0;
			$availableAfter = 0;
		}
		
		$message = '';
		$message1 = '';
		
		if( !$projectAmount || !$costGroupPercent ){
			$message = 'Баланс группы: '.round($groupFactSum*(-1), 2).' руб. <p>Не задан бюджет группы или проекта</p>';
			$message1 = 'Баланс группы после оплаты: '.round(($groupFactSum + $requestedAmount)*(-1), 2).' руб.';
		} 
		else{
			// сообщение под группой 
			if( $available < 0){
				$message = 'Доступно: '.$availableSum.' руб. <p class="text-danger">Перерасход средств по данной группе расходов</p>';
			}
			else if( $available < 30 ){
				$message = 'Доступно: '.$availableSum.' руб. <p class="text-warning">Расходы по данной группе превышают 70% бюджета группы</p>';
			}
			else if( $available > 30 ){
				$message = 'Доступно: '.$availableSum.' руб.';
			}

			if($requestedAmount){
				//сообщение под суммой
				if( $availableAfter < 0 ){
					$message1 = '<p class="text-danger">Перерасход бюджета группы при оплате данной суммы</p>';
				}
				else if( $availableAfter < 30 ){
					$message1 = '<p class="text-warning">Будет превышено 70% бюджета группы при оплате данной суммы</p>';
				}
			}
		}
		
		$response = array(
				'message'		 => $message,
				'message1'	 => $message1				
		);
		return Response::json($response);
	}
	
	// создание заявки
	public function createRequest() {
		$input = Input::all();
		$input['requestedAmount'] = trim($input['requestedAmount']);
		$input['requestedAmount'] = str_replace( ',', '.', $input['requestedAmount'] );
		
		$validator = Validator::make($input, array(
								'requestedAmount'	 => 'numeric',
				        'userForSignId'    => 'required',
				        //'requestProjectId' => 'required'
		));

		if ($validator->fails()) {
			$messages = $validator->messages();
			
			if ($messages->has('requestedAmount')) {
				$message		 = 'Сумма расходов должна быть числом';
				$error_field = 'message-box-sum';
			}
			else if ($messages->has('userForSignId')) {
				$message		 = 'Необходимо выбрать сотрудника для подписи';
				$error_field = 'message-box-sign';
			}
			$response = array(
					'status'				 => 'fail',
					'error_message'	 => $message,
					'error_field'		 => $error_field
			);
			return Response::json($response);
		}
		
		$costSelect = BudgetCost::find(e($input['costSelect']));
		if ($costSelect == null) {
				$response = array(
					'status' => 'fail',
					'message'=> 'Статья расхода с таким id не найдена'
			  );
			return Response::json($response);
		}
	
		$project = Project::find($input['requestProjectId']);
		if($project){
			$projectId = $project->id;	
		}else{
			$response = array(
					'status' => 'fail',
					'message'=> 'Проект не найден'
				);
			return Response::json($response);
		}
		
		$account = BudgetAccount::find(e($input['costRequestAccount']));
		
		if (!$account) {
		  $accountId = null;
		}
		else if ($account->project_id == $projectId) {
			$accountId = $account->id;
		}
		else {
			$response = array(
					'status'				 => 'fail',
					'error_message'	 => 'Счет не относится к данному проекту',
					'error_field'		 => 'message-box-account'
			);
			
			return Response::json($response);
		}
		
		$user = User::find($input['userForSignId']);
		if($user){
			if(!$user->hasRole(Role::ROLE_BUDGET_SIGN_COST_REQUEST)){
				$response = array(
					'status' => 'fail',
					'message'=> 'У данного пользователя нет права подписывать заявки'
				);
				return Response::json($response);
			}	
		}else{
			$response = array(
					'status' => 'fail',
					'message'=> 'Пользователь с таким id не найден'
				);
			return Response::json($response);
		}
		$requestedAmount = $input['requestedAmount']*100;
		
		$status = 0;
		if($input['towork'] == 1){  // если нажали Отправить в работу
		  $status = BudgetCostsRequests::STATUS_WORK;
		}
		$ispattern = 0; // создается шаблон
		if( isset($input['ispattern']) ){
		  $ispattern = 1;
			$status    = null;
		}
		
		$costsRequest = BudgetCostsRequests::create(array(
				'project_id'           => $projectId,
				'ispattern'						 => $ispattern,
				'status'							 => $status,
				'applicant_id'				 => $this->user->id,
				'budget_cost_group_id' => $costSelect->id,
				'budget_account_id'    => $accountId,
        'requested_amount'     => $requestedAmount,
				'request_comment'      => e($input['requestComment']),
				'director_id'          => $user->id
		));
		$costsRequest->save();
   
		if( isset($input['file']) ){
			foreach($input['file'] as $key=>$value){
				$file = BudgetCostsRequestsFiles::find($value);
				if($file){
					$file->budget_cost_request_id = $costsRequest->id;
					$file->save();
				}
			}
		}
		
		$statusType = Session::get('statusType');
		$userType = Session::get('userType');
	  $signRequest = Session::get('signRequest');
		
		$budgetRefrence = $costsRequest->saveCostRequestEditHistory($costsRequest);
		if($budgetRefrence->status_new == BudgetCostsRequests::STATUS_WORK){
		  $costsRequest->createNotification($budgetRefrence->id, $budgetRefrence->director_id_new);
		}
		
		$response = array(
				'status'		 => 'success',
				'id'				 => $costsRequest->id,
				'operation'	 => View::make('budget.costsrequests.operation')
														->with('projectAmount', $project->getCurrentBudgetMonthPlan())
														->with('statusType', $statusType)
														->with('userType', $userType)
				                    ->with('signRequest', $signRequest)
														->with('user', $this->user)
														->with('costsRequest', $costsRequest)
														->render(),
		);
		return Response::json($response);
	}

	// удаление заявки
	public function deleteCostsRequest() {
		$input = Input::all();

		if (!isset($input['id'])) {
			$response = array('status' => 'fail');
			return Response::json($response);
		}

		$costsRequest = BudgetCostsRequests::find($input['id']);
		if ($costsRequest == null || !is_numeric($input['id'])) {
			$response = array('status' => 'fail', 'message' => 'Операция не найдена');
			return Response::json($response);
		}

		foreach($costsRequest->budgetRefrence()->get() as $budgetRefrence){
			$budgetRefrence->budgetCostsRequestsNotification()->delete();
		}
		
		$budgetRefrence = $costsRequest->saveCostRequestHistoryMessage('Заявка удалена', $costsRequest->status, $costsRequest->status);
    // уведомления об удалении подписанной или одобренной заявки
		if($costsRequest->status == BudgetCostsRequests::STATUS_APPROVED){
		  $costsRequest->createNotification($budgetRefrence->id, $costsRequest->director_id);	
		  $costsRequest->createNotification($budgetRefrence->id, $costsRequest->findirector_id);	
	  }else if($costsRequest->status == BudgetCostsRequests::STATUS_SIGNED){
		  $costsRequest->createNotification($budgetRefrence->id, $costsRequest->director_id);	
		}
		
		$costsRequest->delete();

		$statusType = Session::get('statusType');
		$userType = Session::get('userType');
		$signRequest = Session::get('signRequest');
		
		$response = array(
				'status'		 => 'success',
				'id'				 => $costsRequest->id,
				'operation'	=> View::make('budget.costsrequests.operation')
						               ->with('projectAmount', $this->workProject->getCurrentBudgetMonthPlan())							
						               ->with('statusType', $statusType)								
						               ->with('userType', $userType)
				                   ->with('signRequest', $signRequest)
													 ->with('user', $this->user)
													 ->with('costsRequest', $costsRequest)
													 ->render()
		);
		return Response::json($response);
	}

	// восстановление заявки
	public function restoreCostsRequest() {
		$input = Input::all();

		if (!isset($input['id'])) {
			$response = array('status' => 'fail');
			return Response::json($response);
		}

		$costsRequest = BudgetCostsRequests::withTrashed()->find($input['id']);
		if ($costsRequest == null || !is_numeric($input['id'])) {
			$response = array('status' => 'fail', 'message' => 'Операция не найдена');
			return Response::json($response);
		}

		$costsRequest->restore();

		// восстановить все удаленные уведомления, а не удаленным (сообщения об удалении заявки) поставить Просмотрено
		foreach($costsRequest->budgetRefrence()->get() as $budgetRefrence){
			$enabledNotifications = $budgetRefrence->budgetCostsRequestsNotification()->whereNull('deleted_at')->get();
      foreach ($enabledNotifications as $enabledNotification){
				$enabledNotification->is_viewed = 1;
				$enabledNotification->save();
      }
			$budgetRefrence->budgetCostsRequestsNotification()->restore();
		}
		
		$costsRequest->saveCostRequestHistoryMessage('Заявка восстановлена', $costsRequest->status, $costsRequest->status);
		
		$statusType = Session::get('statusType');
		$userType = Session::get('userType');
		$signRequest = Session::get('signRequest');
		
		$response = array(
				'status'		 => 'success',
				'id'				 => $costsRequest->id,
				'operation'	=> View::make('budget.costsrequests.operation')
													 ->with('projectAmount', $this->workProject->getCurrentBudgetMonthPlan())							
													 ->with('statusType', $statusType)								
													 ->with('userType', $userType)
				                   ->with('signRequest', $signRequest)
													 ->with('user', $this->user)
													 ->with('costsRequest', $costsRequest)
													 ->render()
		);
		return Response::json($response);
	}

	// открытие окна редактирования
	public function editCostsRequest() {
		$input = Input::all();

		if (!isset($input['id'])) {
			$response = array('status' => 'fail');
			return Response::json($response);
		}

		$costsRequest = BudgetCostsRequests::find($input['id']);
		if ($costsRequest == null || !is_numeric($input['id'])) {
			$response = array('status' => 'fail', 'message' => 'Операция не найдена');
			return Response::json($response);
		}
		
		if($costsRequest->budget_account_id){
		  $acc = $costsRequest->budget_account_id;
		}else{
			$acc = 0;
		}
		
		$files = '';
		if( !isset($input['createByPattern']) ){
			$files = BudgetCostsRequestsFiles::where('budget_cost_request_id', '=', $input['id'])->get();
			if(!$files){
				$files = 0;
			}	
		}
		
		$dirComment = '';
		if($costsRequest->status == BudgetCostsRequests::STATUS_BACK_OFF){ // возврат подписывающего
			$dirComment = '<b>Возврат:</b> '.$costsRequest->director_comment;
		}else if($costsRequest->status == BudgetCostsRequests::STATUS_SIGN_REJECT){ // отказ от подписывающего
			$dirComment = '<b>Не подписано:</b> '.$costsRequest->director_comment;
		}else if($costsRequest->status == BudgetCostsRequests::STATUS_REJECT_DIR){ // отказ финдиректора
			$dirComment = '<b>Отказано:</b> '.$costsRequest->findirector_comment;
		}
		
		$showsign = 0;
		if( $costsRequest->director_id == Auth::user()->id /*&& ($costsRequest->status == BudgetCostsRequests::STATUS_WORK || $costsRequest->status == BudgetCostsRequests::STATUS_BACK_OFF)*/ ){
		  $showsign = 1;
		}
		
		if ( (($costsRequest->status == BudgetCostsRequests::STATUS_CREATED || $costsRequest->status == BudgetCostsRequests::STATUS_WORK || $costsRequest->status == BudgetCostsRequests::STATUS_BACK_OFF) && $costsRequest->applicant_id == Auth::user()->id) 
				|| ( ($costsRequest->director_id == Auth::user()->id || Auth::user()->hasRole(Role::ROLE_BUDGET_CFO)) && $costsRequest->status != BudgetCostsRequests::STATUS_APPROVED && $costsRequest->status != BudgetCostsRequests::STATUS_PAID ) ){
			$response = array(
				'id'				       => $costsRequest->id,
				'requestProjectId' => $costsRequest->project_id,
				'ispattern'        => $costsRequest->ispattern,
				'costId'		       => $costsRequest->budget_cost_group_id,
				'account'          => $acc,
				'requestedAmount'  => $costsRequest->requested_amount/100,
				'requestComment'   => $costsRequest->request_comment,
				'filePath'         => URL::to('budget/costsrequests/downloadfile/'),
				'userId'           => Auth::user()->id,
				'files'            => $files,
				'director_id'      => $costsRequest->director_id,
				'dirComment'       => $dirComment,
				'director_comment' => $costsRequest->director_comment,
				'showsign'         => $showsign
			);
			return Response::json($response);
		}
	}

	// сохранение изменений
	public function updateCostsRequest() {
		$input = Input::all();
    $input['requestedAmount'] = trim($input['requestedAmount']);
		$input['requestedAmount'] = str_replace( ',', '.', $input['requestedAmount'] );
		
		$validator = Validator::make($input, array(
								'requestedAmount'	 => 'numeric',
				        'userForSignId'    => 'required'
		));

		if ($validator->fails()) {
			$messages = $validator->messages();
			
			if ($messages->has('requestedAmount')) {
				$message		 = 'Сумма расходов должна быть числом';
				$error_field = 'message-box-sum';
			}
			else if ($messages->has('userForSignId')) {
				$message		 = 'Необходимо выбрать непосредственного руководителя.';
				$error_field = 'message-box-sign';
			}
			$response = array(
					'status'				 => 'fail',
					'error_message'	 => $message,
					'error_field'		 => $error_field
			);
			return Response::json($response);
		}
		
		if (!isset($input['costsRequestId'])) {
			$response = array('status' => 'fail');
			return Response::json($response);
		}
		
	  $costsRequest = BudgetCostsRequests::find($input['costsRequestId']);
		if ($costsRequest == null || !is_numeric($input['costsRequestId'])) {
			$response = array('status' => 'fail', 'message' => 'Заявка не найдена');
			return Response::json($response);
		}
	
		$costsRequestOld = clone $costsRequest;
		
		$project = Project::find($input['requestProjectId']);
		if($project){
			$projectId = $project->id;	
		}else{
			$response = array(
					'status' => 'fail',
					'message'=> 'Проект не найден'
				);
			return Response::json($response);
		}

		$account = BudgetAccount::find(e($input['costRequestAccount']));

		if (!$account) {
		  $accountId = null;
		}
		else if ($account->project_id == $projectId) {
			$accountId = $account->id;
		}
		else {
			$response = array(
					'status'				 => 'fail',
					'error_message'	 => 'Счет не относится к данному проекту',
					'error_field'		 => 'message-box-account'
			);

			return Response::json($response);
		}

		$user = User::find($input['userForSignId']);
		if($user){
			if(!$user->hasRole(Role::ROLE_BUDGET_SIGN_COST_REQUEST)){
				$response = array(
					'status' => 'fail',
					'message'=> 'У данного пользователя нет права подписывать заявки'
				);
				return Response::json($response);
			}	
		}else{
			$response = array(
					'status' => 'fail',
					'message'=> 'Пользователь с таким id не найден'
				);
			return Response::json($response);
		}
    
		$status = $costsRequestOld->status; // по умолчанию остается старый статус
		if( isset($input['towork']) && $input['towork'] == 1 && !$costsRequestOld->ispattern ){  // если нажали Отправить в работу и это не шаблон
		  $status = BudgetCostsRequests::STATUS_WORK;
		}else if( isset($input['agree']) && $input['agree'] == 1 && !$costsRequestOld->ispattern ){ // нажато на подпись в окне редактирования
			$status = BudgetCostsRequests::STATUS_SIGNED;
			$costsRequest->director_signed_at = DB::raw('TIMESTAMP(NOW())');
		}
		// если хотят изменить подписывающего в заявке без повторной отправки на подпись 
		if($status != BudgetCostsRequests::STATUS_WORK && $costsRequest->status == BudgetCostsRequests::STATUS_SIGNED && $costsRequest->director_id != $input['userForSignId']){
				$message		 = 'При изменении подписи необходимо повторно отправить заявку на подпись выбранному сотруднику.';
				$error_field = 'message-box-sign';

				$response = array(
						'status'				 => 'fail',
						'error_message'	 => $message,
						'error_field'		 => $error_field
				);
				return Response::json($response);
		}

		if(isset($input['signRequestComment'])){
			if( $costsRequest->director_id == $user->id && Auth::user()->id == $costsRequest->director_id && $costsRequest->director_comment != $input['signRequestComment'] ){
				$dirComment = ': '.$input['signRequestComment'];
				$costsRequest->director_comment = $input['signRequestComment'];
			}
		}

		$requestedAmount = $input['requestedAmount']*100;
		
		$costsRequest->project_id            = $projectId;
		$costsRequest->status                = $status;
		$costsRequest->budget_cost_group_id  = $input['costSelect'];
		$costsRequest->budget_account_id     = $accountId;
		$costsRequest->requested_amount      = $requestedAmount;
		$costsRequest->request_comment       = $input['requestComment'];
		$costsRequest->director_id           = $user->id;
		
		$costsRequest->save();

		if( isset($input['file']) ){
			foreach($input['file'] as $key=>$value){
				$file = BudgetCostsRequestsFiles::find($value);
				if($file){
					$file->budget_cost_request_id = $costsRequest->id;
					$file->save();
				}
			}
		}
		
		$budgetRefrence = $costsRequest->saveCostRequestEditHistory($costsRequest, $costsRequestOld);
		
		if($budgetRefrence->director_id_new && $budgetRefrence->status_new == $budgetRefrence->status_old && $budgetRefrence->status_old == BudgetCostsRequests::STATUS_WORK && !$costsRequest->ispattern){
			// все старые уведомления отметить прочитанными
				$oldRefrences = BudgetRefrence::whereRequestId($costsRequest->id)
							                           ->get();
				foreach($oldRefrences as $oldRefrence){
					$oldRefrence->setNotificationViewed();
				}
			$costsRequest->createNotification($budgetRefrence->id, $budgetRefrence->director_id_new);
		}else if ($budgetRefrence->status_new != $budgetRefrence->status_old && $budgetRefrence->status_new == BudgetCostsRequests::STATUS_WORK && !$costsRequest->ispattern){
			// все старые уведомления отметить прочитанными
				$oldRefrences = BudgetRefrence::whereRequestId($costsRequest->id)
							                           ->get();
				foreach($oldRefrences as $oldRefrence){
					$oldRefrence->setNotificationViewed();
				}
			$costsRequest->createNotification($budgetRefrence->id, $costsRequest->director_id);
			
			if($budgetRefrence->director_id_new){
				$costsRequest->createNotification($budgetRefrence->id, $costsRequest->applicant_id);
				$costsRequest->createNotification($budgetRefrence->id, $costsRequestOld->director_id);
			}else if($budgetRefrence->status_old == BudgetCostsRequests::STATUS_SIGNED){
			  $costsRequest->createNotification($budgetRefrence->id, $costsRequest->applicant_id);
			}
		}
		else if ($budgetRefrence->status_new != $budgetRefrence->status_old && $budgetRefrence->status_new == BudgetCostsRequests::STATUS_SIGNED && !$costsRequest->ispattern){
       // все старые уведомления отметить прочитанными
				$oldRefrences = BudgetRefrence::whereRequestId($costsRequest->id)
							                           ->get();
				foreach($oldRefrences as $oldRefrence){
					$oldRefrence->setNotificationViewed();
				}
			$costsRequest->createNotification($budgetRefrence->id, $costsRequest->applicant_id);
			// уведомления всем с ролью фин.директора и доступом в проект
				$project = Project::find($costsRequest->project_id);
				if($project){
					foreach($project->users as $user){ 
						if( $user->hasRole(Role::ROLE_BUDGET_CFO) && !$user->isAdmin() ){
							$costsRequest->createNotification($budgetRefrence->id, $user->id);
						}
					}
				}else{
					$response = array(
						'status'          => 'fail',
						'message'         => 'Проект не найден'
					);
				}
		}else if ($budgetRefrence->status_new != $budgetRefrence->status_old && $budgetRefrence->status_new == BudgetCostsRequests::STATUS_WORK && !$costsRequest->ispattern){
       // все старые уведомления отметить прочитанными
				$oldRefrences = BudgetRefrence::whereRequestId($costsRequest->id)
							                           ->get();
				foreach($oldRefrences as $oldRefrence){
					$oldRefrence->setNotificationViewed();
				}
			$costsRequest->createNotification($budgetRefrence->id, $costsRequest->director_id);
		}

		$statusType = Session::get('statusType');
		$userType = Session::get('userType');
		$signRequest = Session::get('signRequest');
		
		$costsRequest = BudgetCostsRequests::find($costsRequest->id); // заявка заново выбирается т.к. дата подписи директором формируется в бд и просто после сохранения возвращает пустое поле
		
		$response = array(
			'status'		=> 'success',
			'id'				=> $costsRequest->id,
			'operation'	=> View::make('budget.costsrequests.operation')
						             ->with('projectAmount', $this->workProject->getCurrentBudgetMonthPlan())							
						             ->with('statusType', $statusType)								
						             ->with('userType', $userType)
				                 ->with('signRequest', $signRequest)
						             ->with('user', $this->user)
						             ->with('costsRequest', $costsRequest)
						             ->render()
		);
		return Response::json($response);
	}

	// подпись/отмена подписи
	public function signCostsRequest() {
		$input = Input::all();
		
		if (!isset($input['id'])) {
			$response = array('status' => 'fail');
			return Response::json($response);
		}
		
	  $costsRequest = BudgetCostsRequests::find($input['id']);
		if ($costsRequest == null || !is_numeric($input['id'])) {
			$response = array('status' => 'fail', 'message' => 'Заявка не найдена');
			return Response::json($response);
		}
		
		if ( $costsRequest->status != BudgetCostsRequests::STATUS_APPROVED && $costsRequest->status != BudgetCostsRequests::STATUS_PAID && $costsRequest->director_id == Auth::user()->id && Auth::user()->hasRole(Role::ROLE_BUDGET_SIGN_COST_REQUEST) && (!isset($input['removeSign']) || !$input['removeSign']) ){
			$oldStatus = $costsRequest->status;
			$dirComment = '';

			$costsRequest->status             = BudgetCostsRequests::STATUS_SIGNED;
			//$costsRequest->director_id        = Auth::user()->id;
			$costsRequest->director_signed_at = DB::raw('TIMESTAMP(NOW())');
			if( isset($input['signRequestComment']) && $input['signRequestComment']){
				if( $costsRequest->director_comment != $input['signRequestComment'] ){
					$dirComment = ': '.$input['signRequestComment'];
				  $costsRequest->director_comment = $input['signRequestComment'];
				}
			}
			$costsRequest->save();

			$budgetRefrence = $costsRequest->saveCostRequestHistoryMessage('Заявка подписана'.$dirComment, $oldStatus, BudgetCostsRequests::STATUS_SIGNED);
			if($oldStatus != BudgetCostsRequests::STATUS_SIGNED){
				// все старые уведомления отметить прочитанными
				$oldRefrences = BudgetRefrence::whereRequestId($costsRequest->id)
																				 ->get();
				foreach($oldRefrences as $oldRefrence){
					$oldRefrence->setNotificationViewed();
				}
				$costsRequest->createNotification($budgetRefrence->id, $costsRequest->applicant_id);
				// уведомления всем с ролью фин.директора и доступом в проект
				$project = Project::find($costsRequest->project_id);
				if($project){
					foreach($project->users as $user){ 
						if( $user->hasRole(Role::ROLE_BUDGET_CFO) && !$user->isAdmin() ){
							$costsRequest->createNotification($budgetRefrence->id, $user->id);
						}
					}
				}else{
					$response = array(
						'status'          => 'fail',
						'message'         => 'Проект не найден'
					);
				}
			}
			
			$response = array(
				'status'          => 'success',
			  'message'         => 'Заявка подписана'
			);
			return Response::json($response);
		}
		elseif ($costsRequest->status == BudgetCostsRequests::STATUS_SIGNED && $costsRequest->director_id == Auth::user()->id && Auth::user()->hasRole(Role::ROLE_BUDGET_SIGN_COST_REQUEST) && (isset($input['removeSign']) && $input['removeSign']) ){
			$costsRequest->status             = BudgetCostsRequests::STATUS_WORK;
			$costsRequest->director_signed_at = null;
			$costsRequest->save();

			// все старые уведомления отметить прочитанными
			$oldRefrences = BudgetRefrence::whereRequestId($costsRequest->id)
																			 ->get();
			foreach($oldRefrences as $oldRefrence){
				$oldRefrence->setNotificationViewed();
			}
			$budgetRefrence = $costsRequest->saveCostRequestHistoryMessage('Подпись заявки отменена', BudgetCostsRequests::STATUS_SIGNED, BudgetCostsRequests::STATUS_WORK);
			$costsRequest->createNotification($budgetRefrence->id, $costsRequest->applicant_id);

			$response = array(
				'status'          => 'success',
				'message'         => 'Подпись заявки успешно отменена'
			);
			return Response::json($response);
		}
	}

	// отказ в подписи
	public function rejectSignCostsRequest() {
		$input = Input::all();
		$comment = $input['rejectComment'];

		if (!isset($input['requestId'])) {
			$response = array('status' => 'fail');
			return Response::json($response);
		}
		
	  $costsRequest = BudgetCostsRequests::find($input['requestId']);
		if ($costsRequest == null || !is_numeric($input['requestId'])) {
			$response = array('status' => 'fail', 'message' => 'Заявка не найдена');
			return Response::json($response);
		}
		
		if ($costsRequest) {
			if ($costsRequest->status == BudgetCostsRequests::STATUS_WORK && $costsRequest->director_id == Auth::user()->id && Auth::user()->hasRole(Role::ROLE_BUDGET_SIGN_COST_REQUEST)){
				$costsRequest->status             = BudgetCostsRequests::STATUS_SIGN_REJECT;
				$costsRequest->director_comment   = $comment;
				$costsRequest->director_signed_at = DB::raw('TIMESTAMP(NOW())');
		    $costsRequest->save();

				$response = array(
					'status'          => 'success'
				);
				
				// все старые уведомления отметить прочитанными
				$oldRefrences = BudgetRefrence::whereRequestId($costsRequest->id)
																				 ->get();
				foreach($oldRefrences as $oldRefrence){
					$oldRefrence->setNotificationViewed();
				}
				$budgetRefrence = $costsRequest->saveCostRequestHistoryMessage('Отказ в подписи: '.$comment, BudgetCostsRequests::STATUS_WORK, BudgetCostsRequests::STATUS_SIGN_REJECT);
				$costsRequest->createNotification($budgetRefrence->id, $costsRequest->applicant_id);
				
				return Response::json($response);
			}
		}
	}
	
	// возврат с подписи на переоформление
	public function backOffCostsRequest() {
		$input = Input::all();
		$comment = $input['rejectComment'];

		if (!isset($input['requestId'])) {
			$response = array('status' => 'fail');
			return Response::json($response);
		}
		
	  $costsRequest = BudgetCostsRequests::find($input['requestId']);
		if ($costsRequest == null || !is_numeric($input['requestId'])) {
			$response = array('status' => 'fail', 'message' => 'Заявка не найдена');
			return Response::json($response);
		}
		
		if ($costsRequest) {
			if ($costsRequest->status == BudgetCostsRequests::STATUS_WORK && $costsRequest->director_id == Auth::user()->id && Auth::user()->hasRole(Role::ROLE_BUDGET_SIGN_COST_REQUEST)){
				$costsRequest->status             = BudgetCostsRequests::STATUS_BACK_OFF;
				$costsRequest->director_comment   = $comment;
				$costsRequest->director_signed_at = DB::raw('TIMESTAMP(NOW())');
		    $costsRequest->save();

				$response = array(
					'status'          => 'success'
				);
				
				// все старые уведомления отметить прочитанными
				$oldRefrences = BudgetRefrence::whereRequestId($costsRequest->id)
																				 ->get();
				foreach($oldRefrences as $oldRefrence){
					$oldRefrence->setNotificationViewed();
				}
				$budgetRefrence =$costsRequest->saveCostRequestHistoryMessage('Возврат заявки с подписи: '.$comment, BudgetCostsRequests::STATUS_WORK, BudgetCostsRequests::STATUS_BACK_OFF);
				$costsRequest->createNotification($budgetRefrence->id, $costsRequest->applicant_id);
				
				return Response::json($response);
			}
			else{
				$response = array('status' => 'fail');
			  return Response::json($response);
			}
		}
	}
	
	// одобрение/отмена одобрения фин. директором
	public function agreeCostsRequest() {
		$input = Input::all();
		
		if (!isset($input['id'])) {
			$response = array('status' => 'fail');
			return Response::json($response);
		}
		
	  $costsRequest = BudgetCostsRequests::find($input['id']);
		if ($costsRequest == null || !is_numeric($input['id'])) {
			$response = array('status' => 'fail', 'message' => 'Заявка не найдена');
			return Response::json($response);
		}

			if ($costsRequest->status == BudgetCostsRequests::STATUS_SIGNED && Auth::user()->hasRole(Role::ROLE_BUDGET_CFO)){
				$costsRequest->status                = BudgetCostsRequests::STATUS_APPROVED;
				$costsRequest->findirector_id        = Auth::user()->id;
				$costsRequest->findirector_signed_at = DB::raw('TIMESTAMP(NOW())');
		    $costsRequest->save();

				$response = array(
					'status'          => 'success'
				);
				
				// все старые уведомления отметить прочитанными
				$oldRefrences = BudgetRefrence::whereRequestId($costsRequest->id)
																				 ->get();
				foreach($oldRefrences as $oldRefrence){
					$oldRefrence->setNotificationViewed();
				}
				$budgetRefrence = $costsRequest->saveCostRequestHistoryMessage('Заявка одобрена финансовым директором', BudgetCostsRequests::STATUS_SIGNED, BudgetCostsRequests::STATUS_APPROVED);
				$costsRequest->createNotification($budgetRefrence->id, $costsRequest->applicant_id); // если заявку создал бухгалтер, то у него получится 2 уведомлления
				$project = Project::find($costsRequest->project_id);
				if($project){
					foreach($project->users as $user){ // всем бухгалтерам этого проекта
						if( $user->hasAnyRole(array(Role::ROLE_BUDGET_ACCOUNTANT, Role::ROLE_BUDGET_ACC_SECRETARY)) && !$user->isAdmin() ){
						  $costsRequest->createNotification($budgetRefrence->id, $user->id);
						}
					}
				}else{
					$response = array(
						'status'          => 'fail',
						'message'         => 'Проект не найден'
					);
				}
				
				return Response::json($response);
			}
			elseif ($costsRequest->status == BudgetCostsRequests::STATUS_APPROVED && Auth::user()->hasRole(Role::ROLE_BUDGET_CFO)){
			$costsRequest->status                = BudgetCostsRequests::STATUS_SIGNED;
			$costsRequest->findirector_id        = null;
			$costsRequest->findirector_signed_at = null;
			$costsRequest->save();

			$response = array(
				'status'          => 'success'
			);
			
			// все старые уведомления отметить прочитанными
			$oldRefrences = BudgetRefrence::whereRequestId($costsRequest->id)
																			 ->get();
			foreach($oldRefrences as $oldRefrence){
				$oldRefrence->setNotificationViewed();
			}
			$budgetRefrence = $costsRequest->saveCostRequestHistoryMessage('Отмена одобрения заявки', BudgetCostsRequests::STATUS_APPROVED, BudgetCostsRequests::STATUS_SIGNED);
			$costsRequest->createNotification($budgetRefrence->id, $costsRequest->applicant_id);
			
			return Response::json($response);
		}
	}

	// разбитие заявки - открытие окна
	public function allocateCostsRequest() {
		$input = Input::all();

		if (!isset($input['id'])) {
			$response = array('status' => 'fail');
			return Response::json($response);
		}

		$costsRequest = BudgetCostsRequests::find($input['id']);
		if ($costsRequest == null || !is_numeric($input['id'])) {
			$response = array('status' => 'fail', 'message' => 'Операция не найдена');
			return Response::json($response);
		}

		$project = Project::find($costsRequest->project_id);
		$cost    = BudgetCost::find($costsRequest->budget_cost_group_id);
		$account = BudgetAccount::find($costsRequest->budget_account_id);
		
		if ( $costsRequest->status == BudgetCostsRequests::STATUS_SIGNED ){
			$response = array(
				'id'				       => $costsRequest->id,
				'requestedAmount'  => $costsRequest->requested_amount/100,
				'project'          => $project,
				'cost'             => $cost,
				'account'          => $account
			);
			return Response::json($response);
		}
	}
	
		// разбитие заявки - Сохранение изменений
	public function saveAllocatedCostsRequest() {
		$input = Input::all();

		// Изменение старой заявки
		$costsRequest = BudgetCostsRequests::find($input['requestId']);
		if ($costsRequest == null || !is_numeric($input['requestId'])) {
			$response = array('status' => 'fail', 'message' => 'Заявка не найдена');
			return Response::json($response);
		}
		if ( $costsRequest->status != BudgetCostsRequests::STATUS_SIGNED || !Auth::user()->hasRole(Role::ROLE_BUDGET_CFO) ){
			$response = array('status' => 'fail', 'message' => 'Неверный статус заявки');
			return Response::json($response);
		}
		$costSelect = BudgetCost::find(e($input['costSelect-1']));
		if ($costSelect == null) {
				$response = array(
					'status' => 'fail',
					'message'=> 'Статья расхода с таким id не найдена'
				);
			return Response::json($response);
		}
		
		$project = Project::find($input['requestProjectId-1']);
		if($project){
			$projectId = $project->id;	
		}else{
			$response = array(
					'status' => 'fail',
					'message'=> 'Проект не найден'
				);
			return Response::json($response);
		}
		
		$account = BudgetAccount::find(e($input['costRequestAccount-1']));
		if (!$account) {
		  $accountId = null;
		}
		else if ($account->project_id == $projectId) {
			$accountId = $account->id;
		}
		else {
			$response = array(
					'status'				 => 'fail',
					'error_message'	 => 'Счет не относится к данному проекту',
					'error_field'		 => 'message-box-account'
			);
			
			return Response::json($response);
		}
		
		$costRequestOld = clone $costsRequest;
		
		$amount = trim($input['requestedAmount-1']);
		$requestedAmount = str_replace( ',', '.', $amount )*100;
		
		$costsRequest->project_id            = $projectId;
		$costsRequest->status                = BudgetCostsRequests::STATUS_APPROVED;
		$costsRequest->budget_cost_group_id  = $costSelect->id;
		$costsRequest->budget_account_id     = $accountId;
		$costsRequest->requested_amount      = $requestedAmount;
		$costsRequest->findirector_id        = $this->user->id;
		$costsRequest->findirector_signed_at = DB::raw('TIMESTAMP(NOW())');	
		$costsRequest->requested_amount_old  = $costRequestOld->requested_amount;	
		$costsRequest->save();

		$budgetRefrence = $costsRequest->saveCostRequestEditHistory($costsRequest, $costRequestOld);
		
		// все старые уведомления отметить прочитанными
		$oldRefrences = BudgetRefrence::whereRequestId($costsRequest->id)
																		 ->get();
		foreach($oldRefrences as $oldRefrence){
			$oldRefrence->setNotificationViewed();
		}
		$costsRequest->createNotification($budgetRefrence->id, $costsRequest->applicant_id);
		$project = Project::find($costsRequest->project_id);
				if($project){
					foreach($project->users as $user){ // всем бухгалтерам этого проекта
						if( $user->hasAnyRole(array(Role::ROLE_BUDGET_ACCOUNTANT, Role::ROLE_BUDGET_ACC_SECRETARY)) && !$user->isAdmin() ){
						  $costsRequest->createNotification($budgetRefrence->id, $user->id);
						}
					}
				}else{
					$response = array(
						'status'          => 'fail',
						'message'         => 'Проект не найден'
					);
				}
		
		// Создание новых
		$newRequests = ''; // собираем новые заявки
		foreach($input['requestedAmount'] as $key => $value){
			$amount = trim($value);
			if( $amount && is_numeric($amount) ){
				$projects = $input['requestProjectId'];
				$project = Project::find($projects[$key]);
				if($project){
					$projectId = $project->id;	
				}else{
					$response = array(
							'status' => 'fail',
							'message'=> 'Проект не найден'
						);
					return Response::json($response);
				}

				$requestAccounts = $input['costRequestAccount'];
				$account = BudgetAccount::find($requestAccounts[$key]);
				if (!$account) {
					$accountId = null;
				}
				else if ($account->project_id == $projectId) {
					$accountId = $account->id;
				}
				else {
					$response = array(
							'status'				 => 'fail',
							'error_message'	 => 'Счет не относится к данному проекту',
							'error_field'		 => 'message-box-account'
					);

					return Response::json($response);
				}

				$requestedAmount = str_replace( ',', '.', $amount )*100;

				$newCostsRequest = BudgetCostsRequests::create(array(
						'project_id'            => $projectId,
						'parent_request_id'     => $costsRequest->id,
						'status'							  => BudgetCostsRequests::STATUS_APPROVED,
						'applicant_id'				  => $costsRequest->applicant_id,
						'budget_cost_group_id'  => $costSelect->id,
						'budget_account_id'     => $accountId,
						'requested_amount'      => $requestedAmount,
						'director_id'           => $costsRequest->director_id,
						'director_signed_at'    => $costsRequest->director_signed_at,
						'findirector_id'        => $this->user->id,
		        'findirector_signed_at' => DB::raw('TIMESTAMP(NOW())')
				));
				$newRequests .= '<br><b>#'.$newCostsRequest->id.'</b>, '.($requestedAmount/100).' руб., '.$project->name.'; ';
				$budgetRefrence = $newCostsRequest->saveCostRequestEditHistory($newCostsRequest);
				$project = Project::find($newCostsRequest->project_id);
				if($project){
					foreach($project->users as $user){ // всем бухгалтерам этого проекта
						if( $user->hasAnyRole(array(Role::ROLE_BUDGET_ACCOUNTANT, Role::ROLE_BUDGET_ACC_SECRETARY)) && !$user->isAdmin() ){
						  $newCostsRequest->createNotification($budgetRefrence->id, $user->id);
						}
					}
				}else{
					$response = array(
						'status'          => 'fail',
						'message'         => 'Проект не найден'
					);
				}
			}
	 	}
		if($newRequests){
			$costsRequestParent = BudgetCostsRequests::find($input['requestId']);
			$costsRequestParent->saveCostRequestHistoryMessage('Сумма заявки распределена на следующие заявки: '.$newRequests, BudgetCostsRequests::STATUS_APPROVED, BudgetCostsRequests::STATUS_APPROVED);
		}
		
		return Response::json($input);
	}
	
	// отказ фин. директором
	public function rejectCostsRequest() {
		$input = Input::all();
		$comment = $input['rejectComment'];

		if (!isset($input['requestId'])) {
			$response = array('status' => 'fail');
			return Response::json($response);
		}
		
	  $costsRequest = BudgetCostsRequests::find($input['requestId']);
		if ($costsRequest == null || !is_numeric($input['requestId'])) {
			$response = array('status' => 'fail', 'message' => 'Заявка не найдена');
			return Response::json($response);
		}
		
		if ($costsRequest) {
			if ($costsRequest->status == BudgetCostsRequests::STATUS_SIGNED && Auth::user()->hasRole(Role::ROLE_BUDGET_CFO)){
				$costsRequest->status                = BudgetCostsRequests::STATUS_REJECT_DIR;
				$costsRequest->findirector_id        = Auth::user()->id;
				$costsRequest->findirector_comment   = $comment;
				$costsRequest->findirector_signed_at = DB::raw('TIMESTAMP(NOW())');
		    $costsRequest->save();

				$response = array(
					'status'          => 'success'
				);
				
				// все старые уведомления отметить прочитанными
				$oldRefrences = BudgetRefrence::whereRequestId($costsRequest->id)
																				 ->get();
				foreach($oldRefrences as $oldRefrence){
					$oldRefrence->setNotificationViewed();
				}
				$budgetRefrence = $costsRequest->saveCostRequestHistoryMessage('Отказано финансовым директором: '.$comment, BudgetCostsRequests::STATUS_SIGNED, BudgetCostsRequests::STATUS_REJECT_DIR);
				$costsRequest->createNotification($budgetRefrence->id, $costsRequest->applicant_id);
				if($costsRequest->applicant_id != $costsRequest->director_id){
				  $costsRequest->createNotification($budgetRefrence->id, $costsRequest->director_id);
				}
				
				return Response::json($response);
			}
		}
	}

	// открытие окна оплаты
	public function openPayCostsRequest() {
		$input = Input::all();

		if (!isset($input['id'])) {
			$response = array('status' => 'fail');
			return Response::json($response);
		}

		$costsRequest = BudgetCostsRequests::find($input['id']);
		if ($costsRequest == null || !is_numeric($input['id'])) {
			$response = array('status' => 'fail', 'message' => 'Операция не найдена');
			return Response::json($response);
		}

		$paidAt = '';
		if($costsRequest->paid_at){
			$date = explode('-', $costsRequest->paid_at);
			$paidAt = "{$date[2]}.{$date[1]}.{$date[0]}";
		}
		
		$response = array(
			'status'            => 'success',
			'id'				        => $costsRequest->id,
			'paidAt'            => $paidAt,
			'bankId'            => $costsRequest->payment_order_number,
			'accountantComment' => $costsRequest->accountant_comment,
		);
		return Response::json($response);
	}
	
	// оплата и отмена оплаты
	public function payCostsRequest() {
		$input = Input::all();

		if (!isset($input['id'])) {
			$response = array('status' => 'fail');
			return Response::json($response);
		}
		
	  $costsRequest = BudgetCostsRequests::find($input['id']);
		if ($costsRequest == null || !is_numeric($input['id'])) {
			$response = array('status' => 'fail', 'message' => 'Заявка не найдена');
			return Response::json($response);
		}

		if ($costsRequest) {		
			if ($costsRequest->status == BudgetCostsRequests::STATUS_APPROVED && Auth::user()->hasAnyRole(array(Role::ROLE_BUDGET_ACCOUNTANT, Role::ROLE_BUDGET_ACC_SECRETARY))){
				$date		 = explode('.', $input['paidAt']);
			  $paidAt = "{$date[2]}-{$date[1]}-{$date[0]}";
				
				$costsRequest->status               = BudgetCostsRequests::STATUS_PAID;
				$costsRequest->accountant_id        = Auth::user()->id;
				$costsRequest->payment_order_number = e($input['bankId']);
				$costsRequest->paid_at              = $paidAt;
				$costsRequest->accountant_comment   = e($input['accountantComment']);
		    $costsRequest->save();

				$response = array(
					'status'          => 'success'
				);

				// все старые уведомления отметить прочитанными
				$oldRefrences = BudgetRefrence::whereRequestId($costsRequest->id)
							                           ->get();
				foreach($oldRefrences as $oldRefrence){
					$oldRefrence->setNotificationViewed();
				}
				
				$budgetRefrence = $costsRequest->saveCostRequestHistoryMessage('Заявка оплачена: п/п № '.e($input['bankId']).', от '.$input['paidAt'].', '.e($input['accountantComment']), BudgetCostsRequests::STATUS_APPROVED, BudgetCostsRequests::STATUS_PAID);
				$costsRequest->createNotification($budgetRefrence->id, $costsRequest->applicant_id);
				
				return Response::json($response);
			}
			else if ($costsRequest->status == BudgetCostsRequests::STATUS_PAID && Auth::user()->hasAnyRole(array(Role::ROLE_BUDGET_ACCOUNTANT, Role::ROLE_BUDGET_ACC_SECRETARY))){
				$costsRequest->status = BudgetCostsRequests::STATUS_APPROVED;
		    $costsRequest->save();

				$response = array(
					'status'          => 'success'
				);
				// все старые уведомления отметить прочитанными
				$oldRefrences = BudgetRefrence::whereRequestId($costsRequest->id)
							                           ->get();
				foreach($oldRefrences as $oldRefrence){
					$oldRefrence->setNotificationViewed();
				}
				
				$budgetRefrence = $costsRequest->saveCostRequestHistoryMessage('Отмена оплаты заявки', BudgetCostsRequests::STATUS_PAID, BudgetCostsRequests::STATUS_APPROVED);
				$costsRequest->createNotification($budgetRefrence->id, $costsRequest->applicant_id);

				return Response::json($response);
			}
		}
	}
	
	// ввод номера п/п
	public function setAccountCode() {
		$input = Input::all();

		if ( !isset($input['pk']) ) {
			$response = array('status' => 'fail', 'message' => 'Отсутствует номер заявки');
			return Response::json($response);
		}

		$costsRequest = BudgetCostsRequests::find($input['pk']);
		if ($costsRequest == null || !is_numeric($input['pk'])) {
			$response = array('status' => 'fail', 'message' => 'Заявка не найдена');
			return Response::json($response);
		}
		$costsRequest->accountant_id        = Auth::user()->id;
		$costsRequest->payment_order_number = trim($input['value']);
		$costsRequest->save();

		$response = array(
			'status'          => 'success'
		);
		
		$costsRequest->saveCostRequestHistoryMessage('Номер п/п: '.trim($input['value']), BudgetCostsRequests::STATUS_APPROVED, BudgetCostsRequests::STATUS_APPROVED);
		
		return Response::json($response);
	}

	// история работы с заявкой
	public function showHistory($requestId) {

		$costsRequest = BudgetCostsRequests::withTrashed()->find($requestId);
		if ($costsRequest == null || !is_numeric($requestId)) {
			$response = array('status' => 'fail', 'message' => 'Заявка не найдена');
			return Response::json($response);
		}

		$refrences = BudgetRefrence::select(DB::raw('budget_refrences.*,
																								 u.first_name as director_first_name,
																								 u.last_name as director_last_name,
																								 u1.first_name as user_first_name,
																								 u1.last_name as user_last_name,
																								 p.name as project_name,
																								 bc.name as cost_name,
																								 ba.name as account_name,
																								 ba.current_account as account_number'))
																->leftJoin('users as u1', 'u1.id', '=', 'budget_refrences.user_id')
																->leftJoin('projects as p', 'p.id', '=', 'budget_refrences.project_id_new')
																->leftJoin('budget_costs as bc', 'bc.id', '=', 'budget_refrences.budget_cost_group_id_new')
																->leftJoin('budget_accounts as ba', 'ba.id', '=', 'budget_refrences.budget_account_id_new')
																->leftJoin('users as u', 'u.id', '=', 'budget_refrences.director_id_new')
						                    ->whereRequestId($requestId)
						                    ->orderBy('budget_refrences.id', 'DESC')
						                    ->get();

		$status = 'success';
		if( !isset($refrences[0]) ){
			$status = 'nohistory';
		}
		
		$response = array(
			'status'     => $status,
			'requestId'  => $costsRequest->id,
			'refrences'	 => $refrences->toArray()
		);
		return Response::json($response);
	}
	
	//---------------------- Уведомления ------------------------------------//
	
	// список уведомлений по заявкам
	public function getNewNotifications() {
		$userId = Auth::user()->id;

		$costsRequestNotifications = DB::table('budget_costs_requests_notifications as bcrn')->select(DB::raw('br.*, 
						                                                                              bcrn.id as bcrn_id,
																																													bcrn.budget_refrence_id as bcrn_budget_refrence_id,
																																													bcrn.access_user_id as bcrn_access_user_id,
																																													bcrn.is_viewed as bcrn_is_viewed,
																																													bcrn.created_at as bcrn_created_at,
																																													bcr.requested_amount as bcr_requested_amount,
																																													bcr.created_at as bcr_created_at,
																																													bcr.deleted_at as bcr_deleted_at,
																																													bc.name as costName,
																																													p.name as projectName,
																																													u.last_name as u_last_name,
																																													u.first_name as u_first_name'
						                                                                              ))
																																												 ->whereAccessUserId($userId)
																																												 ->leftJoin('budget_refrences as br', 'br.id', '=', 'bcrn.budget_refrence_id')
																																												 ->leftJoin('budget_costs_requests as bcr', 'bcr.id', '=', 'br.request_id')
																																												 ->leftJoin('budget_costs as bc', 'bc.id', '=', 'bcr.budget_cost_group_id')
																																												 ->leftJoin('projects as p', 'p.id', '=', 'bcr.project_id')
																																												 ->leftJoin('users as u', 'u.id', '=', 'bcr.director_id')
																																												 ->whereNull('bcrn.is_viewed')
																																												 ->whereNull('bcrn.deleted_at')
																																												 ->get();
		$response = array(
			'status'        => 'success',
			'notifications' => $costsRequestNotifications
		);
		return Response::json($response);
	}
	
	/*public function getCountNotifications() { // Заменить закомментированной функцией ниже
		$userId = Auth::user()->id;

		$costsRequestNotifications = DB::table('budget_costs_requests_notifications as bcrn')->select(DB::raw('count(br.status_new) as count,
						                                                                              br.status_new as status'))
																																												 ->whereAccessUserId($userId)
																																												 ->leftJoin('budget_refrences as br', 'br.id', '=', 'bcrn.budget_refrence_id')
																																												 ->whereNull('bcrn.is_viewed')
																																												 ->whereNull('bcrn.deleted_at')
						                                                                             ->groupBy('br.status_new')
																																												 ->get();
		
		$notifications = [];
		foreach ($costsRequestNotifications as $notification){
		  $notifications[$notification->status] = $notification->count;
		}
		
		$actionStatus = []; // набор статусов заявок требующих обработки
		$actionStatus[] = BudgetCostsRequests::STATUS_BACK_OFF;
			
		if(Auth::user()->hasRole(Role::ROLE_BUDGET_SIGN_COST_REQUEST) && !Auth::user()->isAdmin()){
			$actionStatus[] = BudgetCostsRequests::STATUS_WORK;
		}
		if(Auth::user()->hasRole(Role::ROLE_BUDGET_CFO) && !Auth::user()->isAdmin()){
			$actionStatus[] = BudgetCostsRequests::STATUS_SIGNED;
		}
		if(Auth::user()->hasAnyRole(array(Role::ROLE_BUDGET_ACCOUNTANT, Role::ROLE_BUDGET_ACC_SECRETARY)) && !Auth::user()->isAdmin()){
			$actionStatus[] = BudgetCostsRequests::STATUS_APPROVED;
		}
		
		$response = array(
			'status'        => 'success',
			'notifications' => $notifications,
			'actionStatus'  => $actionStatus
		);
		return Response::json($response);
	}*/
	
	public function getCountRequestsByStatus() {
	  $user = Auth::user();
		$allRequestsByStatus = [];
		//$actionRequests   = [];
		//$countDirRejects = 0; // отказы в подписи
		//$countFindirRejects = 0; // отказы фин. директора
    // возвраты 
		
		//------------------------- ЗАЯВИТЕЛЬ--------------------------------------//
		if ( $user->hasRole(Role::ROLE_BUDGET_OUTCOMING_REQUEST) ){
			$costRequests = BudgetCostsRequests::select(DB::raw('count(status) as count, status'))
																					->whereRaw('(applicant_id = '.$user->id.' OR director_id = '.$user->id.')')
																					->whereIspattern(0)
																					->where('status', '>', 0)
							                            ->groupBy('status')
																					->get();
			if($costRequests){
				/*if( isset($costRequests[0]) ){
					$countDirRejects = $costRequests[0]->countDirRejects;
					$countFindirRejects = $costRequests[0]->countFindirRejects;
				}*/
				// все
				foreach ($costRequests as $costRequest){
					if($costRequest->status){
						$allRequestsByStatus[$costRequest->status] = $costRequest->count;
						// для обработки
						/*if( $costRequest->status ==  BudgetCostsRequests::STATUS_BACK_OFF ){
							$actionRequests[$costRequest->status] = $costRequest->count;
						}*/
					}
				}
			}
		//------------------------- ФИН ДИРЕКТОР-----------------------------------//
		}else if ($user->hasRole(Role::ROLE_BUDGET_CFO) && !$user->isAdmin()) {
			$costRequests = BudgetCostsRequests::select(DB::raw('count(status) as count, status'))
																					->whereRaw('( applicant_id = '.$user->id.' OR director_id = '.$user->id.' OR status not in (1,6,7) )')
																					->whereIspattern(0)
																					->where('status', '>', 0)
							                            ->groupBy('status')
																					->get();
			if($costRequests){
				/*if( isset($costRequests[0]) ){
					$countDirRejects = $costRequests[0]->countDirRejects;
					$countFindirRejects = $costRequests[0]->countFindirRejects;
				}*/
				// все
				foreach ($costRequests as $costRequest){
					if($costRequest->status){
						$allRequestsByStatus[$costRequest->status] = $costRequest->count;
						// для обработки
						/*if( $costRequest->status ==  BudgetCostsRequests::STATUS_SIGNED ){
							$actionRequests[$costRequest->status] = $costRequest->count;
						}*/
					}
				}
			}
		//----------------------- БУХГАЛТЕР ---------------------------------------//
		}else if ( $user->hasAnyRole(array(Role::ROLE_BUDGET_ACCOUNTANT, Role::ROLE_BUDGET_ACC_SECRETARY)) && !$user->isAdmin() ) {
			$costRequests = BudgetCostsRequests::select(DB::raw('count(status) as count, status'))
																					->whereRaw('( applicant_id = '.$user->id.' OR director_id = '.$user->id.' OR status in (3,4) )')
																					->whereIspattern(0)
							                            ->groupBy('status')
																					->get();
			if($costRequests){
				/*if( isset($costRequests[0]) ){
					$countDirRejects = $costRequests[0]->countDirRejects;
					$countFindirRejects = $costRequests[0]->countFindirRejects;
				}*/
				// все
				foreach ($costRequests as $costRequest){
					if($costRequest->status){
						$allRequestsByStatus[$costRequest->status] = $costRequest->count;
						// для обработки
						/*if( $costRequest->status ==  BudgetCostsRequests::STATUS_APPROVED || $costRequest->status ==  BudgetCostsRequests::STATUS_BACK_OFF){
							$actionRequests[$costRequest->status] = $costRequest->count;
						}*/
					}
				}
			}
		}


		/*if ($user->hasRole(Role::ROLE_BUDGET_SIGN_COST_REQUEST) && !$user->isAdmin()) {
			$requestsForSign = BudgetCostsRequests::whereDirectorId($user->id)
																						->whereStatus(BudgetCostsRequests::STATUS_WORK)
																						->orderBy('created_at', 'DESC')
																						->count();
			foreach ($costRequests as $costRequest){
				if($costRequest->status){
					$allRequestsByStatus[$costRequest->status] = $costRequest->count;
					// для обработки
					if( $costRequest->status ==  BudgetCostsRequests::STATUS_SIGNED ){
						$actionRequests[$costRequest->status] = $costRequest->count;
					}
				}
			}
		}*/

		$response = array(
			'status'              => 'success',
			//'$costRequests'       => $costRequests,
			//'countDirRejects'     => $countDirRejects,
			//'countFindirRejects'  => $countFindirRejects,
			'allRequestsByStatus' => $allRequestsByStatus, // все заявки по статусам
			//'actionRequests'      => $actionRequests // заявки, требующие обработки
		);
		return Response::json($response);
	}

	// отметка о просмотре уведомления
	public function setViewNotification() {
		$input = Input::all();

		if (isset($input['bcrnId']) && !is_numeric($input['bcrnId'])) {
			$response = array('status' => 'fail', 'message' => 'Неверный номер уведомления');
			return Response::json($response);
		}
		
		$costsRequestNotification = BudgetCostsRequestsNotification::whereId($input['bcrnId'])
																																->whereAccessUserId(Auth::user()->id)
																																->first();
		if($costsRequestNotification){
			$costsRequestNotification->is_viewed = 1;
			$costsRequestNotification->save();
			
			$response = array(
				'status'        => 'success',
				'notifications' => $costsRequestNotification
			);
		}else{
			$response = array(
				'status'        => 'fail',
				'message'       => 'Уведомление не найдено'
			);
		}
		
		return Response::json($response);
	}
	//---------------------- Вкладки ----------------------------------------//

  // на подпись
	public function signCostsRequests() {
    $input = Input::all();

		if (Session::get('statusType') && Input::has('projectId')) {
			return Redirect::to('budget/costsrequests/'.Session::get('statusType'));
		}

        $workProject = $this->workProject;
        
        if ($this->user->budgetProjects->first() == null 
            || !$this->user->hasAnyRole(array(Role::ROLE_BUDGET_OUTCOMING_REQUEST, Role::ROLE_BUDGET_CFO, Role::ROLE_BUDGET_ACCOUNTANT, Role::ROLE_BUDGET_ACC_SECRETARY))
            || !$this->user->hasProject($workProject->id)
           ) {
            $workProject = $this->user->budgetProjects->first();
            Session::put($this->projectPrefix.'_work_projectId', $workProject->id);
			return Redirect::to("budget/");
		}
        
		if (Input::has('projectId')) {
			Session::put('work_projectId', $input['projectId']);
			return Redirect::to('budget/costsrequests');
		}
		
		// во вкладке "На подпись" все с правом подписи, кроме фин директора будут видеть и новые, и подписанные ими заявки (для информации)
		// для фин. директора подписанные убраны из этой вкладки во избежание путаницы, т.к. эти заявки у него будут еще в "Новых"
    if (!Auth::user()->hasRole( Role::ROLE_BUDGET_CFO)) {
			$costsRequests = BudgetCostsRequests::whereProjectId($workProject->id)
																					->whereIn('status', array(BudgetCostsRequests::STATUS_SIGNED, BudgetCostsRequests::STATUS_WORK))
							                            ->whereIspattern(0)
																					->whereDirectorId($this->user->id)
																					->where('created_at', '>=', DB::raw('NOW() - INTERVAL 3 MONTH'))
																					->orderBy('created_at', 'DESC')
																					->get();
		}
		else{
			$costsRequests = BudgetCostsRequests::whereProjectId($workProject->id)
																				->whereIn('status', array(BudgetCostsRequests::STATUS_BACK_OFF, BudgetCostsRequests::STATUS_WORK))
																				->whereIspattern(0)
						                            ->whereDirectorId($this->user->id)
																				->where('created_at', '>=', DB::raw('NOW() - INTERVAL 3 MONTH'))
																				->orderBy('created_at', 'DESC')
																				->get();
		}
	
		$budgetCostsGroups = BudgetCostGroup::groupBy('name')->get();

		Session::put('statusType', 'sign');
		
		return $this->setupLayout('budget.costsrequests.index')
										->with('user', $this->user)
						        ->with('costsRequests', $costsRequests)
						        ->with('budgetCostsGroups', $budgetCostsGroups)
										->with('workProject', $workProject);
	}
	
    // Новые
	public function newCostsRequests() {
    $input = Input::all();

		if (Session::get('statusType') && Input::has('projectId')) {
			return Redirect::to('budget/costsrequests/'.Session::get('statusType'));
		}
		
		$workProject = $this->workProject;
        
        if ($this->user->budgetProjects->first() == null 
            || !$this->user->hasAnyRole(array(Role::ROLE_BUDGET_OUTCOMING_REQUEST, Role::ROLE_BUDGET_CFO, Role::ROLE_BUDGET_ACCOUNTANT, Role::ROLE_BUDGET_ACC_SECRETARY))
            || !$this->user->hasProject($workProject->id)
           ) {
            $workProject = $this->user->budgetProjects->first();
            Session::put($this->projectPrefix.'_work_projectId', $workProject->id);
			return Redirect::to("budget/");
		}
		if (Input::has('projectId')) {
			Session::put('work_projectId', $input['projectId']);
			return Redirect::to('budget/costsrequests');
		}

		if ( Auth::user()->hasRole(Role::ROLE_BUDGET_OUTCOMING_REQUEST) ) {
			$costsRequests = BudgetCostsRequests::whereProjectId($workProject->id)
							                            ->whereRaw('(applicant_id = '.$this->user->id.' OR (director_id = '.$this->user->id.' AND status > 0) )')
																					->whereIspattern(0)
							                            ->whereIn('status', array(BudgetCostsRequests::STATUS_SIGNED, BudgetCostsRequests::STATUS_CREATED, BudgetCostsRequests::STATUS_WORK, BudgetCostsRequests::STATUS_BACK_OFF))
																					->orderBy('created_at', 'DESC')
																					->get();
		}
		else if ( Auth::user()->hasRole(Role::ROLE_BUDGET_CFO) ) {
			$costsRequests = BudgetCostsRequests::whereProjectId($workProject->id)
							                            ->whereStatus(BudgetCostsRequests::STATUS_SIGNED)
																					->whereIspattern(0)
																					->orderBy('director_signed_at', 'DESC')
																					->get();
		}

		$budgetCostsGroups = BudgetCostGroup::groupBy('name')->get();

		Session::put('statusType', 'new');		
		
		return $this->setupLayout('budget.costsrequests.index')
										->with('user', $this->user)
						        ->with('costsRequests', $costsRequests)
						        ->with('budgetCostsGroups', $budgetCostsGroups)
										->with('workProject', $workProject);
	}

	  // Одобрено
	public function agreedCostsRequests() {
    $input = Input::all();

		if (Session::get('statusType') && Input::has('projectId')) {
			return Redirect::to('budget/costsrequests/'.Session::get('statusType'));
		}
		
		$workProject = $this->workProject;
        
        if ($this->user->budgetProjects->first() == null 
            || !$this->user->hasAnyRole(array(Role::ROLE_BUDGET_OUTCOMING_REQUEST, Role::ROLE_BUDGET_CFO, Role::ROLE_BUDGET_ACCOUNTANT, Role::ROLE_BUDGET_ACC_SECRETARY))
            || !$this->user->hasProject($workProject->id)
           ) {
            $workProject = $this->user->budgetProjects->first();
            Session::put($this->projectPrefix.'_work_projectId', $workProject->id);
			return Redirect::to("budget/");
		}
		if (Input::has('projectId')) {
			Session::put('work_projectId', $input['projectId']);
			return Redirect::to('budget/costsrequests');
		}

		if ( Auth::user()->hasRole(Role::ROLE_BUDGET_OUTCOMING_REQUEST) ){
			if(!Role::ROLE_BUDGET_SIGN_COST_REQUEST){
				$costsRequests = BudgetCostsRequests::whereProjectId($workProject->id)
																						->whereApplicantId($this->user->id)
																						->whereIspattern(0)
																						->whereStatus(BudgetCostsRequests::STATUS_APPROVED)
																						->where('findirector_signed_at', '>=', DB::raw('NOW() - INTERVAL 3 MONTH'))
																						->orderBy('created_at', 'DESC')
																						->get();
			}else{
				$costsRequests = BudgetCostsRequests::whereProjectId($workProject->id)
																						->whereRaw('(applicant_id = '.$this->user->id.' OR director_id = '.$this->user->id.')')
																						->whereStatus(BudgetCostsRequests::STATUS_APPROVED)
																						->whereIspattern(0)
																						->where('findirector_signed_at', '>=', DB::raw('NOW() - INTERVAL 3 MONTH'))
																						->orderBy('created_at', 'DESC')
																						->get();
			}
		}
		else if ( Auth::user()->hasRole(Role::ROLE_BUDGET_CFO) ) {
			$costsRequests = BudgetCostsRequests::whereProjectId($workProject->id)
							                            ->whereStatus(BudgetCostsRequests::STATUS_APPROVED)
																					->whereIspattern(0)
							                            ->where('findirector_signed_at', '>=', DB::raw('NOW() - INTERVAL 3 MONTH'))
																					->orderBy('created_at', 'DESC')
																					->get();
		}
		else if ( Auth::user()->hasAnyRole(array(Role::ROLE_BUDGET_ACCOUNTANT, Role::ROLE_BUDGET_ACC_SECRETARY)) ) {
			$costsRequests = BudgetCostsRequests::whereProjectId($workProject->id)
							                            ->whereStatus(BudgetCostsRequests::STATUS_APPROVED)
																					->whereIspattern(0)
																					->orderBy('created_at', 'DESC')
																					->get();
		}

		$budgetCostsGroups = BudgetCostGroup::groupBy('name')->get();

		Session::put('statusType', 'agreed');
		
		return $this->setupLayout('budget.costsrequests.index')					
										->with('user', $this->user)
						        ->with('costsRequests', $costsRequests)
						        ->with('budgetCostsGroups', $budgetCostsGroups)
										->with('workProject', $workProject);
	}

	  // Отказано
	public function rejectedCostsRequests() {
    $input = Input::all();
		
		if (Session::get('statusType') && Input::has('projectId')) {
			return Redirect::to('budget/costsrequests/'.Session::get('statusType'));
		}
		
		$workProject = $this->workProject;
        
        if ($this->user->budgetProjects->first() == null 
            || !$this->user->hasAnyRole(array(Role::ROLE_BUDGET_OUTCOMING_REQUEST, Role::ROLE_BUDGET_CFO, Role::ROLE_BUDGET_ACCOUNTANT, Role::ROLE_BUDGET_ACC_SECRETARY))
            || !$this->user->hasProject($workProject->id)
           ) {
            $workProject = $this->user->budgetProjects->first();
            Session::put($this->projectPrefix.'_work_projectId', $workProject->id);
			return Redirect::to("budget/");
		}
		if (Input::has('projectId')) {
			Session::put('work_projectId', $input['projectId']);
			return Redirect::to('budget/costsrequests');
		}

		if ( Auth::user()->hasRole(Role::ROLE_BUDGET_OUTCOMING_REQUEST) ) {
			if(!Role::ROLE_BUDGET_SIGN_COST_REQUEST){
				$costsRequests = BudgetCostsRequests::whereProjectId($workProject->id)
																						->whereApplicantId($this->user->id)
																						->whereIn('status',  array(BudgetCostsRequests::STATUS_REJECT_DIR, BudgetCostsRequests::STATUS_CLOSED, BudgetCostsRequests::STATUS_SIGN_REJECT))
																						->whereIspattern(0)
																						->where('created_at', '>=', DB::raw('NOW() - INTERVAL 3 MONTH'))
																						->orderBy('created_at', 'DESC')
																						->get();
			}else{
				$costsRequests = BudgetCostsRequests::whereProjectId($workProject->id)
																						->whereRaw('(applicant_id = '.$this->user->id.' OR director_id = '.$this->user->id.')')
																						->whereIn('status',  array(BudgetCostsRequests::STATUS_REJECT_DIR, BudgetCostsRequests::STATUS_CLOSED, BudgetCostsRequests::STATUS_SIGN_REJECT))
																						->whereIspattern(0)
																						->where('created_at', '>=', DB::raw('NOW() - INTERVAL 3 MONTH'))
																						->orderBy('created_at', 'DESC')
																						->get();
			}
		}
		else if ( Auth::user()->hasRole(Role::ROLE_BUDGET_CFO) ) {
			$costsRequests = BudgetCostsRequests::whereProjectId($workProject->id)
							                            ->whereRaw('( status = '.BudgetCostsRequests::STATUS_REJECT_DIR.' OR ( status = '.BudgetCostsRequests::STATUS_SIGN_REJECT.' AND (director_id = '.Auth::user()->id.' OR applicant_id = '.Auth::user()->id.') )  )')
																					->whereIspattern(0)
							                            ->where('created_at', '>=', DB::raw('NOW() - INTERVAL 3 MONTH'))
																					->orderBy('created_at', 'DESC')
																					->get();
		}

		$budgetCostsGroups = BudgetCostGroup::groupBy('name')->get();

		Session::put('statusType', 'rejected');
		
		return $this->setupLayout('budget.costsrequests.index')						
										->with('user', $this->user)
						        ->with('costsRequests', $costsRequests)
						        ->with('budgetCostsGroups', $budgetCostsGroups)
										->with('workProject', $workProject);
	}

	  // Оплачено
	public function paidCostsRequests() {
    $input = Input::all();

		if (Session::get('statusType') && Input::has('projectId')) {
			return Redirect::to('budget/costsrequests/'.Session::get('statusType'));
		}
		
		$workProject = $this->workProject;
        
        if ($this->user->budgetProjects->first() == null 
            || !$this->user->hasAnyRole(array(Role::ROLE_BUDGET_OUTCOMING_REQUEST, Role::ROLE_BUDGET_CFO, Role::ROLE_BUDGET_ACCOUNTANT, Role::ROLE_BUDGET_ACC_SECRETARY))
            || !$this->user->hasProject($workProject->id)
           ) {
            $workProject = $this->user->budgetProjects->first();
            Session::put($this->projectPrefix.'_work_projectId', $workProject->id);
			return Redirect::to("budget/");
		}
		if (Input::has('projectId')) {
			Session::put('work_projectId', $input['projectId']);
			return Redirect::to('budget/costsrequests');
		}

		if ( Auth::user()->hasRole(Role::ROLE_BUDGET_OUTCOMING_REQUEST) ) {
			if(!Role::ROLE_BUDGET_SIGN_COST_REQUEST){
				$costsRequests = BudgetCostsRequests::whereProjectId($workProject->id)
																						->whereApplicantId($this->user->id)
																						->whereStatus(BudgetCostsRequests::STATUS_PAID)
																						->whereIspattern(0)
																						->where('paid_at', '>=', DB::raw('NOW() - INTERVAL 3 MONTH'))
																						->orderBy('created_at', 'DESC')
																						->get();
			}else{
				$costsRequests = BudgetCostsRequests::whereProjectId($workProject->id)
																						->whereRaw('(applicant_id = '.$this->user->id.' OR director_id = '.$this->user->id.')')
																						->whereStatus(BudgetCostsRequests::STATUS_PAID)
																						->whereIspattern(0)
																						->where('paid_at', '>=', DB::raw('NOW() - INTERVAL 3 MONTH'))
																						->orderBy('created_at', 'DESC')
																						->get();
			}
		}
		else if ( Auth::user()->hasRole(Role::ROLE_BUDGET_CFO) ) {
			$costsRequests = BudgetCostsRequests::whereProjectId($workProject->id)
							                            ->whereStatus(BudgetCostsRequests::STATUS_PAID)
																					->whereIspattern(0)
							                            ->where('paid_at', '>=', DB::raw('NOW() - INTERVAL 3 MONTH'))
																					->orderBy('created_at', 'DESC')
																					->get();
		}
		else if ( Auth::user()->hasAnyRole(array(Role::ROLE_BUDGET_ACCOUNTANT, Role::ROLE_BUDGET_ACC_SECRETARY)) ) {
			$costsRequests = BudgetCostsRequests::whereProjectId($workProject->id)
							                            ->whereStatus(BudgetCostsRequests::STATUS_PAID)
																					->whereIspattern(0)
							                            ->where('paid_at', '>=', DB::raw('NOW() - INTERVAL 3 MONTH'))
																					->orderBy('created_at', 'DESC')
																					->get();
		}

		$budgetCostsGroups = BudgetCostGroup::groupBy('name')->get();

		Session::put('statusType', 'paid');
		
		return $this->setupLayout('budget.costsrequests.index')
										->with('user', $this->user)
						        ->with('costsRequests', $costsRequests)
						        ->with('budgetCostsGroups', $budgetCostsGroups)
										->with('workProject', $workProject);
	}

	  // "Мои"
	public function myCostsRequests() {
    $input = Input::all();

		if (Session::get('statusType') && Input::has('projectId')) {
			return Redirect::to('budget/costsrequests/'.Session::get('statusType'));
		}
		
		if (!$this->user->budgetProjects->count()) {
			return Redirect::to('/');
		}
		if (!Auth::user()->hasAnyRole(array(Role::ROLE_BUDGET_CFO, Role::ROLE_BUDGET_ACCOUNTANT, Role::ROLE_BUDGET_ACC_SECRETARY))) {
			return Redirect::to('/');
		}
		if (Input::has('projectId')) {
			Session::put('work_projectId', $input['projectId']);
			return Redirect::to('budget/costsrequests');
		}

		if (Auth::user()->hasAnyRole(array(Role::ROLE_BUDGET_CFO, Role::ROLE_BUDGET_ACCOUNTANT, Role::ROLE_BUDGET_ACC_SECRETARY))) {
			$costsRequests = BudgetCostsRequests::whereProjectId($this->workProject->id)
							                            ->whereApplicantId($this->user->id)
							                            ->where('created_at', '>=', DB::raw('NOW() - INTERVAL 3 MONTH'))
																					->orderBy('created_at', 'DESC')
																					->get();
		}

		$budgetCostsGroups = BudgetCostGroup::groupBy('name')->get();

		Session::put('statusType', 'my');
		
		return $this->setupLayout('budget.costsrequests.index')					
										->with('user', $this->user)
						        ->with('costsRequests', $costsRequests)
						        ->with('budgetCostsGroups', $budgetCostsGroups)
										->with('workProject', $this->workProject);
	}

	  // с "моей" подписью
	public function mySignRequests() {
    $input = Input::all();

		if (Session::get('statusType') && Input::has('projectId')) {
			return Redirect::to('budget/costsrequests/'.Session::get('statusType'));
		}
		
		if (!$this->user->budgetProjects->count()) {
			return Redirect::to('/');
		}
		if (!Auth::user()->hasRole(Role::ROLE_BUDGET_SIGN_COST_REQUEST)) {
			return Redirect::to('/');
		}
		if (Input::has('projectId')) {
			Session::put('work_projectId', $input['projectId']);
			return Redirect::to('budget/costsrequests');
		}

		if (Auth::user()->hasRole(Role::ROLE_BUDGET_SIGN_COST_REQUEST) && !Auth::user()->hasRole(Role::ROLE_BUDGET_CFO)) {
			$costsRequests = BudgetCostsRequests::whereProjectId($this->workProject->id)
							                            ->whereDirectorId($this->user->id)
																					->whereIspattern(0)
							                            ->where('created_at', '>=', DB::raw('NOW() - INTERVAL 3 MONTH'))
																					->orderBy('created_at', 'DESC')
																					->get();
		}

		$budgetCostsGroups = BudgetCostGroup::groupBy('name')->get();

		Session::put('statusType', 'mysign');
		
		return $this->setupLayout('budget.costsrequests.index')					
										->with('user', $this->user)
						        ->with('costsRequests', $costsRequests)
						        ->with('budgetCostsGroups', $budgetCostsGroups)
										->with('workProject', $this->workProject);
	}
	
	 // Шаблоны заявок
	public function patterns() {
    $input = Input::all();

		if (Session::get('statusType') && Input::has('projectId')) {
			return Redirect::to('budget/costsrequests/'.Session::get('statusType'));
		}
		
		if (!$this->user->budgetProjects->count()) {
			return Redirect::to('/');
		}
		if (Input::has('projectId')) {
			Session::put('work_projectId', $input['projectId']);
			return Redirect::to('budget/costsrequests');
		}

		$costsRequests = BudgetCostsRequests::whereProjectId($this->workProject->id)
																				->whereApplicantId($this->user->id)
																				->whereIspattern(1)
																				->orderBy('created_at', 'DESC')
																				->get();

		$budgetCostsGroups = BudgetCostGroup::groupBy('name')->get();

		Session::put('statusType', 'pattern');
		
		return $this->setupLayout('budget.costsrequests.index')					
										->with('user', $this->user)
						        ->with('costsRequests', $costsRequests)
						        ->with('budgetCostsGroups', $budgetCostsGroups)
										->with('workProject', $this->workProject);
	}
	
	// страница поиска
	public function costsRequestsSearch() {
    // ну костыль, ну убого, ну вот как-то так
		$input = Input::all();

    $sort_allowed = ['id', 'project_id', 'status', 'applicant_id', 'budget_cast_group_id', 'requested_amount', 'request_comment'];
    $sort_direction_allowed = ['asc', 'desc'];

    $orders = Input::only('orderBy', 'direction');

    $orders['direction'] = !is_null($orders['direction']) && in_array($orders['direction'], $sort_direction_allowed) ? $orders['direction'] : 'desc';
    $orders['orderBy'] = !is_null($orders['orderBy']) && in_array($orders['orderBy'], $sort_allowed) ? 'budget_costs_requests.'.$orders['orderBy'] : 'budget_costs_requests.id';
        
    
		$workProject = $this->workProject;
    $costsRequestsSql = '';  
        if ($this->user->budgetProjects->first() == null 
            || !$this->user->hasAnyRole(array(Role::ROLE_BUDGET_OUTCOMING_REQUEST, Role::ROLE_BUDGET_CFO, Role::ROLE_BUDGET_ACCOUNTANT, Role::ROLE_BUDGET_ACC_SECRETARY))
           ) {
            $workProject = $this->user->budgetProjects->first();
            Session::put($this->projectPrefix.'_work_projectId', $workProject->id);
			return Redirect::to("budget/");
		}
		if (!Auth::user()->hasAnyRole(array(Role::ROLE_BUDGET_OUTCOMING_REQUEST, Role::ROLE_BUDGET_CFO, Role::ROLE_BUDGET_ACCOUNTANT, Role::ROLE_BUDGET_ACC_SECRETARY))) {
			return Redirect::to('/');
		}
    $budgetCostsGroups = BudgetCostGroup::groupBy('name')->get();
		
		if ( isset($input['content']) && isset($input['type']) ){
			$content = trim($input['content']);
		  $type = $input['type'];
		
			if (is_numeric($content)){
				$amount = $content*100;
			} else {
				$amount = $content;
			}

      $beginDate = (isset($input['beginDate']) && $input['beginDate'] != '')? $input['beginDate'] : null;
      $endDate = (isset($input['endDate']) && $input['endDate'] != '')? $input['endDate'] : null;
          
			if( $content != '#all' & ($content || $beginDate || $endDate) ){ // для пустого ввода пока отключен поиск, иначе будет выводить всю таблицу
          // *************** Даты ************* //
          $dateRange = '';        
          if($beginDate || $endDate){
              
            $dateMin = 0;
            $dateMax = date('Y-m-d 23:59:59');
            if($beginDate){  
              $beginDate = explode('.', $beginDate);
              $dateMin = $beginDate[2].'-'.$beginDate[1].'-'.$beginDate[0].' 00:00:00';
            }
            if($endDate){
              $endDate = explode('.', $endDate);
              $dateMax = $endDate[2].'-'.$endDate[1].'-'.$endDate[0].' 23:59:59';
            }

              $rejectedCR = ' AND budget_costs_requests.status IN ('.BudgetCostsRequests::STATUS_REJECT_DIR.', '.BudgetCostsRequests::STATUS_CLOSED.', '.BudgetCostsRequests::STATUS_SIGN_REJECT.')';
              $notRejectedCR = ' AND budget_costs_requests.status NOT IN ('.BudgetCostsRequests::STATUS_REJECT_DIR.', '.BudgetCostsRequests::STATUS_CLOSED.', '.BudgetCostsRequests::STATUS_SIGN_REJECT.')';
              $dateRawArr = [
                  'все'=>" AND ( (budget_costs_requests.created_at > '".$dateMin."' AND budget_costs_requests.created_at < '".$dateMax."') OR
                            (budget_costs_requests.updated_at > '".$dateMin."' AND budget_costs_requests.updated_at < '".$dateMax."') OR
                            (budget_costs_requests.director_signed_at > '".$dateMin."' AND budget_costs_requests.director_signed_at < '".$dateMax."') OR
                            (budget_costs_requests.findirector_signed_at > '".$dateMin."' AND budget_costs_requests.findirector_signed_at < '".$dateMax."') OR
                            (budget_costs_requests.paid_at >= '".$beginDate[2].'-'.$beginDate[1].'-'.$beginDate[0]."' AND budget_costs_requests.paid_at <= '".$endDate[2].'-'.$endDate[1].'-'.$endDate[0]."')
                           )",
                  'создана'=>" AND (budget_costs_requests.created_at > '".$dateMin."' AND budget_costs_requests.created_at < '".$dateMax."')", 
                  'создано'=>" AND (budget_costs_requests.created_at > '".$dateMin."' AND budget_costs_requests.created_at < '".$dateMax."')", 
                  'созданы'=>" AND (budget_costs_requests.created_at > '".$dateMin."' AND budget_costs_requests.created_at < '".$dateMax."')", 
                  'обновлена'=>" AND (budget_costs_requests.updated_at > '".$dateMin."' AND budget_costs_requests.updated_at < '".$dateMax."')", 
                  'обновлено'=>" AND (budget_costs_requests.updated_at > '".$dateMin."' AND budget_costs_requests.updated_at < '".$dateMax."')",
                  'обновлены'=>" AND (budget_costs_requests.updated_at > '".$dateMin."' AND budget_costs_requests.updated_at < '".$dateMax."')",
                  'подписано'=>" AND (budget_costs_requests.director_signed_at > '".$dateMin."' AND budget_costs_requests.director_signed_at < '".$dateMax."')",
                  'подписаны'=>" AND (budget_costs_requests.director_signed_at > '".$dateMin."' AND budget_costs_requests.director_signed_at < '".$dateMax."')",
                  'подписанные'=>" AND (budget_costs_requests.director_signed_at > '".$dateMin."' AND budget_costs_requests.director_signed_at < '".$dateMax."')", 
                  'одобрено'=>$notRejectedCR." AND (budget_costs_requests.findirector_signed_at > '".$dateMin."' AND budget_costs_requests.findirector_signed_at < '".$dateMax."')",
                  'одобрены'=>$notRejectedCR." AND (budget_costs_requests.findirector_signed_at > '".$dateMin."' AND budget_costs_requests.findirector_signed_at < '".$dateMax."')",
                  'одобренные'=>$notRejectedCR." AND (budget_costs_requests.findirector_signed_at > '".$dateMin."' AND budget_costs_requests.findirector_signed_at < '".$dateMax."')", 
                  'отказано'=>$rejectedCR." AND (budget_costs_requests.findirector_signed_at > '".$dateMin."' AND budget_costs_requests.findirector_signed_at < '".$dateMax."')",
                  'отказаны'=>$rejectedCR." AND (budget_costs_requests.findirector_signed_at > '".$dateMin."' AND budget_costs_requests.findirector_signed_at < '".$dateMax."')",
                  'отказанные'=>$rejectedCR." AND (budget_costs_requests.findirector_signed_at > '".$dateMin."' AND budget_costs_requests.findirector_signed_at < '".$dateMax."')", 
                  'оплачена'=>" AND (budget_costs_requests.paid_at >= '".$beginDate[2].'-'.$beginDate[1].'-'.$beginDate[0]."' AND budget_costs_requests.paid_at <= '".$endDate[2].'-'.$endDate[1].'-'.$endDate[0]."')",
                  'оплачено'=>" AND (budget_costs_requests.paid_at >= '".$beginDate[2].'-'.$beginDate[1].'-'.$beginDate[0]."' AND budget_costs_requests.paid_at <= '".$endDate[2].'-'.$endDate[1].'-'.$endDate[0]."')",
                  'оплачены'=>" AND (budget_costs_requests.paid_at >= '".$beginDate[2].'-'.$beginDate[1].'-'.$beginDate[0]."' AND budget_costs_requests.paid_at <= '".$endDate[2].'-'.$endDate[1].'-'.$endDate[0]."')"
              ];
              $datetype = ( !isset($input['datetype']) || $input['datetype'] == null )? 'все': $input['datetype'];
              if( isset($dateRawArr[$datetype]) ){
                $dateRange = $dateRawArr[$datetype];      
              }
          }
          //***********************************//
          
				if($type == 'id' && is_numeric($content)){ // проверка на число нужна для того, чтобы не искать по int полю текст строгим равенством, т.к в таком случае вернет набор записей с нулевыми значениями выбранных полей
          $costsRequestsSql = BudgetCostsRequests::my()->whereRaw('( id = '.$content.' OR  parent_request_id = '.$content.')')
																							->orderBy('parent_request_id')
																							->orderBy($orders['orderBy'], $orders['direction'])
																							->withTrashed();
				}
				else if( $type == null || $type == 'all' || ($type == 'id' && !is_numeric($content)) ){
					$costsRequestsSql = BudgetCostsRequests::my()->select(DB::raw('budget_costs_requests.*,
																																u.first_name,
																																u.last_name,
																																u1.first_name,
																																u1.last_name,
																																budget_costs.name'))
																							->leftJoin('users as u', 'u.id', '=', 'budget_costs_requests.applicant_id')
																							->leftJoin('users as u1', 'u1.id', '=', 'budget_costs_requests.director_id')
																							->leftJoin('budget_costs', 'budget_costs_requests.budget_cost_group_id', '=', 'budget_costs.id')
																							->whereRaw('(budget_costs_requests.id LIKE "'.$content.'" OR
																													budget_costs_requests.parent_request_id LIKE "'.$content.'" OR
																													budget_costs_requests.requested_amount LIKE "%'.$amount.'%" OR
																													budget_costs_requests.requested_amount_old LIKE "%'.$amount.'%" OR
																													budget_costs_requests.request_comment LIKE "%'.$content.'%" OR
																													budget_costs_requests.director_comment LIKE "%'.$content.'%" OR
																													budget_costs_requests.findirector_comment LIKE "%'.$content.'%" OR
																													u.first_name LIKE "%'.$content.'%" OR
																													u.last_name LIKE "%'.$content.'%" OR
																													u1.first_name LIKE "%'.$content.'%" OR
																													u1.last_name LIKE "%'.$content.'%" OR
																													budget_costs.name LIKE "%'.$content.'%")'
                                                          .$dateRange
																												)
																							->orderBy($orders['orderBy'], $orders['direction'])
//																							->orderBy('project_id', 'DESC')
																							->withTrashed()
//																							->get();
																							/*->paginate(20)*/;
				}else{
          $costsRequests = array();
        }
			}else if($content == '#all'){
				$costsRequestsSql = BudgetCostsRequests::my()
																						->orderBy($orders['orderBy'], $orders['direction'])
//																						->orderBy('project_id', 'DESC')
																						->withTrashed()
//																						->get();
																						/*->paginate(20)*/;
			}
			else{
				$costsRequests = array();
			}
	  }	
		else{
			$costsRequests = array();
		}
    $costsRequestsSum = ($costsRequestsSql)? $costsRequestsSql->sum('requested_amount') : 0;
    $costsRequests = ($costsRequestsSql)? $costsRequestsSql->paginate(20) : array();
    
		Session::put('statusType', 'search');
    
		return $this->setupLayout('budget.costsrequests.search')		
										->with('orderBy', $orders['orderBy'])
                    ->with('direction', $orders['direction'])
										->with('costsRequests', $costsRequests)
										->with('user', Auth::user())
						        ->with('budgetCostsGroups', $budgetCostsGroups)
										->with('workProject', $workProject)
										->with('sum', round($costsRequestsSum/100, 2))
										->with('input', $input);
	}
	//-----------------------------------------------------------------------//
	
	/*public function testDeleteFile(){
		$input = Input::all();
			
		$files = BudgetCostsRequestsFiles::where(DB::raw('budget_cost_request_id IS NULL OR deleted_at IS NOT NULL OR created_at <= (NOW() - INTERVAL 3 MONTH)'))
						                          //->where('created_at', '<=', DB::raw('NOW() - INTERVAL 3 MONTH'))
						                          ->get();
		foreach ($files as $file){
			$fileNameArr = explode ('_', $file->name);
			$createdUserId = $fileNameArr[0];
		  File::delete('../public/costsrequests/uploadfile/'.$createdUserId.'/'.$file->name);
			$file->file_deleted_at = DB::raw('NOW()');
			$file->save();
		}	
		
		$response = array(
					'message' => 'ok'
				);
		return Response::json($response);
	}*/

	public function costsRequestsTest(){
	
		return $this->setupLayout('budget.costsrequests.test')					
										->with('user', $this->user)
										->with('workProject', $this->workProject);
	}
}