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

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

  before_action :admin_space
  
  def admin_space
    @admin_space = "stocks"
  end
  
  def index
    @m_odr_reps = MOdrRep.includes(:m_odr)
    
    @can_update = current_admin.has_permission?("odr_rep.update")
    
    if !current_admin.has_permission?("odr_rep.view")
      @m_odr_reps = @m_odr_reps.joins(:m_odr).where(:m_odrs => {:p_customer_id => current_admin.p_customers.ids})
      
    end
    
    if params[:name].to_s != ""
      @m_odr_reps = @m_odr_reps.where("cc_particular_name LIKE ? or cc_particular_firstname LIKE ?","%#{params[:name]}%", "%#{params[:name]}%")
    end
    
    if params[:search][:state].to_s != ""
      @m_odr_reps = @m_odr_reps.where(:state => params[:search][:state])
    end
    
    if params[:search][:m_odr_id].to_s != ""
      @m_odr_reps = @m_odr_reps.where(:m_odr_id => params[:search][:m_odr_id])
    end


    @m_odr_reps = sort_by_sorting(@m_odr_reps, "m_odr_reps.created_at DESC")
    
    
    params[:search][:per_page] = params[:search][:per_page] || 50
		per_page = params[:search][:per_page]
		page = (params[:page] and params[:page] != "") ? params[:page] : 1 
		@m_odr_reps = @m_odr_reps.page(page).per(per_page)
    

  end

  def show
    @m_odr_rep = MOdrRep.find(params[:id])
    @m_odr = @m_odr_rep.m_odr
    
    
  end

  def new
    @m_odr_rep = MOdrRep.new
  
  end

  def edit
    @m_odr_rep = MOdrRep.find(params[:id])
    
  end

  def create
    @m_odr_rep = MOdrRep.new(params.require(:m_odr_rep).permit!)

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

  end


  def update
    @m_odr_rep = MOdrRep.find(params[:id])


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


  def destroy
    @m_odr_rep = MOdrRep.find(params[:id])
    @m_odr_rep.destroy
    
  end
  
  
  def generate_virement
    @m_odr_rep = MOdrRep.find(params[:id])
    
    @m_odr_rep.m_odr_virements.create
    @m_odr_rep.change_state("Virement demandé")
    
    redirect_back(fallback_location:"/")
  end
    
    
  def refuse
    @m_odr_rep = MOdrRep.find(params[:id])
    
    
    @m_odr_rep.change_state("Refusée")
    
    
    redirect_to [:admin, @m_odr_rep]
  end
    
  def send_mail
    @m_odr_rep = MOdrRep.find(params[:id])
    @m_odr_rep.send_mail_type(params[:slug].to_s)
    
    redirect_to [:admin, @m_odr_rep]
    
    
  end
  
end
