class PProduct < ApplicationRecord
  has_many :p_product_p_normes, :dependent => :destroy
  has_many :p_product_specs, :through => :p_product_p_normes
  
  has_many :p_product_brut_products
  has_many :p_brut_products, :through => :p_product_brut_products
  
  belongs_to :p_product_cat
  
  accepts_nested_attributes_for :p_product_brut_products, allow_destroy: true
  
  attr_accessor :create_matiere
  
  def self.for_search(search)
    PProduct.where("name LIKE ? or code LIKE ?", "%#{search}%", "%#{search}%")
  end
  
  after_create do
    
    if self.create_matiere.to_s == "1"
      p_brut_product = PBrutProduct.create(:name => self.name)
      self.p_product_brut_products << PProductBrutProduct.create(:p_brut_product => p_brut_product, :qte => 1.0) 
      self.save
    end
  end
  
  def self.import_csv
    require 'csv'    

    csv_text = File.read("#{Rails.root}/csv_import/articles.csv")
    @csv = CSV.parse(csv_text, :headers => false, :col_sep => ";")
  
    @csv.each do |row|
      @p_product = PProduct.new(:create_matiere => true)
      @p_product.p_product_cat_id = row[0].to_i
      @p_product.code = row[1]
      @p_product.name = row[2]
      @p_product.conditionnement = row[3]
      @p_product.uv = row[4]
      @p_product.compte_achat = row[5]
      @p_product.compte_vente = row[6]
      @p_product.save
  
    end
    
  
  end
end
