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

class Admin::PProductsController < ApplicationController
  layout "admin"
  before_action :auth_admin
  
  before_action :admin_space
  
  def admin_space
    @admin_space = "ventes"
  end
  

  def index
    @p_products = PProduct.joins(:p_product_cat).order("p_product_cats.name ASC, p_products.name ASC")
    
    if params[:archived]
      @p_products = @p_products.where(:enabled => false)
    else
      @p_products = @p_products.where(:enabled => true)
    end
    
   
  end

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

  end

  def new
    
    
		@p_product = PProduct.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
      
    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
       
    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
