# -*- encoding : utf-8 -*-

class Admin::PProductsController < ApplicationController
  layout "admin"
  before_action :auth_admin
  
  before_action :admin_space
  
  def import2
    if true #params[:force]
      require "csv"
      csv_text = File.read("#{Rails.root}/import_csv/export articles precision.csv", :encoding => 'UTF-8')
      @csv = CSV.parse(csv_text, :headers => true, :col_sep => ";")
      
      
    end
  
  end
  
  def import
    if false #params[:force]
      require "csv"
      csv_text = File.read("#{Rails.root}/import_csv/export articles.csv", :encoding => 'UTF-8')
      @csv = CSV.parse(csv_text, :headers => true, :col_sep => ";")
      
      PProduct.destroy_all
      
      @csv.each do |row|
        
        p_product = PProduct.new(:enabled => true, :imported => true)
        p_product.code = row["CodeArticle"]
        if row["restauration"].to_s == "oui"
          p_product.p_customer_cats = PCustomerCat.where(:id => [2,3])
        else
          p_product.p_customer_cats = PCustomerCat.where(:id => [1,3])
        end
          
        p_product.note = row["commentaire"] if row["commentaire"].to_s != "0" and row["commentaire"].to_s != "" 
          
        if row["Article Actif"] == "non"
          p_product.enabled = false
        end
        p_product.sub_code = row["CodeArticle2"]
        p_product.name = row["Libelle interne"]
        p_product.ct_purchase_price_ht = row["Prix achat HT 2020"].to_s.sub(",",".").to_f
        p_product.a_code_tva = row["CodeTvaVente"]
        if p_product_cat = PProductCat.where(:name => row["Famille_lib"]).first
        
        else
          p_product_cat = PProductCat.create(:name => row["Famille_lib"])
        end
        p_product.p_product_cat_id = p_product_cat.id
       
        p_product_ref = PProductRef.new
        
        p_product_ref.ct_price_ht = row["Prix de vente HT 2020"].to_s.sub(",",".").to_f
        #p_product_ref.uv = 
        p_product_ref.weight = row["kg colis"].to_s.sub(",",".").to_f if row["PoidsUnitaire"].to_s != "0"
        
        
        ss_famille_1 = PProductSubCat.where(:parent_id => nil, :name => row["Sous-famille_lib"]).first
        
        if ss_famille_1
          if ss_famille_1
            p_product.p_product_sub_cats << ss_famille_1
          
            if row["ss-famille_n2_lib"].to_s != ""
              ss_famille_2 = PProductSubCat.where(:parent_id => ss_famille_1.id, :name => row["ss-famille_n2_lib"]).first
          
              if ss_famille_2
                p_product.p_product_sub_cats << ss_famille_2
              
                if row["ss-famille_n3_lib"].to_s != ""
                  ss_famille_3 = PProductSubCat.where(:parent_id => ss_famille_2.id, :name => row["ss-famille_n3_lib"]).first
          
                  p_product.p_product_sub_cats << ss_famille_3 if ss_famille_3
                end
                
              
              end
            end
          end
        end
        
        
        p_product.p_product_refs << p_product_ref
        
        if p_product.save
          #puts p_customer.save
        else
          puts p_product.errors.messages.to_s
          sdffsd = sfdfd
        
        end
      
      end
      
      render :inline  => "ok"
      
    end 
  end
  
  
  def admin_space
    @admin_space = "stocks"
  end
  

  def index
    @p_products = PProduct.includes(:p_product_cat).includes(:s_brand).includes(:p_product_refs)
    

    @p_products = sort_by_sorting(@p_products)
    
    
    params[:search] = params[:search] || {}
    
    params[:search][:enabled] = "Oui" if !params[:search][:enabled]
    
    if params[:search][:enabled].to_s == "Oui"
      @p_products = @p_products.where(:enabled => true)
    elsif params[:search][:enabled].to_s == "Non"
      @p_products = @p_products.where(:enabled => false)
    end
    
    if params[:search][:p_product_cat_id].to_s != ""
      @p_products = @p_products.where(:p_product_cat_id => params[:search][:p_product_cat_id])
    end
    
    if params[:search][:s_brand_id].to_s != ""
      @p_products = @p_products.where(:s_brand_id => params[:search][:s_brand_id])
    end
    
    if params[:search][:p_customer_cat_id].to_s != ""
      @p_products = @p_products.joins(:p_product_p_customer_cats).where(:p_product_p_customer_cats => {:p_customer_cat_id => params[:search][:p_customer_cat_id]})
    end
    
    
    
     
    if params[:code].to_s != ""
      @p_products = @p_products.where("p_products.code LIKE ?","%#{params[:code]}%")
    end
    
    if params[:name].to_s != ""
      @p_products = @p_products.where("p_products.name LIKE ?","%#{params[:name]}%")
    end
   
    respond_to do |format|
      format.html{
      
        params[:search][:per_page] = params[:search][:per_page] || 50
    		per_page = params[:search][:per_page]
    		page = (params[:page] and params[:page] != "") ? params[:page] : 1 
    		@p_products = @p_products.page(page).per(per_page)
      
      }
    end
   
  end

  def show
    @p_product = PProduct.find(params[:id])

  end

  def new
    
    
		@p_product = PProduct.new(:p_customer_cat_ids => [3])
    
    @p_product.p_product_refs << PProductRef.new

  end

 

  def edit
  
    
    @p_product = PProduct.find(params[:id])
  end

  def create
    
    if params[:p_product][:create_matiere] == "1"
      
      params[:p_product].delete(:p_product_brut_products_attributes)

    end
    @p_product = PProduct.new(params.require(:p_product).permit!)


    if @p_product.save
      @p_products = PProduct.joins(:p_product_cat).order("p_product_cats.name ASC, p_products.name ASC").all
      
      
      redirect_to admin_p_products_path()
    else
      render action: "new"
 
    end

  end


  def update
    @p_product = PProduct.find(params[:id])


    if @p_product.update_attributes(params.require(:p_product).permit!)
      
      @p_products = PProduct.joins(:p_product_cat).order("p_product_cats.name ASC, p_products.name ASC").all
      
      redirect_to admin_p_products_path()
      
    else
     render action: "edit" 
      
    end
      
  end


  def destroy
    @p_product = PProduct.find(params[:id])
    @p_product.destroy
    
  end
  
  def autocomplete
    @p_products = PProduct.for_search(params[:search]).limit(50)
    
    
    
    
    respond_to do |format|
        format.json { render json: @p_products }
    end
  end
  
  def autocomplete_apercu
    @p_product = PProduct.find(params[:id])
    
  end
  
  
end
