class Public::ProductOrderProductsController < ApplicationController

	layout "public"

	def create
    #clear params
    params[:product_order_product][:product_size_id] = nil if params[:product_order_product][:product_size_id] == ""
    params[:product_order_product][:product_option_id] = nil if params[:product_order_product][:product_option_id] == ""
    
    # Trying to retreive an existing pop in the current cart
    existing_product_order_product = @product_order.product_order_products.where(:product_id => params[:product_order_product][:product_id], :product_size_id => params[:product_order_product][:product_size_id], :product_option_id => params[:product_order_product][:product_option_id]).first

    # if the pop exists in the current cart, just increase the quantity
    if existing_product_order_product
      existing_product_order_product.qty += 1
      existing_product_order_product.verify_qty
      existing_product_order_product.save
    else

      @product_order_product = ProductOrderProduct.new(params.require(:product_order_product).permit(:product_id, :product_size_id, :product_option_id))
      
      @product_order_product.qty = 1
      
      @product_order_product.save
      
      #@product_order_product.save
      @product_order.product_order_products << @product_order_product
      #@product_order_product.verify_qty
      @product_order_product.save
    end

    # Make back a redirection
    
    
    respond_to do |format|
      format.js
      format.html{
        
        redirect_to :back
        
      }
    end
    
    
	end


  def delete

  end

  def update

    @product_order_product = ProductOrderProduct.find(params[:id])
    @product_order_product.qty = params[:product_order_product][:qty]
    
    @product_order_product.verify_qty
    
    @product_order_product.save
    
    if @product_order_product.qty == 0
      @product_order_product.destroy
      
    end
    
    # Make back a redirection
    redirect_to :back

  end


end
