class ExpensesController < ApplicationController
  ##--- Abilities
  load_and_authorize_resource

  ##--- Breadcrum_rails
  add_breadcrumb I18n.t("breadcrumbs." + controller_name), :expenses_path
  add_breadcrumb "Nuevo egreso", :new_expense_path, only: :new
  add_breadcrumb "Detalle del egreso", :expense_path, only: :show
  add_breadcrumb "Editar egreso", :edit_expense_path, only: :edit

  before_action :set_expense, only: [:show, :edit, :update, :destroy]
  before_action :set_data, only: [:new, :create, :edit, :update]
  # GET /expenses
  # GET /expenses.json
  def index
    case current_user.usertype
    when "A"
      @from_pointsale = Expense.where.not(open_cash_register_id: nil).includes(:expensesconcept).order(" id DESC ")
      @general_expenses = Expense.where(open_cash_register_id: nil).includes(:expensesconcept).order(" id DESC ")
    when "G"
      @expenses = Pointsale.find(current_user.pointsale_id).expenses.includes(:expensesconcept, :open_cash_register).order("id DESC ")
    when "C"
      @expenses = Expense.where(open_cash_register_id: session[:open_cash_register_id]).includes(:expensesconcept).order("id DESC ")
    end
  end

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

  # GET /expenses/new
  def new
    @expense = Expense.new
    @concept_purchase_payment = Expensesconcept.find_by(expense_from_purchase: 1)
    if current_user.usertype == 'C'
      @is_cashier = true
      @expense.open_cash_register_id = session[:open_cash_register_id]
    end
  end

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

  # POST /expenses
  # POST /expenses.json
  # rubocop:disable Metrics/BlockLength
  def create
    respond_to do |format|
      @expense = Expense.new(expense_params)
      @concept_purchase_payment = Expensesconcept.find_by(expense_from_purchase: 1)
      @expense.status = :active

      if current_user.usertype == "A"
        @expense.skip_open_cash_validation = true
        @expense.skip_open_cash_has_money = true
      else
        @expense.expense_date = Date.current
      end

      @expense.audit_comment = "Egreso por #{@expense.quantity} registrado"
      if @expense.save
        # gasto pago a venta
        if @concept_purchase_payment.id == @expense.expensesconcept_id
          if params[:purchases].present?
            purchase = Purchase.find(params[:purchases])
            purchase.update_attributes(status: "paid")
          end
        end
        # movimiento de efectivo
        if current_user.usertype != "A"
          move = CashRegistersMove.new
          move.skip_received_validation = true
          move.expense_id = @expense.id
          move.open_cash_register_id = @expense.open_cash_register_id
          move.quantity = @expense.quantity
          move.move_type = :egreso
          move.concept = :expense
          move.payment_method_id = PaymentMethod.find_by(isCash: 1).id
          # si es pago a compra ponle el ID
          if purchase.present?
            move.purchase_id = purchase.id
          end
          move.save
        end
        format.html { redirect_to expenses_path, notice: 'El egreso fue creado correctamente.' }
        format.json { render :show, status: :created, location: @expense }
      else
        format.html { render :new }
        format.json { render json: @expense.errors, status: :unprocessable_entity }
      end
    end
  end
  # rubocop:enable Metrics/BlockLength

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

  # DELETE /expenses/1
  # DELETE /expenses/1.json
  def destroy
    respond_to do |format|
      if current_user.usertype == 'A'
        @expense.skip_open_cash_validation = true
      end

      @expense.audit_comment = "Egreso #{@expense.expense_code} cancelado."
      if @expense.update_attributes(status: 0)
        CashRegistersMove.where(expense_id: @expense.id).destroy_all
        format.html { redirect_to expenses_url, warning: 'El Gasto fue cancelado correctamente.' }
      else
        format.html { redirect_to expenses_url, warning: 'Error, intentar nuevamente.' }
      end
      format.json { head :no_content }
    end
  end

  private

  def set_data
    @is_cashier = false
    if current_user.usertype != "A"
      @expenses_concepts = Array.new
      Expensesconcept.where("status = 1 and allpoints = 'true'").each do |expense|
        @expenses_concepts << expense
      end

      Pointsale.find(current_user.pointsale_id).expensesconcepts.activos.each do |expense|
        @expenses_concepts << expense
      end
      @expenses_concepts.uniq!
    else
      @expenses_concepts = Expensesconcept.activos
    end
  end

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

  # Never trust parameters from the scary internet, only allow the white list through.
  def expense_params
    params.require(:expense).permit(:expensesconcept_id, :open_cash_register_id, :cash_registers_move_id, :quantity, :status, :purchases, :observations, :expense_date, :expense_code)
  end
end
