class Order < ActiveRecord::Base
  
  belongs_to :annonce_account
  belongs_to :credit_product
  belongs_to :commission
  belongs_to :devise
  has_many :hipay_histories
  
  validates :cgv, :presence => true
  validates :retractation, :presence => true
  
  
	scope :between, lambda { |start, stop|
	        after(start).before(stop)
	    }
	
	scope :after, lambda { |date|
	        where("(paid_at >= ?)", date )
	    }
	scope :before, lambda { |date|
	        where("(paid_at <= ?)", date )
	    }
  
  
  
  
  
  
  after_save do
    

    
  end
  
  def generate_bill
    if self.paid  and self.paid_at and self.payment_type_id == 2 and !self.bill_token
      
      self.bill_at = self.paid_at

      
      begin
        self[:bill_token] = SecureRandom.urlsafe_base64
      end while Order.exists?(:bill_token => self[:bill_token])
      
      
      @documents = Order.where("bill_token IS NOT NULL").where("bill_at <= ? and bill_at >= ?",self.bill_at.end_of_month, self.bill_at.beginning_of_month )
      @last = @documents.order("bill_id DESC").first
          if @last and @last.bill_id?
            @number = @last.bill_id.to_i + 1
        else
            @number = 1
          
        end
        
        self.bill_id = @number
      
      
      
      
      self.bill_number = "SP"+self.bill_at.strftime("%Y%m").to_s+('%05d' % self.bill_id)
      self.save
    end
    
    
  end
  
  def billing_address?
    if self.annonce_account.address? and self.annonce_account.cp? and self.annonce_account.city? and self.annonce_account.country?
      true
    else
      false
    end
  end
  
  def after_paid(soft=false)
    #ajout des crédits au compte
    
    #self.paid_at.to_date+(self.validity.to_i.months)
   
    self.annonce_account.credits.create(:cred => true, :value => self.nbr_credits, :expire_after => Date.parse("2016/12/31"), :operation_id => self.id, :operation_type => "Order", :note => "Commande de crédits")
    self.annonce_account.inscription_binaire
    
    if !soft
      #comission directe désactivée, remplacée par le mutliniveau
      if self.annonce_account.parent
      
        #self.annonce_account.parent.commissions.create(:order => self, :commission_type_id => 1, :amount => (self.price_ht.to_f() *0.1))
      
      end
    
      
      # binaire (commissions désactivé dans annonce_account commission_binary_now)
      if self.annonce_account.binary_parent
        self.credit_binary_parent(self.annonce_account.binary_parent, self.annonce_account)
      end
      
      
      # commissions multiniveau
      
      self.commission_mlm_now
      
      self.generate_bill
      self.save
      
    end
    
  end
  
  def commission_mlm_now
    if self.annonce_account.parent
      i = 0
      parent_to_commission = self.annonce_account.parent
      
      while parent_to_commission and i <= 12
        i += 1
        
        if parent_to_commission.mlm_nbr_niveaux >= i
          com_percent = (parent_to_commission.callif_now[4][i].to_f/100)
          com = ((parent_to_commission.callif_now[4][i].to_f/100)*self.price_ht.to_f()).round(2)
          puts "Commission à #{parent_to_commission.pseudo}: génération #{i}, #{com_percent}%, #{com}"
          
          parent_to_commission.commissions.create(:order => self, :commission_type_id => 10, :amount => com, :percent => com_percent, :generation => i, :devise => self.devise)
          
        end
        
        parent_to_commission = parent_to_commission.parent
        
        
      end
      
      
    end
  end
  
  def credit_binary_parent(parent, fileul)

  
    parent.binary_points.create(:value => self.binary_points, :side => fileul.binary_side, :fileul_id => fileul.id, :order => self, :point_type => 1)
    parent.commission_binary_now(self)
    
    
    if parent.binary_parent
      self.credit_binary_parent(parent.binary_parent, parent)
    end
    
    
  end
  
  def self.points_binaires_between(start, stop)
    Order.between(start, stop).where("unpaid is null").where("payment_type_id = 2").where(:paid => true).sum(:binary_points)
  end
  
  
  def self.points_binaires_mlm_between(start, stop)
    Order.between(start, stop).where("unpaid is null").where("payment_type_id = 2").where(:paid => true).includes(:annonce_account).where("annonce_accounts.parent_id IS NOT NULL").sum(:binary_points)
  end
  
  def self.points_binaires_direct_between(start, stop)
    Order.between(start, stop).where("unpaid is null").where("payment_type_id = 2").where(:paid => true).includes(:annonce_account).where("annonce_accounts.parent_id IS NULL").sum(:binary_points)
  end
  
  
  def self.com_part_between(start,stop)
    self.points_binaires_mlm_between(start, stop) * 0.20 + self.points_binaires_direct_between(start, stop) * 1.0
    
    
  end
  
  def evaluate_use_coms(force_eval=false)
    ttc = self.credit_product.price_ttc_final(self.annonce_account)
    
    if self.annonce_account.solde_commissions(self.devise_id) > 0.0 and (self.with_com or force_eval == true)
      if self.annonce_account.solde_commissions(self.devise_id) >= ttc
        self.credit_product.price_ttc_final(self.annonce_account)
      else
        self.annonce_account.solde_commissions(self.devise_id)
      end
      
    else
      0.0
    end
    
  end
  
  
  def evaluate_solde_coms(force_eval=false)
    self.annonce_account.solde_commissions(self.devise_id) - self.evaluate_use_coms(force_eval)
  end
  
  def evaluate_price_with_coms_ht(force_eval=false)
    
        if self.with_com or force_eval == true
          
          (self.evaluate_price_with_coms_ttc(force_eval) / 1.2).round(2)
    
        else
        
          self.credit_product.price_ht_final(self.annonce_account)
        end
    
  end
  
  def evaluate_price_with_coms_ttc(force_eval=false)
    self.credit_product.price_ttc_final(self.annonce_account) - self.evaluate_use_coms(force_eval)

    
  end
  
  
end
