<?php

class BudgetDebtPartnersController extends BaseController {

	protected $rules		 = array(
			'name' => 'required_without:debet_project_id|max:50',
			'debet_project_id' => 'required_without:name|integer'
	);
	protected $messages	 = array(
			'name.required_without' => 'Неообходимо ввести название долгового контрагента',
			'debet_project_id.required_without' => 'Неообходимо выбрать долгового контрагента'
	);

	/**
	 * 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/debtpartners');
		}
        
        $budgetDebtPartners = $this->workProject->budgetDebtPartners;

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

	/**
	 * Show the form for creating a new resource.
	 *
	 * @return Response
	 */
	public function create() {
		return $this->setupLayout('budget.debtpartners.create')
										->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('BudgetDebtPartnersController@create')
											->withInput()
											->withErrors($validation->errors());
		}
		else {
			$where = '';
			if($input['debet_project_id']){
			$projectById = Project::find($input['debet_project_id']);
            if ($projectById == null) {
                return Redirect::to("budget/debtpartners");
            }
            
            $debetProjectId = $projectById->id;

			$where = ' AND debet_project_id = '.$debetProjectId;
			}
            $projectByName = '';
            if(trim(e($input['name'])) != null){
			  $where = " AND name = '".trim(e($input['name']))."'";
              $projectByName = Project::whereName(trim(e($input['name'])))->first(); // чтобы не создавали с одинаковыми названиями
            } 
            
			$budgetDebtPartner = BudgetDebtPartner::whereRaw('project_id = '.$this->workProject->id.$where)->first();
			if($budgetDebtPartner == null && $projectByName == null){
                $budgetDebtPartner = BudgetDebtPartner::create(array(
                                        'debet_project_id' => isset($debetProjectId)? $debetProjectId : null,
                                        'name'             => trim(e($input['name']))
                ));
                $budgetDebtPartner->project()->associate($this->workProject);
                $budgetDebtPartner->save();
                // создание зеркального контрагента
                if( isset($input['dual-deb-partner']) ){
                  $budgetDebtPartner = BudgetDebtPartner::whereRaw('project_id = '.$debetProjectId.' AND debet_project_id = '.$this->workProject->id)
                                                        ->first();
                  if($budgetDebtPartner == null){
                    $budgetDebtPartner = BudgetDebtPartner::create(array(
                                        'project_id'       => $debetProjectId,
                                        'debet_project_id' => $this->workProject->id
                    ));
                  }
                }
                return Redirect::to('budget/debtpartners');
            }else{
              return Redirect::action('BudgetDebtPartnersController@create')
											->withInput()
											->withErrors(array('partner-exist' => 'Такой долговой контрагент уже существует в данном проекте'));
            }
		}
	}

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

		return $this->setupLayout('budget.debtpartners.edit')
										->with('budgetDebtPartner', $budgetDebtPartner)
										->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('BudgetDebtPartnersController@edit', $id)
											->withInput()
											->withErrors($validation->errors());
		}
		else {
			$budgetDebtPartner = BudgetDebtPartner::find($id);
			if ($budgetDebtPartner == null || !is_numeric($id) || $budgetDebtPartner->project_id != $this->workProject->id || !$this->workProject->isMy()) {
				return Redirect::to("budget/debtpartners");
			}

			$budgetDebtPartner->name						 = e($input['name']);
			$budgetDebtPartner->save();

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

	/**
	 * Remove the specified resource from storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id) {
		$budgetDebtPartner = BudgetDebtPartner::find($id);
		if ($budgetDebtPartner == null || !is_numeric($id) || $budgetDebtPartner->project_id != $this->workProject->id || !$this->workProject->isMy()) {
			return \App::abort(404);
		}

		BudgetDebtPartner::destroy($id);

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

}
