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

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

  before_action :admin_space
  
  def admin_space
    @admin_space = "documents"
  end
  
  
  def generate_stocks
    @stock_movement = StockMovement.find(params[:id])
    
    
    
    
    if @stock_movement.generate_stock
      redirect_back(fallback_location: admin_stock_movements_path)
    else
      redirect_back(fallback_location: admin_stock_movements_path,:notice => "Le stock n'a pas pu être mis à jour, tous les articles ne sont pas présents")
    end
    
    
  end
  
  def index
    @stock_movements = StockMovement.all


    if false
        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
    
    
      @stock_movements = @stock_movements.where("date >= ?", @start) if @start

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

    end

    @stock_movements = sort_by_sorting(@stock_movements, "id DESC")
    
    @all_stock_movements = @stock_movements
    
    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 
        @stock_movements = @stock_movements.page(page).per(per_page)
      
      }
    end
  end

  def show
    @stock_movement = StockMovement.find(params[:id])

  end

  def new
    @stock_movement = StockMovement.new(:movement_type => params[:movement_type])
  
  end

  def edit
    @stock_movement = StockMovement.find(params[:id])
    
  end

  def create
    @stock_movement = StockMovement.new(params.require(:stock_movement).permit!)

    if @stock_movement.save
      
    else
      render action: "new"
 
    end

  end


  def update
    @stock_movement = StockMovement.find(params[:id])


    if @stock_movement.update_attributes(params.require(:stock_movement).permit!)
      
    else
     render action: "edit" 
      
    end
      
  end


  def destroy
    @stock_movement = StockMovement.find(params[:id])
    @stock_movement.destroy
    
  end
end
