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

class Admin::PProductRefsController < ApplicationController
  layout "admin"
  before_action :auth_admin

  before_action :admin_space
  
  def admin_space
    @admin_space = "default"
  end
  
  def index
    @p_product_refs = PProductRef.order(:name).all

  end

  def show
    @p_product_ref = PProductRef.find(params[:id])

  end

  def new
    @p_product_ref = PProductRef.new
  
  end

  def edit
    @p_product_ref = PProductRef.find(params[:id])
    
  end

  def create
    @p_product_ref = PProductRef.new(params.require(:p_product_ref).permit!)

    if @p_product_ref.save
      
    else
      render action: "new"
 
    end

  end


  def update
    @p_product_ref = PProductRef.find(params[:id])


    if @p_product_ref.update_attributes(params.require(:p_product_ref).permit!)
      
    else
     render action: "edit" 
      
    end
      
  end


  def destroy
    @p_product_ref = PProductRef.find(params[:id])
    @p_product_ref.destroy
    
  end
  
  def autocomplete
    @p_product_refs = PProductRef.for_search(params[:search]).limit(50)
    
    if params[:p_customer_id]
      @p_customer = PCustomer.find(params[:p_customer_id])
      @p_product_refs = @p_product_refs.where("p_products.p_customer_id IS NULL or p_products.p_customer_id = ? ", @p_customer.id).joins(:p_customer_cats).where(:p_customer_cats => {:id => @p_customer.p_customer_cat_id})
    end
    
    @p_product_refs = @p_product_refs.where(:p_products => {:enabled => true})
    
    result = []
    
    @p_product_refs.all.each do |p_product_ref|
      result << {:member_label => "#{p_product_ref.p_product.code} | #{p_product_ref.p_product.name} - #{p_product_ref.uv} - #{p_product_ref.weight}Kg | #{p_product_ref.cat_name}", :id => p_product_ref.id }
    end
    
    respond_to do |format|
        format.json { render json: result}
    end
  end
  
  
  def get_infos
    @p_product_ref = PProductRef.find(params[:id])
    
    if params[:type] == "price"
      price = @p_product_ref.get_price(:p_customer_id => params[:p_customer_id], :qte => params[:qte])
      
      p_customer = PCustomer.find(params[:p_customer_id])
      accounting_zone_id = p_customer.accounting_zone_id
      tva_account_id = @p_product_ref.p_product.tva_rate(accounting_zone_id).id
      tva_account_value = @p_product_ref.p_product.tva_rate(accounting_zone_id).rate
      
      
      
      
      respond_to do |format|
          format.json { render json: {:weight => @p_product_ref.weight, :price => price, :tva_account_id => tva_account_id, :tva_account_value => tva_account_value} }
      end
    end
      
      
  end
  
  def autocomplete_apercu
    @p_product_ref = PProductRef.find(params[:id])
    
  end
  
end
