class ProductsController < ApplicationController

  skip_before_action :authenticate_user!, only: [ :index ]

  def index
    if params[:query].present?
      @products = Product.search_by_name_and_description(params[:query])
    else
      @products = Product.all
    end
  end

  def new
    @product = Product.new
  end

  def create
    @product = Product.new(product_params)
    @product.user = current_user
    if @product.save
      redirect_to products_path
    else
      render :new
    end
  end

  def destroy
    @product = Product.find(params[:id])
    @product.destroy
    flash[:notice] = "Your product '#{@product.name}' has been deleted."
    redirect_to products_path
  end

  def show
    @product = Product.find(params[:id])
    @reviews = Review.where(product: @product)
  end

  private

  def product_params
    params.require(:product).permit(:name, :description, :price, :category, :photos)
  end
end

