# -*- coding: utf-8 -*-
class CompaniesController < ApplicationController
  # Наши фирмы: заказчики и исполнители для категорий и отчетов
  before_filter :isAuthorization
  before_filter :check_access

  def index
    @companies = Company.all
  end

  def new
    @company = Company.new
  end


  def create
    @company = Company.new(params[:company])
    respond_to do |format|
      if @company.save   
        flash[:notice] = 'Компания  создана!'
        format.html { redirect_to companies_path }
      else
        flash[:error] = (@company.errors.each_full { |msg| puts msg }).to_s
        format.html { render :action => "new" }
      end
    end  
  end


  def edit
    @company = Company.find params[:id]
  end
  
  def update
    @company = Company.find params[:id]
   respond_to do |format|
      if @company.update_attributes(params[:company])
        flash[:notice] = 'Данные обновлены'
        format.html { redirect_to companies_path }
      else
        format.html { render :action => "edit" }
      end
    end
  end


  def destroy
    @company = Company.find params[:id]
    if @company.destroy
      flash[:notice] = 'Организация удалена'
    else
      flash[:error] =  (@company.errors.each_full { |msg| puts msg }).to_s
      end
    respond_to do |format|
      format.html { redirect_to(companies_path()) }
    end

  end



  private
  def check_access
    @current_user = Employee.find(session[:user_id])
    @departments = @current_user.accesses.select{|i| i.access_admin == 1 || i.access_delete == 1}.map{|i| i.department}
    if @departments.size == 0
      @errors = "В доступе отказано!"
      render(:partial => "/corp/errors")
    end
  end


end
