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

  def index
    if params[:filter_month]      
      month = params[:filter_month].to_s
      year = params[:filter_year].to_s
    else
      month = Date.today.month.to_s
      year = Date.today.year.to_s
    end
    @date = (month +'/01/' + year).to_date
  
    @salaries = Employee.find_by_sql("SELECT 68 div_id, 'Коммерческий монтаж' div_name, pos.name pos_name, pos.id position_id, s.sum as salary, s.static_sum static_sum, s.date_from as date_from FROM people e
LEFT JOIN positions pos ON pos.id = e.position_id 
LEFT JOIN salaries s ON s.id = (SELECT s2.id FROM salaries s2 WHERE e.position_id = s2.position_id AND s2.date_from <= DATE('#{@date}')  ORDER BY date_from DESC LIMIT 1) 
 GROUP BY e.position_id")
  end

  def update
    date = params[:date].to_date
    params[:salaries].each do |key, salary_attr|
      salary = Salary.find(:first, :conditions =>["division_id = ? AND position_id = ?", (salary_attr["div_id"]).to_i, salary_attr["position_id"]], :order =>'date_from')

      if salary && salary.date_from == date
        salary.update_attributes(:static_sum => salary_attr["static_sum"], :sum => salary_attr["salary"].to_f) if salary.sum != salary_attr["salary"].to_f || salary.static_sum != salary_attr["static_sum"]    
      elsif !salary || salary.sum != salary_attr["salary"].to_f #!= 0 && (!salary || salary.sum != salary_attr["salary"])
        Salary.create(:division_id => salary_attr["div_id"], :position_id => salary_attr["position_id"], :sum => salary_attr["salary"], :date_from => date, :static_sum => salary_attr["static_sum"]) if salary_attr["salary"] != ""
      end
    end
    redirect_to :action => :index, :date => @date
  end


  def working_days
    if params[:date]
      @date = params[:date].to_date
    else
      @date = Date.today
    end
    @working_days = WorkingDay.find_or_create_for_year(@date.year)
  end

  def change_working_days
    @working_days = WorkingDay.find(params[:working_day_ids])
    @working_days.each do |wd|
      weekends = params[:working_day][wd.id.to_s]["weekends"].split(", ").map!{|e| e.to_i}.compact.uniq.sort
      working_days =  Time.days_in_month(wd.month.month, wd.month.year) - weekends.count
      wd.update_attributes(:weekends => weekends.join(", "), :working_days => working_days)
    end
    redirect_to "/"
  end


  private
  

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

end
