class PurchasesController < ApplicationController

  ##--- Abilities
  load_and_authorize_resource

  ##--- Breadcrum_rails
  add_breadcrumb I18n.t("breadcrumbs." + controller_name), :purchases_path
  add_breadcrumb "Nueva " + I18n.t("breadcrumbs." + controller_name).singularize, :new_purchase_path, only: :new
  add_breadcrumb "Detalle de la " + I18n.t("breadcrumbs." + controller_name).singularize , :purchase_path, only: :show
  add_breadcrumb "Editar " + I18n.t("breadcrumbs." + controller_name).singularize , :edit_purchase_path, only: :edit

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

  # GET /purchases
  # GET /purchases.json
  def index
    if current_user.usertype == "A"
      @purchases = Purchase.all.includes(:supplier, :pointsale, :warehouse, :user).order("created_at DESC")
    else
      @purchases = Purchase.includes(:supplier, :user).where(:pointsale_id => current_user.pointsale_id).order('created_at desc')
    end
  end

  # GET /purchases/1
  # GET /purchases/1.json
  def show
  end

  # GET /purchases/new
  def new
    @disable_supplier = false
    @disable_pointsale = false
    @disable_warehouse = false
    @disable_is_in_dollars = false
    @disable_destiny = false
    @disabled_button = true
    @destiny = 'warehouse'
    @purchase = Purchase.new
    @purchase.purchase_details.new
    @pre_purchases = PrePurchase.where(:user_id => current_user.id)
    if @pre_purchases.size > 0
      @purchase.supplier_id = @pre_purchases[0].supplier_id
      @purchase.pointsale_id = @pre_purchases[0].pointsale_id
      @purchase.warehouse_id =  @pre_purchases[0].warehouse_id
      @destiny = @purchase.pointsale_id.present? ? 'pointsale' : 'warehouse'
      @purchase.exchange = @pre_purchases[0].exchange if @pre_purchases[0].exchange.present?
      @purchase.is_in_dollars = true if @pre_purchases[0].exchange.present?
      @disable_supplier = true
      @disable_pointsale = true
      @disable_warehouse = true
      @disable_is_in_dollars =  true
      @disable_destiny = true
      @disabled_button = false
    end
    if current_user.usertype == 'G'
      @destiny = 'pointsale'
      @purchase.pointsale_id = current_user.pointsale_id
      @disable_pointsale = true
      @disable_warehouse = true
      @disable_destiny = true
    end
  end

  # POST /purchases
  # POST /purchases.json
  def create
    @purchase = Purchase.new(purchase_params)
    @purchase.user_id = current_user.id
    @purchase.status = :notpaid
    @pre_purchases = PrePurchase.where(:user_id => current_user.id)

    respond_to do |format|
      message = "compra #{@purchase.purchase_code} por #{@purchase.total} creada."
      @purchase.audit_comment = message
      if @purchase.save
        @pre_purchases.each do |pre_purchase|
          # agregar detalles de la compra
          detail = PurchaseDetail.new
          detail.product_id = pre_purchase.product_id
          detail.quantity = pre_purchase.quantity
          detail.amount = pre_purchase.total
          detail.price = pre_purchase.price_base
          detail.tax = pre_purchase.tax
          @purchase.purchase_details << detail
          # actualizar stock del producto cuando es para punto de venta
          if @purchase.pointsale_id.present?
            stockProduct = AvailableProduct.find_by(:product_id => detail.product_id, :pointsale_id => @purchase.pointsale_id)
            if stockProduct.present?
              stockProduct.stock = 0 if stockProduct.stock.blank?
              stockProduct.stock += detail.quantity
              stockProduct.save
            else
              stockProduct = AvailableProduct.new
              stockProduct.product_id = detail.product_id
              stockProduct.pointsale_id = @purchase.pointsale_id
              stockProduct.stock = detail.quantity
              stockProduct.save
            end
          else
            # actualizar stock del producto cuando es para punto de venta
            stockProduct = WarehouseStock.find_by(:product_id => detail.product_id, :warehouse_id => @purchase.warehouse_id)
            if stockProduct.present?
              stockProduct.stock = 0 if stockProduct.stock.blank?
              stockProduct.stock += detail.quantity
              stockProduct.save
            else
              stockProduct = WarehouseStock.new
              stockProduct.product_id = detail.product_id
              stockProduct.warehouse_id = @purchase.warehouse_id
              stockProduct.stock = detail.quantity
              stockProduct.save
            end
          end
          # guardar en bitacora de inventario
          move = InventoriesMove.new
          move.product_id = detail.product_id
          move.purchase_id = @purchase.id
          move.quantity = detail.quantity
          move.move_type = "incoming"
          move.reason = "purchase"
          move.save

          pre_purchase.destroy
        end
        format.html { redirect_to purchases_url, success: message }
      else
        format.html { render :new }
        format.json { render json: @purchase.errors.values, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /purchases/1
  # DELETE /purchases/1.json
  def destroy
    respond_to do |format|
      message = "Compra #{@purchase.purchase_code} cancelada."
      @purchase.audit_comment = message
      if @purchase.update_attributes(:status => :cancelled)
        #checa si hay pagos de esta compra
        CashRegistersMove.where(:purchase_id => @purchase.id).each do |move|
          new_cash_move = move.dup
          new_cash_move.move_type = :ingreso
          new_cash_move.save
        end

        @purchase.purchase_details.each do |detail|
          detail.update_attributes(:status => :inactive)
          #busca y actualiza el stock de productos
          if @purchase.pointsale.present?
            stockProduct = AvailableProduct.find_by(:product_id => detail.product_id, :pointsale_id => @purchase.pointsale_id)
          else
            stockProduct = WarehouseStock.find_by(:product_id => detail.product_id, :warehouse_id => @purchase.warehouse_id)
          end
          # restarle al stock del producto
          stock = stockProduct.stock - detail.quantity
          stockProduct.update_attributes(:stock => stock)

          # guardar en bitacora de inventario
          move = InventoriesMove.new
          move.product_id = detail.product_id
          move.purchase_id = @purchase.id
          move.quantity = detail.quantity
          move.move_type = "outgoing"
          move.reason = "purchase_cancel"
          move.save
        end
        format.html { redirect_to purchases_url, warning: message }
        format.json { head :no_content }
      else
        format.html { render :edit }
        format.json { render json: @purchase.errors, status: :unprocessable_entity }
      end
    end
  end

  def find_purchases_by_date
    startDate = DateTime.parse(params[:begin_date])
    endDate = DateTime.parse(params[:end_date])
    if current_user.usertype == "A"
      @purchases = Purchase.includes(:supplier, :pointsale, :warehouse, :user).where(:purchase_date => startDate..endDate).order('purchase_date desc')
    else
      @purchases = Purchase.includes(:supplier, :user).where(:pointsale_id => current_user.pointsale_id, :created_at => startDate..endDate).order('purchase_date desc')
    end
    respond_to do |format|
      format.js
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_purchase
      @purchase = Purchase.find(params[:id])
    end

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

    # Never trust parameters from the scary internet, only allow the white list through.
    def purchase_params
      params.require(:purchase).permit(:supplier_id, :pointsale_id, :warehouse_id ,:purchase_code, :amount, :tax, :total, :observations, :purchase_date, :is_in_dollars, :exchange)
    end
end
