# -*- coding: utf-8 -*-
class Payment < ActiveRecord::Base
  belongs_to :period_zp
  has_one :period, :through => :period_zp
  belongs_to :employee
  belongs_to :author, :class_name => "Employee"

  before_save :set_period
  before_destroy :check_period_active
  validates_presence_of :operation_date, :message =>"Введите дату!"
  validates_presence_of :sum, :message =>"Введите сумму!"
  named_scope :over_period, lambda { |date_from, date_to| {  :conditions =>  "DATE(DATE_ADD(operation_date, INTERVAL #{Time.now.utc_offset} SECOND)) >= (DATE('#{date_from.to_date}')) AND DATE(DATE_ADD(operation_date, INTERVAL #{Time.now.utc_offset} SECOND)) <= (DATE('#{date_to.to_date}'))" }}

#  named_scope :over_period, lambda { |date_from, date_to| { :conditions => ['operation_date >= ? AND operation_date <= ?', date_from.to_time.utc, date_to.to_time.end_of_day.utc] } }
  named_scope :with_employee, lambda { |empl|  empl.present? ? { :conditions => ['employee_id = ?', empl] } : { }}
  named_scope :with_editor, lambda { |empl|  empl.present? ? { :conditions => ['author_id = ?', empl] } : { }}

  default_scope :order => 'operation_date'
  def save_with_check
    ActiveRecord::Base.transaction do
      self.save!
      pz = self.period_zp
      pz.payment_sum = pz.payment_sum.to_f + self.sum.to_f
      pz.save!
    end
  rescue Exception => e
    puts e.message
    return false
  end

  

  def set_period
    self.period_zp = PeriodZp.for_date_and_employee(self.operation_date, self.employee_id) unless self.period_zp
    unless self.period_zp
      errors.add_to_base "Период не найден или закрыт! Проверьте дату."
    end
  end
 

  def destroy_with_check
    ActiveRecord::Base.transaction do
      if self.period && self.period.closed == true
        errors.add_to_base "Период закрыт! Изменение невозможно." 
        raise  ActiveRecord::Rollback
      end
      pz = self.period_zp      
      pz.payment_sum = pz.payment_sum.to_f - self.sum.to_f
      self.destroy
      pz.save!
    end
  rescue Exception => e
    errors.add_to_base  e.message
    return false
  end

  private

  def check_period_active
   if self.period && self.period.closed == true
      errors.add_to_base "Период закрыт! Изменение невозможно."
    end
  end

end
