<?php

class BudgetAccountsController 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('/');
		}
		if (Input::has('projectId')) {
			Session::put('work_projectId', $input['projectId']);
			return Redirect::to('budget/accounts');
		}

		return $this->setupLayout('budget.accounts.index')
										->with('input', $input)
										->with('user', $this->user)
										->with("budgetAccounts", $this->workProject->budgetAccounts)
										->with('workProject', $this->workProject);
	}

	/**
	 * Show the form for creating a new resource.
	 *
	 * @return Response
	 */
	public function create() {
		$budgetCostsGroups = BudgetCost::whereIn('project_id', array($this->workProject->id, 0))
																                    ->with('budgetCostGroup')
							                                      ->orderBy('name')
																                    ->groupBy('budget_cost_group_id')->get();

		return $this->setupLayout('budget.accounts.create')
										->with('budgetCostsGroups', $budgetCostsGroups)
										->with('user', $this->user)
										->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('BudgetAccountsController@create')
											->withInput()
											->withErrors($validation->errors());
		}
		else {
			$input				 = Input::all();
			$budgetCost		 = BudgetCost::find($input['cost_id']);
			$budgetAccount = BudgetAccount::create(array(
									'name'						 => e($input['name']),
									'current_account'	 => e($input['current_account']),
									'isrobokassa'			 => e((isset($input['isrobokassa']) ? 1 : 0)),
									'iscache'					 => e((isset($input['iscache']) ? 1 : 0)),
									'isbuffer'				 => e((isset($input['isbuffer']) ? 1 : 0)),
									'noupload'				 => e((isset($input['noupload']) ? 1 : 0))
			));
			$budgetAccount->project()->associate($this->workProject);
			if ($budgetCost) {
				$budgetAccount->cost()->associate($budgetCost);
			}
			$budgetAccount->save();

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

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

		$budgetCostsGroups = BudgetCost::whereIn('project_id', array($this->workProject->id, 0))
																                    ->with('budgetCostGroup')
							                                      ->orderBy('name')
																                    ->groupBy('budget_cost_group_id')->get();

		return $this->setupLayout('budget.accounts.edit')
										->with('budgetCostsGroups', $budgetCostsGroups)
										->with('budgetAccount', $budgetAccount)
										->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('BudgetAccountsController@edit', $id)
											->withInput()
											->withErrors($validation->errors());
		}
		else {
			$budgetAccount = BudgetAccount::find($id);
			$budgetCost		 = BudgetCost::find($input['cost_id']);
			if ($budgetAccount == null || !is_numeric($id) || $budgetAccount->project_id != $this->workProject->id || !$this->workProject->isMy()) {
				return \App::abort(404);
			}

			$budgetAccount->name						 = e($input['name']);
			$budgetAccount->current_account	 = e($input['current_account']);
			$budgetAccount->isrobokassa			 = (isset($input['isrobokassa']) ? 1 : 0);
			$budgetAccount->iscache					 = (isset($input['iscache']) ? 1 : 0);
			$budgetAccount->isbuffer				 = (isset($input['isbuffer']) ? 1 : 0);
			$budgetAccount->noupload				 = (isset($input['noupload']) ? 1 : 0);
			if ($budgetCost) {
				$budgetAccount->cost()->associate($budgetCost);
			}elseif( isset($input['cost_id']) && $input['cost_id'] == 0 ){
				$budgetAccount->cost_id				 = 0;
			}
			$budgetAccount->save();

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

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

		BudgetAccount::destroy($id);

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

}
