class PromotionsController < ApplicationController
  ##--- Abilities
  load_and_authorize_resource

  add_breadcrumb I18n.t("breadcrumbs." + controller_name), :promotions_path
  add_breadcrumb "Nueva " + I18n.t("breadcrumbs." + controller_name).singularize, :new_promotion_path, only: :new

  before_action :set_promotion, only: [:show, :destroy]

  # GET /promotions
  # GET /promotions.json
  def index
    @promotions = Promotion.all.order('id desc')
    @promotions.map(&:verify_promotion)
  end

  # GET /promotions/1
  # GET /promotions/1.json
  def show; end

  # GET /promotions/new
  def new
    @promotion = Promotion.new
    @promotion.percent = nil
  end

  # POST /promotions
  # POST /promotions.json
  def create
    @promotion = Promotion.new(promotion_params)
    @promotion.subcategory_id = nil if !@promotion.subcategory_id.nil? && @promotion.subcategory_id.zero?
    source =
      if @promotion.category_id.present? || @promotion.subcategory_id.present?
        "a la #{@promotion.subcategory_id.present? ? 'sublínea' : 'línea'} #{@promotion.subcategory_id.present? ? Category.find(@promotion.subcategory_id).category : @promotion.category.category}"
      elsif @promotion.product.present?
        "al producto #{@promotion.product.name}"
      end
    respond_to do |format|
      if @promotion.save
        message = "Promoción de descuento del #{@promotion.percent}% agregado #{source} del #{@promotion.start_date.strftime("%d/%m/%Y")} al #{@promotion.end_date.strftime("%d/%m/%Y")}"
        @promotion.audit_comment = message
        format.html { redirect_to promotions_path, notice: message }
        format.json { render :show, status: :created, location: @promotion }
      else
        @filter = params[:filter]
        format.html { render :new }
        format.json { render json: @promotion.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /promotions/1
  # DELETE /promotions/1.json
  def destroy
    message = "Descuento eliminado correctamente"
    @promotion.audit_comment = message
    @promotion.destroy
    respond_to do |format|
      format.html { redirect_to promotions_url, notice: message }
      format.json { head :no_content }
    end
  end

  private

  # Use callbacks to share common setup or constraints between actions.
  def set_promotion
    @promotion = Promotion.find(params[:id])
  end

  # Never trust parameters from the scary internet, only allow the white list through.
  def promotion_params
    params.require(:promotion).permit(:start_date, :end_date, :percent, :product_id, :category_id, :subcategory_id, :status)
  end
end
