class ProductOrder < ActiveRecord::Base
  has_many :product_order_products

  has_many :product_order_payments
  belongs_to :product_order_payment_ok, :class_name => "ProductOrderPayment"

  belongs_to :particular_bill, :class_name => "Particular"

  accepts_nested_attributes_for :particular_bill

  belongs_to :particular_send, :class_name => "Particular"

  accepts_nested_attributes_for :particular_send

  belongs_to :product_customer

  accepts_nested_attributes_for :product_customer
  
  belongs_to :product_fdp
  belongs_to :product_fdp_archived, :class_name => "ProductFdp"
  
  belongs_to :vourcher_code
  belongs_to :vourcher_code_archived, :class_name => "VourcherCode"
  
  validates :product_fdp, :presence => true, :if => :force_fdp_validation?
  
  validates :cgv, :presence => {:message => "Vous devez accepter les conditions générales de vente."}, :if => :force_cgv_validation?
  
  attr_accessor :force_fdp_validation, :force_payment, :force_cgv_validation
  
  
  
  def prodons_country
    countr = particular_bill.country
    if countr.to_s == "FR"
      
    else
      c = ISO3166::Country.new countr
      c.translation('fr')
    end
  end
  
  
  def prodons_date
    if self.paid_at?
      date = self.paid_at
    else
      date = self.created_at
    end
    
    date.strftime("%d/%m/%Y")
      
  end
  
  
  
  def verify_paid_status
    
    product_order_payments_to_count = self.product_order_payments.where("paid_at IS NOT NULL").order("paid_at DESC")
    amount_paid = product_order_payments_to_count.sum(:amount)
    
    if product_order_payments_to_count.first and amount_paid >= self.total_ttc
      self.paid = true
      self.paid_at = product_order_payments_to_count.first.paid_at
    else
      self.paid = nil
      self.paid_at = nil
      
      
    end
    self.save
    
  end
  
  
  def total_ttc
    total_articles + total_fdp - vourcher_reduction
  end
  
  def total_ttc_without_fdp
    total_articles - vourcher_reduction
  end
  
  def vourcher_reduction
    if self.vourcher_code and 1==1
      (total_articles * (self.vourcher_code.percent / 100 )).round(2)
      
    else
      0.0
    end
  end
  
  
  def archived_vourcher_reduction
    if self.vourcher_code_archived and 1==1
      (total_articles * (self.vourcher_code_archived.percent / 100 )).round(2)
      
    else
      0.0
    end
  end
  
  
  
  def archived_total_ttc
    archived_total_articles + archived_total_fdp - archived_vourcher_reduction
  end
  
  
  def archived_total_articles
    archived_total = 0.0
    product_order_products.each do |p|
      archived_total += p.archived_final_price_ttc_with_qty
    end
    archived_total
  end
  
  def archived_total_fdp(fdp=self.product_fdp_archived)
    if fdp
      if self.archived_total_articles < fdp.price_max
        fdp.price
      else
        0.0
      end
    else
      0.0
    end
    
  end
  
  def generate_bill_number

    
    if !self.bill_number and self.paid and self.product_order_payment_type_ok_id == 3
      self.paid_at = self.product_order_payment_ok.paid_at
      
      self.bill_year = self.paid_at.year
      

      
      
      last_number = 0
      last_number = ProductOrder.where("paid_at is not null").where(:bill_year => self.bill_year ).order("bill_index DESC").first.bill_index if ProductOrder.where("paid_at is not null").where(:bill_year => self.bill_year ).first
      self.bill_index = last_number+1
      self.bill_number = "WEB"+self.bill_year.to_s+('%04d' % self.bill_index)
      self.save(:validate => false)
    
    end
  end
  
  def after_paid
    
    self.product_order_products.each do |p|
    
      p.update_stock_th
      
    end
    
    self.generate_bill_number
    
  end
  
  def after_ship
    if !self.shiped
      self.product_order_products.each do |p|
    
        p.update_stock
      
      end
    
      self.shiped = true
      self.shiped_at = Time.now
      self.save
    end
  end
  
  def archive_now
		self.product_order_products.each do |p|
      
      # Archive the product
      p.archived_product = p.product.dup
      p.archived_product.archived = true
      p.verify_qty
      p.save

      # Archive product langs

      p.product.product_langs.each do |pl|
        dup_pl = pl.dup
        dup_pl.archived = true
        p.archived_product.product_langs << dup_pl
        p.save
      end

      # Archive the pop size
      
      if p.product_size
        dup_product_size = p.product_size.dup
        dup_product_size.archived = true
        p.archived_product_size  = dup_product_size 
      end
      
      if p.product_option# Archive the pop option
      
        dup_product_option = p.product_option.dup
        dup_product_option.product_id = nil
        dup_product_option.archived = true
        p.archived_product_option  = dup_product_option 

        p.product_option.product_option_langs.each do |pl|
          p.archived_product_option.product_option_langs << pl.dup
          p.save
        end
		  end
      
      

      # save
      p.save


    end
    
    if self.product_fdp
      a_product_fdp = self.product_fdp.dup
      a_product_fdp.archived = true
      a_product_fdp.save
      self.product_fdp_archived_id = a_product_fdp.id
      self.save
      
    end
    
    if self.vourcher_code
      a_vourcher_code = self.vourcher_code.dup
      a_vourcher_code.archived = true
      a_vourcher_code.save
      self.vourcher_code_archived_id = a_vourcher_code.id
      self.save
      
    end
    
  end
  
  def total_articles
    total = 0.0
    product_order_products.each do |p|
      total += p.final_price_ttc_with_qty
    end
    total
  end
  
  def total_fdp(fdp=self.product_fdp)
    if fdp
      if self.total_ttc_without_fdp < fdp.price_max
        fdp.price
      else
        0.0
      end
    else
      0.0
    end
    
  end
  
  def force_fdp_validation?
    true if self.force_fdp_validation
  end
  
  def force_cgv_validation?
    true if self.force_cgv_validation
  end
  
  before_validation do
     self.verify
       
  end
  
  
  protected
  
  	def verify(size=16)
  		if !self.token
  			s = ""
  			size.times { s << (i = Kernel.rand(62); i += ((i < 10) ? 48 : ((i < 36) ? 55 : 61 ))).chr }
  			self.token = s
	    end
	  end
  
  
  
end
