# -*- coding: utf-8 -*-
class PricelistController < ApplicationController
  layout "pricelist"
  before_filter :isAuthorization
  before_filter :set_var
  around_filter :isAccessSuper

  def index
    @sections = Section.all
    @pl_items = Pricelist.with_section(params[:section_id]).active_hidden(params[:active_hidden]).with_legal_entity(params[:legal_entity_id]).find(:all, :order =>"section_id, pl_items.ordered")
    if params[:category].to_i != 0
      @pl_items = @pl_items.select{|i| i.pricelist_divisions.select{|i| i.category.to_s.split(',').include? params[:category].to_s}.size > 0}
    end
  end



  def new
    @item = Pricelist.new(:price => 0)
    @item.pricelist_divisions.build(:division_id => 68)
    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @item }
    end
  end

  # GET /pl_items/1/edit
  def edit
    @item = Pricelist.find(params[:id])
  end

  # POST /pl_items
  # POST /pl_items.xml
  def create
    @item = Pricelist.new(params[:pricelist])
    @item.usr = Employee.current_user
    respond_to do |format|
      if @item.save
        format.html { redirect_to(pricelist_index_path(:section_id => params[:section_id], :active_hidden =>params[:active_hidden]), :notice => 'Запись сохранена.') }
      else
        format.html { render :action => "new" }
      end
    end
  end

  # PUT /pricelist/1
  # PUT /pricelist/1.xml
  def update
    @item = Pricelist.find(params[:id])
    respond_to do |format|
      if @item.update_attributes(params[:pricelist])
        format.html { redirect_to(pricelist_index_path(:section_id => params[:section_id], :active_hidden =>params[:active_hidden]), :notice => 'Запись сохранена.') }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
      end
    end
  end

  # DELETE /pricelist/1
  # DELETE /pricelist/1.xml
  def destroy
    @item = Pricelist.find(params[:id])
    @item.destroy

    respond_to do |format|
      format.html { redirect_to(pricelist_index_path) }
    end
  end

  private
  
  def set_var
    Employee.current_user = Employee.find(session[:user_id]) unless session[:user_id].nil?
  end


end
