# -*- coding: utf-8 -*-
class CfgController < ApplicationController # Категории работ
  	
  # Авторизация (файл: controllers/application.rb)
  before_filter :isAuthorization

  # Права доступа (файл: controllers/application.rb)
  around_filter :isAccessSuper
  around_filter :isAccessAdmin, :only => :delcfg

  # Конструктор
  before_filter :construct

  def construct
    if(session[:isAdmin]=='true')
      $department = Check.isText(params[:d])
    else
      $department = Check.isText(cookies[:sys_dep])
    end
  end


  
  def index
		if(session[:isAdmin]=='true')
    else
      if(session[:isSuperUser]=='true')
        redirect_to :action => "edit"
      else
        redirect_to :action => "error", :code=>1
      end
    end
  end


  def edit
    @result = CfgDB.find_by_sql("SELECT * FROM cfg WHERE department='"+$department.to_s+"' ORDER BY id ASC")
  end



	def addcfg
		@title=''
		@value=''
    @description = ''


		begin
			CfgDB.find(params[:id].to_i)
		rescue
			print 'Куда полез?'
		else
			# get data work
			@id = Check.intval(params[:id]).to_s
			@result = CfgDB.find_by_sql("SELECT * FROM cfg WHERE id="+@id+"")
			@title = @result[0]['name'].to_s
			@value = @result[0]['val'].to_s
			@description = @result[0]['description'].to_s
		end
		
	end

	def savecfg
		if(params[:id].to_i>0)
			id = Check.intval(params[:id]).to_i
			sv_work = CfgDB.find(id)
		else
			sv_work = CfgDB.new
		end
		# get
		sv_work.name = Check.isText(params[:title])
		sv_work.val = Check.isText(params[:value])
    sv_work.description = Check.isText(params[:description])   
		sv_work.department = Check.isText(params[:department])

		# save
		sv_work.save
		#redirect
		redirect_to :action => "edit", :d=>Check.isText(params[:department])
	end
	
	def delcfg
		if(params[:id].to_i>0)
			id = params[:id].to_i
			begin
				CfgDB.find(id)
			rescue	
				print 'Такого идентификатора - НЕТ.'
			else 	
				# delete
				CfgDB.delete(id)
				# redirect
				redirect_to :action => "index"
			end
		end
	end


end



