<?php

class BudgetCostsController extends BaseController {

	protected $rules		 = array(
			'name' => 'required|max:50',
	);
	protected $messages	 = array(
			'required' => 'Неообходимо ввести статью расходов'
	);

	/**
	 * Constructor
	 */
	public function __construct() {
		// Establish Filters
		$this->beforeFilter('auth');
		$this->beforeFilter('hasRole:' . Role::ROLE_BUDGET_REFRENCE);

		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() {
		$input = Input::all();

		if ($this->user->projects->first() == null) {
			return Redirect::to("budget/costs");
		}
		if (Input::has('projectId')) {
			Session::put('work_projectId', $input['projectId']);
			return Redirect::to('budget/costs');
		}
    $budgetCosts = BudgetCost::whereIn('project_id', array($this->workProject->id, 0))->with('budgetCostGroup')->orderBy('name')->get();
		return $this->setupLayout('budget.costs.index')
										->with('input', $input)
										->with('user', $this->user)
										->with("budgetCosts", $budgetCosts)
										->with('workProject', $this->workProject);
	}

	/**
	 * Show the form for creating a new resource.
	 *
	 * @return Response
	 */
	public function create() {
		$budgetCostGroups = array(0 => 'Нет');
		foreach (BudgetCostGroup::whereProjectId($this->workProject->id)->orderBy('name')->get() as $budgetCostGroup) {
		  $budgetCostGroups[$budgetCostGroup->id] = $budgetCostGroup->name;
		}
		return $this->setupLayout('budget.costs.create')
										->with('user', $this->user)
						        ->with('budgetCostGroups', $budgetCostGroups)
										->with('workProject', $this->workProject);
	}

	/**
	 * Store a newly created resource in storage.
	 *
	 * @return Response
	 */
	public function store() {
		$input			 = Input::all();
		$validation	 = Validator::make($input, $this->rules, $this->messages);

		if ($validation->fails()) {
			return Redirect::action('BudgetCostsController@create')
											->withInput()
											->withErrors($validation->errors());
		}
		else {
			$budgetCostGroup = BudgetCostGroup::whereProjectId($this->workProject->id)->find($input['budget_cost_group_id']);
			if ($budgetCostGroup == null || !is_numeric($input['budget_cost_group_id'])) {
				$budgetCostGroupId = 0;
			}else{
				$budgetCostGroupId =$budgetCostGroup->id;
			}
			$input								  = Input::all();
			$budgetCost						  = BudgetCost::create(array(
				'budget_cost_group_id'=> $budgetCostGroupId,
				'name'		            => e($input['name']),
				'managed'	            => e($input['managed']),
				'template'            => e($input['template'])
			));
			$budgetCost->project()->associate($this->workProject);
			$budgetCost->plan_amount = $input['plan_amount'];
			$budgetCost->save();

			return Redirect::to('budget/costs');
		}
	}

	/**
	 * Show the form for editing the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id) {
		$budgetCost = BudgetCost::find($id);
		if ($budgetCost == null || !is_numeric($id) || $budgetCost->project_id != $this->workProject->id || !$this->workProject->isMy()) {
			return Redirect::to("budget/costs");
		}

		$budgetCostGroups = array(0 => 'Нет');
		foreach (BudgetCostGroup::whereProjectId($this->workProject->id)->orderBy('name')->get() as $budgetCostGroup) {
			$budgetCostGroups[$budgetCostGroup->id] = $budgetCostGroup->name;
		}
		return $this->setupLayout('budget.costs.edit')
										->with('budgetCost', $budgetCost)
										->with('budgetCostGroups', $budgetCostGroups)
										->with('user', $this->user)
										->with('workProject', $this->workProject);
	}

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

		if ($validation->fails()) {
			return Redirect::action('BudgetCostsController@edit', $id)
											->withInput()
											->withErrors($validation->errors());
		}
		else {
			$budgetCost = BudgetCost::find($id);
			if ($budgetCost == null || !is_numeric($id) || $budgetCost->project_id != $this->workProject->id || !$this->workProject->isMy()) {
				return \App::abort(404);
			}
      $budgetCostGroup = BudgetCostGroup::whereProjectId($this->workProject->id)->find($input['budget_cost_group_id']);
			if ($budgetCostGroup == null || !is_numeric($input['budget_cost_group_id'])) {
				$budgetCostGroupId = 0;
			}else{
				$budgetCostGroupId =$budgetCostGroup->id;
			}
			$budgetCost->budget_cost_group_id = $budgetCostGroupId;
			$budgetCost->name				          = e($input['name']);
			$budgetCost->managed		          = e($input['managed']);
			$budgetCost->template		          = e($input['template']);
			$budgetCost->plan_amount          = e($input['plan_amount']);
			$budgetCost->save();

			return Redirect::to('budget/costs');
		}
	}

	/**
	 * Remove the specified resource from storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id) {
		$budgetCost = BudgetCost::find($id);
		if ($budgetCost == null || !is_numeric($id) || $budgetCost->project_id != $this->workProject->id || !$this->workProject->isMy()) {
			$response = array(
					'status' => 'fail'
			);
			return Response::json($response);
		}

		BudgetOperation::whereBudgetCostId($id)->update(array('budget_cost_id' => 0));
		BudgetCost::destroy($id);

		$response = array(
				'status' => 'success'
		);
		return Response::json($response);
	}

}
