class PointsalesController < ApplicationController
  ##--- Abilities
  load_and_authorize_resource

  ##--- Breadcrum_rails
  add_breadcrumb I18n.t("breadcrumbs." + controller_name), :pointsales_path
  add_breadcrumb "Nuevo Punto de venta", :new_pointsale_path, only: :new
  add_breadcrumb "Detalle del Punto de venta", :pointsale_path, only: :show

  before_action :set_pointsale, only: [:show, :edit, :update, :destroy, :update_products]
  before_action :get_filters, only: [:index, :show, :edit, :new]
  # before_action :get_available_products, only: [:edit, :update]

  # GET /pointsales
  # GET /pointsales.json
  def index
    @pointsales = Pointsale.vigentes
  end

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

  # GET /pointsales/new
  def new
    @pointsale = Pointsale.new
  end

  # GET /pointsales/1/edit
  def edit
    @todo = params[:todo]
    add_breadcrumb (@todo.present? ? "Actualizar productos del punto de venta " : "Editar Punto de venta"), :edit_pointsale_path, only: :edit
    respond_to do |format|
      format.html
      format.json { render json: AvailableProductsDatatable.new(view_context, @pointsale) }
    end
  end

  # POST /pointsales
  # POST /pointsales.json
  def create
    @pointsale = Pointsale.new(pointsale_params)
    @pointsale.skip_name_validation = false
    @pointsale.skip_products_validation = false
    @pointsale.users.first.skip_validations_from_pointsale = true
    @pointsale.audit_comment = "El punto de venta " + @pointsale.name + " fue creado."
    @pointsale.users.first.usertype = 'G'
    @pointsale.users.first.status = 1
    @pointsale.prefix.upcase!
    respond_to do |format|
      if @pointsale.save
        @pointsale.users.first.pointsale_id = @pointsale.id
        main_cash_register = CashRegister.new
        main_cash_register.name = @pointsale.name + " Principal"
        main_cash_register.description = "Caja registradora principal"
        main_cash_register.pointsale_id = @pointsale.id
        main_cash_register.main = 'yes'
        main_cash_register.status = 'active'
        main_cash_register.save

        format.html { redirect_to pointsales_url, success: "El punto de venta " + @pointsale.name + " fue creado." }
        format.json { render :show, status: :created, location: @pointsale }
      else
        format.html { render :new }
        format.json { render json: @pointsale.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /pointsales/1
  # PATCH/PUT /pointsales/1.json
  def update
    respond_to do |format|
      if @pointsale.update(pointsale_params)
        @pointsale.audit_comment = "El punto de venta #{@pointsale.name} fue modificado."
        format.html { redirect_to pointsales_url, success: "El punto de venta #{@pointsale.name} fue modificado." }
        format.json { render :show, status: :ok, location: @pointsale }
      else
        format.html { render :edit }
        format.json { render json: @pointsale.errors, status: :unprocessable_entity }
      end
    end
  end

  def update_status
    pointsale = Pointsale.find(params[:pointsale_id])
    if pointsale.active?
      pointsale.status = 2
    elsif pointsale.inactive?
      pointsale.status = 1
    end
    respond_to do |format|
      if pointsale.save(validate: false)
        pointsale.users.each do |user|
          unless user.erased?
            user.status = pointsale.status
            user.save(validate: false)
          end
        end
        format.html { redirect_to pointsales_url, warning: "El punto de venta " + pointsale.name + " fue " + (pointsale.active? ? "activado" : "desactivado") + "." }
        # format.json { render :show, status: :ok, location: @pointsale }
        format.json { head :no_content }
      else
        format.html { redirect_to pointsales_url }
        format.json { render json: @pointsale.errors, status: :unprocessable_entity }
      end
    end
  end

  # rubocop:disable Metrics/BlockLength
  def transfer_stock
    respond_to do |format|
      destiny = params[:destiny][2, params[:destiny].length]
      availables = AvailableProduct.where('id in (?)', params[:all_ids])

      AvailableProduct.find(params[:ids_to_transfer]).each do |available|
        if params[:destiny].first == 'P' # es a punto de venta
          stock_product = AvailableProduct.find_by(product_id: available.product_id, pointsale_id: destiny)
          if stock_product.present?
            stock_product.stock += available.stock
          else
            stock_product = available.dup
            stock_product.pointsale_id = destiny
          end
        else
          # es a almacen
          stock_product = WarehouseStock.find_by(product_id: available.product_id, warehouse_id: destiny)
          if stock_product.present?
            stock_product.stock += available.stock
          else
            stock_product = WarehouseStock.new(warehouse_id: destiny, product_id: available.product_id, stock_min: available.stock_min, stock_max: available.stock_max, stock: available.stock)
          end
        end
        stock_product.save
        available.destroy
      end

      availables_with_zero = params[:all_ids] - params[:ids_to_transfer]
      unless availables_with_zero.empty?
        AvailableProduct.where(id: availables_with_zero).delete_all
      end
      format.json { head :ok }
    end
  end
  # rubocop:enable Metrics/BlockLength

  def assign_or_delete_products
    @todo = params[:todo]
    if @todo == 'delete'
      @products = AvailableProduct.find(params[:ids])
    elsif @todo == 'assign'
      @products = Product.find(params[:ids])
    end
    @pointsale = Pointsale.find(params[:pointsale_id])
  end

  def assign_products_to_pointsale
    respond_to do |format|
      @products = JSON.parse params[:products]
      @products.each do |product|
        available = AvailableProduct.new
        available.product_id = product['id']
        available.pointsale_id = params[:pointsale_id]
        available.stock_min = 0
        available.stock_max = 0
        available.stock = product['stock']
        available.save
      end
      format.json { head :ok }
    end
  end

  def delete_products_from_pointsale
    respond_to do |format|
      @ids = params[:ids]
      @to_delete_with_stock = AvailableProduct.where("id in (?) and stock > 0", @ids)
      @ids_array = Array.new
      @ids.each do |id|
        @ids_array << id
      end
      @ids_array = @ids_array.to_s

      if @to_delete_with_stock.blank?
        AvailableProduct.where(id: @ids).delete_all
      end
      format.js
    end
  end

  # DELETE /pointsales/1
  # DELETE /pointsales/1.json
  def destroy
    respond_to do |format|
      @pointsale.skip_name_validation = true
      @pointsale.skip_products_validation = true
      @pointsale.audit_comment = "El punto de venta " + @pointsale.name + " fue eliminado."
      if @pointsale.update_attributes(status: 0)
        CashRegister.where(pointsale_id: @pointsale.id).update_all(status: 'erased')
        format.html { redirect_to pointsales_url, warning: "El punto de venta " + @pointsale.name + " fue eliminado." }
        format.json { head :no_content }
      else
        format.html { render :edit }
        format.json { render json: @pointsale.errors, status: :unprocessable_entity }
      end
    end
  end

  private

  def set_pointsale
    @pointsale = Pointsale.find(params[:id])
  end

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

  def pointsale_params
    params.require(:pointsale).permit(:name, :address, :notes, :status, :prefix, :img_pointsale, :img_pointsale_cache, :ticket_footer, :haggle_percent, users_attributes: [:userid, :first_name, :last_name, :password, :email, :password_confirmation])
  end
end
