class Settings::ProductsController < ApplicationController
load_and_authorize_resource except: [:create]
  before_action :set_settings_product, only: [:show, :edit, :update, :destroy]
  before_action :check_user

  # GET /settings/products
  # GET /settings/products.json
  def index
    @settings_products = Product.all
  end

  # GET /settings/products/1
  # GET /settings/products/1.json
  def show
  end

  # GET /settings/products/new
  def new
    @settings_product = Product.new
  end

  # GET /settings/products/1/edit
  def edit
  end

  # POST /settings/products
  # POST /settings/products.json
  def create
    
    @settings_product = Product.new(settings_product_params)
    @settings_product.created_by = current_user.name
    respond_to do |format|
      if @settings_product.save
        format.html { redirect_to settings_products_path, notice: 'Product was successfully created.' }
        format.json { render :show, status: :created, location: @settings_product }
      else
        format.html { render :new }
        format.json { render json: @settings_product.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /settings/products/1
  # PATCH/PUT /settings/products/1.json
  def update
    respond_to do |format|
      if @settings_product.update(settings_product_params)
        format.html { redirect_to settings_product_path, notice: 'Product was successfully updated.' }
        format.json { render :show, status: :ok, location: @settings_product }
      else
        format.html { render :edit }
        format.json { render json: @settings_product.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /settings/products/1
  # DELETE /settings/products/1.json
  def destroy
    @settings_product.destroy
    flash[:notice] = 'Product was successfully destroyed.'
    render :json => {:status=> "Success", :url => settings_products_path }.to_json
    # respond_to do |format|
    #   format.html { redirect_to settings_products_path, notice: 'Product was successfully destroyed.' }
    #   format.json { head :no_content }
    # end
  end

  def check_user
    if current_user.nil?
      redirect_to root_path
    end
  end
  
  private
    # Use callbacks to share common setup or constraints between actions.
    def set_settings_product
      @settings_product = Product.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def settings_product_params
      params.require(:product).permit(:item_code, :name, :alt_name, :unit_price, :image_path, :description, :information, :taxable,:created_by)
    end

end
