# -*- encoding : utf-8 -*-

class Admin::LineStocksController < ApplicationController
  layout "admin"
  before_action :auth_admin

  before_action :admin_space

  def admin_space
    @admin_space = "documents"
  end

  def index
    @line_stocks = LineStock.all

    date_regex = /^(0[1-9]|[12][0-9]|3[01])[\/](0[1-9]|1[012])[\/](19|20)\d\d$/i


    #params[:start] = Date.today.beginning_of_month.strftime('%d/%m/%Y') if !params[:start]

    if params[:start] and params[:start] =~ date_regex
      #fsfds = sdfsfd
      @start = Date.parse(params[:start]).beginning_of_day
      params[:start]= @start.strftime('%d/%m/%Y')
    else
      @start = nil
    end

    if true
      #params[:stop] = Date.today.end_of_month.strftime('%d/%m/%Y') if !params[:stop]


      if params[:stop].to_s != "" # and params[:stop] =~ date_regex
        @stop = Date.parse(params[:stop]).end_of_day

        params[:stop]= @stop.strftime('%d/%m/%Y')


      else
         @stop = nil
      end

    end


    @line_stocks = @line_stocks.where("date >= ?", @start) if @start

    @line_stocks = @line_stocks.where("date <= ?", @stop.end_of_day) if @stop


    if params[:p_product_ref_id].to_s != ""
      @p_product_ref = PProductRef.where(:id => params[:p_product_ref_id]).first
      @line_stocks = @line_stocks.where(:p_product_ref_id => params[:p_product_ref_id])
    end


    @line_stocks = sort_by_sorting(@line_stocks, "date DESC")

    @all_line_stocks = @line_stocks

    respond_to do |format|
      format.html{

        params[:search][:per_page] = params[:search][:per_page] || 100
        per_page = params[:search][:per_page]
        page = (params[:page] and params[:page] != "") ? params[:page] : 1
        @line_stocks = @line_stocks.page(page).per(per_page)

      }
    end
  end

  def show
    @line_stock = LineStock.find(params[:id])

  end

  def new
    @line_stock = LineStock.new

  end

  def edit
    @line_stock = LineStock.find(params[:id])

  end

  def create
    @line_stock = LineStock.new(params.require(:line_stock).permit!)

    if @line_stock.save

    else
      render action: "new"

    end

  end


  def update
    @line_stock = LineStock.find(params[:id])


    if @line_stock.update_attributes(params.require(:line_stock).permit!)

    else
     render action: "edit"

    end

  end


  def destroy
    @line_stock = LineStock.find(params[:id])
    @line_stock.destroy

  end

  def stock_resume
    @p_product_refs = PProductRef.order(:name).all

    if params[:code].to_s != ""
      @p_product_refs = @p_product_refs.where("p_product_refs.code LIKE ?","%#{params[:code]}%")
    end

    if params[:name].to_s != ""
      @p_product_refs = @p_product_refs.where("p_product_refs.name LIKE ?","%#{params[:name]}%")
    end
  end

  def empty_stock
    @price_document = PriceDocument.where(:price_document_type_id => 4, :cost_ok => false)
  end
end
