<?php

class BudgetSalaryController extends BaseController {

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

		/*if ($this->user && $this->user->hasAnyRole(array(Role::ROLE_BUDGET, Role::ROLE_BUDGET_ACCOUNTANT))) {
			$this->beforeFilter('hasRole:' . Role::ROLE_BUDGET);
			$this->beforeFilter('hasRole:' . Role::ROLE_BUDGET_ACCOUNTANT);
		}*/
		
		if (Auth::check()) {
			$this->user	    = Auth::user();
			$this->projects = $this->user->budgetProjects;
		}
		$this->projectPrefix = 'budget';
        parent::__construct();
	}

	/**
	 * Display a listing of the resource.
	 *
	 * @return Response
	 */
	public function index() {
		return Redirect::to('budget/salary/stat');
	}

	public function stat() {
		$input = Input::all();
        $workProject = $this->workProject;
        
		if ($this->user->budgetProjects->first() == null 
            || !$this->user->hasAnyRole(array(Role::ROLE_BUDGET, Role::ROLE_BUDGET_ACCOUNTANT, Role::ROLE_BUDGET_SALARY_MANAGMENT))
            || !$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/salary/stat');
		}

		$salaryUsers      = $workProject->salaryUsers()->orderBy('last_name')->get();
		$salaryUsersCount = $workProject->salaryUsers()->count();
		
		return $this->setupLayout('budget.salary.stat.index')
						   ->with('input', $input)
						   ->with('salaryUsers', $salaryUsers)
						   ->with('salaryUsersCount', $salaryUsersCount)
					     ->with('workProject', $workProject);
	}
    
	public function allstat() {
		$input = Input::all();

		//if ($this->user->projects->first() == null || !$this->user->hasAnyRole(array(Role::ROLE_BUDGET, Role::ROLE_BUDGET_ACCOUNTANT, Role::ROLE_BUDGET_SALARY_MANAGMENT))) {
		if ( $this->user->projects->first() == null || !Auth::user()->isAdmin() ) {
			return Redirect::to("budget/");
		}

		if (Input::has('projectId')) {
			Session::put('work_projectId', $input['projectId']);
			return Redirect::to('budget/salary/stat');
		}

		$workProject      = $this->workProject;
		$salaryUsers      = $workProject->getAllowSalaryUsers();
		$salaryUsersCount = $workProject->countAllowSalaryUsers();
		
		return $this->setupLayout('budget.salary.stat.all')
						   ->with('input', $input)
						   ->with('salaryUsers', $salaryUsers)
						   ->with('salaryUsersCount', $salaryUsersCount)
					     ->with('workProject', $workProject);
	}
	
	public function salaryOperations() {
		$input = Input::all();
		$workProject = $this->workProject;
        
		if ($this->user->budgetProjects->first() == null 
            || !$this->user->hasAnyRole(array(Role::ROLE_BUDGET, Role::ROLE_BUDGET_ACCOUNTANT, Role::ROLE_BUDGET_SALARY_MANAGMENT))
            || !$this->user->hasProject($workProject->id)
           ) {
            $workProject = $this->user->budgetProjects->first();
            Session::put($this->projectPrefix.'_work_projectId', $workProject->id);
			return Redirect::to("budget/");
		}
		
		$startDate = Session::get('budget_operation_startDate');
		if (!$startDate) {
			$startDate = date("d.m.Y", time() - 3600 * 24);
		}
		$endDate = Session::get('budget_operation_endDate');
		if (!$endDate) {
			$endDate = date('d.m.Y');
		}
		if (Input::has('startDate')) {
			$startDate = $input['startDate'];
			Session::put('budget_operation_startDate', $input['startDate']);
		}
		$date					 = explode('.', $startDate);
		$startDateRaw	 = "{$date[2]}-{$date[1]}-{$date[0]}";
		if (Input::has('endDate')) {
			$endDate = $input['endDate'];
			Session::put('budget_operation_endDate', $input['endDate']);
		}
		$date				 = explode('.', $endDate);
		$endDateRaw	 = "{$date[2]}-{$date[1]}-{$date[0]}";
		
		$salaryUsers = $workProject->salaryUsers()->orderBy('last_name')->get();
		
		$salaryOperations = BudgetSalary::select(DB::raw('budget_salary.*,
																								 u.first_name as first_name,
																								 u.last_name as last_name,
																								 p.name as project_name,
																								 bo.date as bo_date,
																								 bo.amount as bo_amount'))
						                         ->leftJoin('users as u', 'u.id', '=', 'budget_salary.salary_user_id')
																     ->leftJoin('budget_operations as bo', 'bo.id', '=', 'budget_salary.budget_operation_id')
																     ->leftJoin('projects as p', 'p.id', '=', 'budget_salary.project_id')
						                         ->where('budget_salary.salary_date', '>=', $startDateRaw)
						                         ->where('budget_salary.salary_date', '<=', $endDateRaw)
						                         ->where('budget_salary.project_id', '=', $workProject->id)
						                         ->orderBy('budget_salary.budget_operation_id')
																		 ->orderBy('budget_salary.created_at', 'DESC')
						                         ->get();
		
		Session::put('salaryUserId', 'all');
		
		return $this->setupLayout('budget.salary.stat.operation')
								->with('salaryUsers', $salaryUsers)
						    ->with('startDate', $startDate)
							  ->with('endDate', $endDate)
						    ->with('salaryOperations', $salaryOperations);
	}
	
	public function userSalaryOperations($id) {
		$input = Input::all();
		$workProject = $this->workProject;
        
        if ($this->user->budgetProjects->first() == null 
            || !$this->user->hasAnyRole(array(Role::ROLE_BUDGET, Role::ROLE_BUDGET_ACCOUNTANT, Role::ROLE_BUDGET_SALARY_MANAGMENT))
            || !$this->user->hasProject($workProject->id)
           ) {
            $workProject = $this->user->budgetProjects->first();
            Session::put($this->projectPrefix.'_work_projectId', $workProject->id);
			return Redirect::to("budget/");
		}
        
		$user = User::find($id);
		if ( $user == null || !is_numeric($id) ) {
			return \App::abort(404);
		}
		
		if ($this->user->projects->first() == null || !$this->user->hasAnyRole(array(Role::ROLE_BUDGET, Role::ROLE_BUDGET_ACCOUNTANT))) {
			return Redirect::to("budget/salary");
		}
		
		$startDate = Session::get('budget_operation_startDate');
		if (!$startDate) {
			$startDate = date("d.m.Y", time() - 3600 * 24);
		}
		$endDate = Session::get('budget_operation_endDate');
		if (!$endDate) {
			$endDate = date('d.m.Y');
		}
		if (Input::has('startDate')) {
			$startDate = $input['startDate'];
			Session::put('budget_operation_startDate', $input['startDate']);
		}
		$date					 = explode('.', $startDate);
		$startDateRaw	 = "{$date[2]}-{$date[1]}-{$date[0]}";
		if (Input::has('endDate')) {
			$endDate = $input['endDate'];
			Session::put('budget_operation_endDate', $input['endDate']);
		}
		$date				 = explode('.', $endDate);
		$endDateRaw	 = "{$date[2]}-{$date[1]}-{$date[0]}";
		
		$salaryUsers = $workProject->salaryUsers()->orderBy('last_name')->get();
		
		$salaryOperations = BudgetSalary::select(DB::raw('budget_salary.*,
																								 u.first_name as first_name,
																								 u.last_name as last_name,
																								 p.name as project_name,
																								 bo.date as bo_date,
																								 bo.amount as bo_amount'))
						                         ->leftJoin('users as u', 'u.id', '=', 'budget_salary.salary_user_id')
																		 ->leftJoin('budget_operations as bo', 'bo.id', '=', 'budget_salary.budget_operation_id')
																     ->leftJoin('projects as p', 'p.id', '=', 'budget_salary.project_id')
						                         ->where('budget_salary.salary_date', '>=', $startDateRaw)
						                         ->where('budget_salary.salary_date', '<=', $endDateRaw)
						                         ->where('budget_salary.salary_user_id', '=', $user->id)
						                         ->where('budget_salary.project_id', '=', $workProject->id)
						                         ->orderBy('budget_salary.budget_operation_id')
						                         ->orderBy('budget_salary.created_at', 'DESC')
						                         ->get();
		
		Session::put('salaryUserId', $user->id);
		
		return $this->setupLayout('budget.salary.stat.operation')
								->with('salaryUsers', $salaryUsers)
						    ->with('startDate', $startDate)
							  ->with('endDate', $endDate)
						    ->with('salaryOperations', $salaryOperations);
	}

	// таблица общая статистика по з/п
	public function export() {
        $workProject = $this->workProject;
        
        if ($this->user->budgetProjects->first() == null 
            || !$this->user->hasAnyRole(array(Role::ROLE_BUDGET, Role::ROLE_BUDGET_ACCOUNTANT, Role::ROLE_BUDGET_SALARY_MANAGMENT))
            || !$this->user->hasProject($workProject->id)
           ) {
            $workProject = $this->user->budgetProjects->first();
            Session::put($this->projectPrefix.'_work_projectId', $workProject->id);
			return Redirect::to("budget/");
		}
        
		$fileName = "SalaryAndPlanStat-{$workProject->id}__" . date('d-m-Y');
		Excel::create($fileName, function($excel) {
			$excel->sheet('Зп и планы продаж', function($sheet) {
				$workProject      = $this->workProject;
		    $salaryUsers      = $workProject->salaryUsers()->orderBy('last_name')->get();
		    $salaryUsersCount = $workProject->salaryUsers()->count();
				$input = Input::all();
				$monthRange = $input['monthRange'];
				$reportTitle = 'З/п и планы продаж сотрудников проекта ';
		
				if ($workProject) {
					$sheet->loadView('budget.export.salarystat')
									->with('workProject', $workProject)
									->with('salaryUsers', $salaryUsers)
									->with('salaryUsersCount', $salaryUsersCount)
									->with('reportTitle', $reportTitle)
									->with('monthRange', $monthRange);
				}
			});
		})->store('xlsx');

		return Response::download('../app/storage/exports/' . $fileName . '.xlsx');
	}
	
	// окно планов продаж
	public function getUsersSalesPlans() {
		
		$workProject = $this->workProject;
        
        if ($this->user->budgetProjects->first() == null 
            || !$this->user->hasAnyRole(array(Role::ROLE_BUDGET, Role::ROLE_BUDGET_ACCOUNTANT, Role::ROLE_BUDGET_SALARY_MANAGMENT))
            || !$this->user->hasProject($workProject->id)
           ) {
            $workProject = $this->user->budgetProjects->first();
            Session::put($this->projectPrefix.'_work_projectId', $workProject->id);
			return Redirect::to("budget/");
		}
		$userSalesPlans = UsersSalaryProject::select(DB::raw('uspl.*,
																													u.id as u_id,
																													u.first_name as u_first_name,
																													u.last_name as u_last_name'))
																				->leftJoin('users as u', 'u.id', '=', 'users_salary_projects.user_id')
																				->leftJoin('users_sales_plan as uspl', function($join){
																					  $input = Input::all();
		                                        $planDate = $input['planDate'];
																						$join->on('uspl.salary_user_id', '=', 'u.id')
																								 ->where('uspl.plan_date', '=', $planDate);
																					})
																				->where('users_salary_projects.project_id', '=', $workProject->id)
																				->whereNull('u.deleted_at')
																				->whereNull('uspl.deleted_at')
																				->orderBy('last_name')
																				->withTrashed()
																				->get();
		$response = array(
				'status'		     => 'success',
				'userSalesPlans' => $userSalesPlans				
		);
		return Response::json($response);
	}
	
	// сохранение планов продаж сотрудников
	public function updateUsersSalesPlans() {
		$input = Input::all();

		$workProjectId   = $this->workProject->id;
		$usersPlanDate   = $input['users-plan-date'];
		$usersid         = $input['usersid'];
		$comments        = $input['comment'];
		$execSalaryPlans = $input['execSalaryPlan'];
		
		foreach ($usersid as $key => $val){
	    $userSalesPlan = UserSalesPlan::whereProjectId($workProjectId)
																		 ->whereSalaryUserId($usersid[$key])
																		 ->wherePlanDate($usersPlanDate)
																		 ->first();
			if($execSalaryPlans[$key] != 0 || $comments[$key] != null || $userSalesPlan != null){
				$execSalaryPlans[$key] = trim($execSalaryPlans[$key]);
				$execSalaryPlans[$key] = str_replace( ',', '.', $execSalaryPlans[$key] );

				if( !is_numeric($execSalaryPlans[$key]) && $execSalaryPlans[$key] != null ){
					$message		 = 'План продаж должен быть числом';
					$error_field = 'message-box-sum-'.$key;

					$response = array(
							'status'				 => 'fail',
							'error_message'	 => $message,
							'error_field'		 => $error_field
					);
					return Response::json($response);
				}else{
					if ($userSalesPlan == null) {
						$userSalesPlan = UserSalesPlan::create(array(
								'project_id'         => $workProjectId,
								'salary_user_id'     => $usersid[$key],
								'plan_date'          => $usersPlanDate
						));
					}
					$userSalesPlan->exec_amount = $execSalaryPlans[$key]*100;
					$userSalesPlan->comment = $comments[$key];
					$userSalesPlan->last_edite_user_id = Auth::user()->id;
					$userSalesPlan->save();
				}
		  }
		}
		
		$response = array(
				'status' => 'success'
			);
		return Response::json($response);
	}
	
	//---------------------- кнопки заявок на расход  ----------------------------------------//
	public function salaryCR() { // все з/п заявки на расход
		$input = Input::all();

		$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/salary/costsrequests');
		}

		$costsRequests = BudgetCostsRequests::my()
						                                ->whereProjectId($workProject->id)
						                                ->whereIn( 'budget_cost_group_id', $workProject->salaryCosts() )
						                                ->whereIspattern(0)
																						->where('created_at', '>=', DB::raw('NOW() - INTERVAL 3 MONTH'))
																						->orderBy('project_id', 'DESC')
																						->withTrashed()
																						->get();
		
//			$costsRequests = BudgetCostsRequests::/*whereProjectId($this->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)
//																					->whereIn( 'budget_cost_group_id', $this->workProject->salaryCosts() )
							                            //->where('created_at', '>=', DB::raw('NOW() - INTERVAL 3 MONTH'))
//																					->orderBy('created_at', 'DESC')
//																					->get();

		$budgetCostsGroups = BudgetCostGroup::groupBy('name')->get();
		
		return $this->setupLayout('budget.salary.costsrequests.index')						
										->with('user', $this->user)
						        ->with('costsRequests', $costsRequests)
						        ->with('budgetCostsGroups', $budgetCostsGroups)
										->with('workProject', $workProject);
	}

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

		if (Session::get('statusType') && Input::has('projectId')) {
			return Redirect::to('budget/salary/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/salary/costsrequests');
		}
		
		// во вкладке "На подпись" все с правом подписи, кроме фин директора будут видеть и новые, и подписанные ими заявки (для информации)
		// для фин. директора подписанные убраны из этой вкладки во избежание путаницы, т.к. эти заявки у него будут еще в "Новых"
    if (!Auth::user()->hasRole( Role::ROLE_BUDGET_CFO)) {
			$costsRequests = BudgetCostsRequests::whereProjectId($this->workProject->id)
																					->whereIn('status', array(BudgetCostsRequests::STATUS_SIGNED, BudgetCostsRequests::STATUS_WORK))
							                            ->whereIspattern(0)
																					->whereDirectorId($this->user->id)
																					->whereIn( 'budget_cost_group_id', $this->workProject->salaryCosts() )
																					->where('created_at', '>=', DB::raw('NOW() - INTERVAL 3 MONTH'))
																					->orderBy('created_at', 'DESC')
																					->get();
		}
		else{
			$costsRequests = BudgetCostsRequests::whereProjectId($this->workProject->id)
																					->whereIn('status', array(BudgetCostsRequests::STATUS_BACK_OFF, BudgetCostsRequests::STATUS_WORK))
																					->whereIspattern(0)
																					->whereDirectorId($this->user->id)
																					->whereIn( 'budget_cost_group_id', $this->workProject->salaryCosts() )
																					->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.salary.costsrequests.index')
										->with('user', $this->user)
						        ->with('costsRequests', $costsRequests)
						        ->with('budgetCostsGroups', $budgetCostsGroups)
										->with('workProject', $this->workProject);
	}
	
    // Новые
	public function newSalaryCR() {
    $input = Input::all();

		if (Session::get('statusType') && Input::has('projectId')) {
			return Redirect::to('budget/salary/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/salary/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( 'budget_cost_group_id', $workProject->salaryCosts() )
							                            ->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($this->workProject->id)
							                            ->whereStatus(BudgetCostsRequests::STATUS_SIGNED)
																					->whereIspattern(0)
																					->whereIn( 'budget_cost_group_id', $this->workProject->salaryCosts() )
																					->orderBy('director_signed_at', 'DESC')
																					->get();
		}

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

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

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

		if (Session::get('statusType') && Input::has('projectId')) {
			return Redirect::to('budget/salary/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/salary/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)
																						->whereIn( 'budget_cost_group_id', $workProject->salaryCosts() )
																						->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)
																						->whereIn( 'budget_cost_group_id', $this->workProject->salaryCosts() )
																						->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)
																					->whereIn( 'budget_cost_group_id', $this->workProject->salaryCosts() )
							                            ->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)
																					->whereIn( 'budget_cost_group_id', $this->workProject->salaryCosts() )
																					->whereIspattern(0)
																					->orderBy('created_at', 'DESC')
																					->get();
		}

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

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

	  // Отказано
	public function rejectedSalaryCR() {
    $input = Input::all();
		
		if (Session::get('statusType') && Input::has('projectId')) {
			return Redirect::to('budget/salary/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/salary/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))
																						->whereIn( 'budget_cost_group_id', $workProject->salaryCosts() )
																						->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))
																						->whereIn( 'budget_cost_group_id', $workProject->salaryCosts() )
																						->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.') )  )')
																					->whereIn( 'budget_cost_group_id', $workProject->salaryCosts() )
																					->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.salary.costsrequests.index')						
										->with('user', $this->user)
						        ->with('costsRequests', $costsRequests)
						        ->with('budgetCostsGroups', $budgetCostsGroups)
										->with('workProject', $workProject);
	}

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

		if (Session::get('statusType') && Input::has('projectId')) {
			return Redirect::to('budget/salary/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/salary/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)
																						->whereIn( 'budget_cost_group_id', $workProject->salaryCosts() )
																						->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)
																						->whereIn( 'budget_cost_group_id', $workProject->salaryCosts() )
																						->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)
																					->whereIn( 'budget_cost_group_id', $workProject->salaryCosts() )
							                            ->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)
																					->whereIn( 'budget_cost_group_id', $workProject->salaryCosts() )
							                            ->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.salary.costsrequests.index')
										->with('user', $this->user)
						        ->with('costsRequests', $costsRequests)
						        ->with('budgetCostsGroups', $budgetCostsGroups)
										->with('workProject', $workProject);
	}

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

		if (Session::get('statusType') && Input::has('projectId')) {
			return Redirect::to('budget/salary/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/salary/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)
							                            ->whereIn( 'budget_cost_group_id', $this->workProject->salaryCosts() )
							                            ->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.salary.costsrequests.index')					
										->with('user', $this->user)
						        ->with('costsRequests', $costsRequests)
						        ->with('budgetCostsGroups', $budgetCostsGroups)
										->with('workProject', $this->workProject);
	}

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

		if (Session::get('statusType') && Input::has('projectId')) {
			return Redirect::to('budget/salary/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/salary/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)
																					->whereIn( 'budget_cost_group_id', $this->workProject->salaryCosts() )
																					->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.salary.costsrequests.index')					
										->with('user', $this->user)
						        ->with('costsRequests', $costsRequests)
						        ->with('budgetCostsGroups', $budgetCostsGroups)
										->with('workProject', $this->workProject);
	}
	
	 // Шаблоны заявок
	public function salaryPatterns() {
    $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.salary.costsrequests.index')
										->with('user', $this->user)
						        ->with('costsRequests', $costsRequests)
						        ->with('budgetCostsGroups', $budgetCostsGroups)
										->with('workProject', $this->workProject);
	}
	
	// страница поиска
	public function salaryCRSearch() {
		$input = Input::all();
		
		if (Session::get('statusType') && Input::has('projectId')) {
			return Redirect::to('budget/salary/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/");
		}
    $budgetCostsGroups = BudgetCostGroup::groupBy('name')->get();
		
		if ( isset($input['content']) && isset($input['type']) ){
			$content = $input['content'];
		  $type = $input['type'];
		
			if (is_numeric($content)){
				$amount = $content*100;
			} else {
				$amount = $content;
			}

			if($content && $content != '#all'){ // для пустого ввода пока отключен поиск, иначе будет выводить всю таблицу
				if($type == 'id' && is_numeric($content)){ // проверка на число нужна для того, чтобы не искать по int полю текст строгим равенством, т.к в таком случае вернет набор записей с нулевыми значениями выбранных полей
					$costsRequests = BudgetCostsRequests::my()
																							->whereIn( 'budget_cost_group_id', $workProject->salaryCosts() )
																							->whereRaw('( id = '.$content.' OR  parent_request_id = '.$content.')')
																							->orderBy('parent_request_id')
																							->orderBy('project_id', 'DESC')
																							->withTrashed()
																							->get();
				}
				else if( ($type == 'all') || ($type == 'id' && !is_numeric($content)) ){
					$costsRequests = 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')
																							->whereIn( 'budget_costs_requests.budget_cost_group_id', $workProject->salaryCosts() )
																							->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.'%")'
																												)
																							->orderBy('project_id', 'DESC')
																							->withTrashed()
																							->get();
				}
				else{
					$costsRequests = array();
				}
			}else if($content == '#all'){
				$costsRequests = BudgetCostsRequests::my()
																						->whereIn( 'budget_cost_group_id', $workProject->salaryCosts() )
																						->orderBy('project_id', 'DESC')
																						->withTrashed()
																						->get();
			}
			else{
				$costsRequests = array();
			}
	  }	
		else{
			$costsRequests = array();
		}
		Session::put('statusType', 'search');
		
		return $this->setupLayout('budget.salary.costsrequests.index')		
										->with('costsRequests', $costsRequests)
										->with('user', Auth::user())
						        ->with('budgetCostsGroups', $budgetCostsGroups)
										->with('workProject', $workProject);
	}
}