class Public::ProductOrderProductsController < ApplicationController

	layout "public"
  before_filter :get_reseaux
	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] == ""
    @product = Product.find(params[:product_order_product][:product_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 @product.constraint_qty
      if @product.step_stop?
        max = @product.step_stop
      else
        max = 500
      end
      
      if @product.step_start?
        min = @product.step_start
      else
        min = 1
      end
      
      if @product.step_group?
        group = @product.step_group
      else
        group = 10
      end
    end

    # if the pop exists in the current cart, just increase the quantity
    if existing_product_order_product
      if group
        existing_product_order_product.qty += group
      elsif [1,2].include?(@product.id)
        existing_product_order_product.qty += 10
      else
        existing_product_order_product.qty += 1
      end
      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))
      
      if [1,2].include?(@product.id)
        @product_order_product.qty = 10
      else
        if min
          @product_order_product.qty = min
        else
          @product_order_product.qty = 1
        end
        
      end
      
      @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
