class CommissionsController < ApplicationController
  ##--- Abilities
  load_and_authorize_resource

  ##--- Breadcrum_rails
  add_breadcrumb I18n.t("breadcrumbs." + controller_name), :commissions_path, only: :show

  before_action :set_commission, only: [:show, :edit, :update, :destroy]
  before_action :get_filters, only: [:index, :show, :edit, :new]

  # GET /commissions
  # GET /commissions.json
  def index
    @commissions = current_user.usertype == 'A' ? Commission.all.includes(:pointsale, :user).order('created_at desc') : Commission.includes(:pointsale, :user).where(pointsale_id: current_user.pointsale_id).order('created_at desc')
  end

  # GET /commissions/1
  # GET /commissions/1.json
  def show
    sellers_commissions_ids = SalesSellercommission.where('sellerscommission_id in (?)', @commission.sellerscommissions.pluck(:id)).pluck(:sale_id)
    @sales = Sale.where('sales.id in (?)', sellers_commissions_ids).joins(:seller).order('sellers.name')
  end

  # GET /commissions/new
  def new
    @sellers = Seller.where('id IN (?)', params[:sellers_ids])
    @initial_date = params[:initial_date]
    @final_date = params[:final_date]
    commission_total = 0
    @sellers.each do |seller|
      total = seller.get_sales_by_period(@initial_date, @final_date, 'commission').sum(:total)
      commission_total += total
    end
    @commission = Commission.new
    @commission.sellerscommissions.new
    @commission.commission_total = commission_total
    @commission.pointsale_id = params[:pointsale_id]
    @commission.initial_date = @initial_date
    @commission.final_date = @final_date
  end

  # GET /commissions/1/edit
  def edit; end

  # POST /commissions
  # POST /commissions.json
  def create
    @commission = Commission.new(commission_params)
    @commission.user_id = current_user.id
    respond_to do |format|
      @commission.audit_comment = "Comisiones del #{@commission.initial_date} al #{@commission.final_date} generadas"
      if @commission.save
        @commission.sellerscommissions.each do |seller_commission|
          sales_by_period = seller_commission.seller.get_sales_by_period(@commission.initial_date, @commission.final_date, 'commission').pluck(:id)
          sales_by_period.each do |sale|
            sales_sellercom = SalesSellercommission.new
            sales_sellercom.sellerscommission_id = seller_commission.id
            sales_sellercom.sale_id = sale
            sales_sellercom.save
          end
        end
        format.html { redirect_to commissions_path, notice: 'Pago de comisión registrado con éxito.' }
        format.json { render :show, status: :created, location: @commission }
      else
        format.html { render :new }
        format.json { render json: @commission.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /commissions/1
  # PATCH/PUT /commissions/1.json
  def update
    respond_to do |format|
      if @commission.update(commission_params)
        format.html { redirect_to @commission, notice: 'Commission was successfully updated.' }
        format.json { render :show, status: :ok, location: @commission }
      else
        format.html { render :edit }
        format.json { render json: @commission.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /commissions/1
  # DELETE /commissions/1.json
  def destroy
    @commission.destroy
    respond_to do |format|
      format.html { redirect_to commissions_url, notice: 'Commission was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  def sellers_for_commissions; end

  def generate_commissions; end

  def find_sellers_by_date
    initial_date = DateTime.parse(params[:initial_date])
    final_date = DateTime.parse(params[:final_date])
    exists_any = Commission.where("pointsale_id = ? AND ((initial_date BETWEEN ? AND ?) OR (final_date BETWEEN ? AND ?))", params[:pointsale_id], initial_date, final_date, initial_date, final_date).any?

    if exists_any
      render json: Array.new, status: :unprocessable_entity
    else
      ids_w_moves_in_period = Pointsale.find(params[:pointsale_id]).cash_registers_moves.where(move_type: '1', created_at: initial_date..final_date).pluck(:sale_id)
      news_sales_in_period = Pointsale.find(params[:pointsale_id]).sales.activas.where(date_sale: initial_date..final_date).pluck(:id)
      all_ids = (ids_w_moves_in_period + news_sales_in_period).uniq
      if all_ids.present?
        commissions_paid = SalesSellercommission.includes(:sale).where('sale_id IN (?) and sales.saletype = ?', all_ids, 1).pluck(:sale_id)
        to_pay = all_ids - commissions_paid
        sellers = Sale.where('sales.id IN (?)', to_pay).joins(:seller).distinct(:seller_id).select(:seller_id, :name)
      else
        sellers = Array.new
      end
      render json: sellers
    end
  end

  private

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

  def get_filters
    @current_page = params[:current_page].blank? ? 1 : params[:current_page]
    @filter = params[:filter]
  end

  # Never trust parameters from the scary internet, only allow the white list through.
  def commission_params
    params.require(:commission).permit(:initial_date, :final_date, :commission_total, :pointsale_id, :user_id, sellerscommissions_attributes: [:total_sold_cash, :total_sold_credits_apartments, :income_by_cash, :income_by_reserved_and_credits, :seller_id, :num_sales, :sales_total, :commission_calculated, :commission_paid, :commission_percent])
  end
end
