class Public::PProductsController < ApplicationController
  layout "public"
  skip_before_action :verify_authenticity_token, only: :show

  before_action :set_menu
  
  before_action :p_customer_validated

  def set_menu
    @boutique = true
  end

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


    @p_products = sort_by_sorting(@p_products)

    if params[:change_display_product_value].to_s == "true"
      session[:display_products] = true
    elsif params[:change_display_product_value].to_s == "false"
      session[:display_products] = false
    end

    params[:search] = params[:search] || {}

    
    @p_products = @p_products.where(:enabled => true)
    

    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

    
      @p_products = @p_products.joins(:p_product_p_customer_cats).where(:p_product_p_customer_cats => {:p_customer_cat_id => current_p_customer.p_customer_cat_id})





    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)

      }
      format.js{}
    end
  end

  def show
    if @p_product = PProduct.find(params[:id])
    else
      redirect_to "/"
    end
  end

end
