class Admin::MessagesController < ApplicationController
  layout "admin"
  before_filter :auth_admin


  def index
    @need = Need.find(params[:need_id])
    @comments = @need.messages.order(created_at: :desc).page params[:page]

  end

  def create
    @message = Message.new
    @message.admin = current_admin
    @message.content = params[:message][:content]
    @need = Need.find(params[:need_id])
    @message.need = @need
    if @message.save
      admins = Admin.where.not(email: nil)
      admins.each do |admin|
        AdminMailer.customer_post_comment(admin, @need, @message).deliver
      end

      @need.customers.each do |customer|
        CustomerMailer.need_commented(customer, @need, @message).deliver
      end

      flash[:notice] = "Commentaire envoyé"

      redirect_to action: 'index'
    else
      flash[:error] = "Impossible de créer ce commentaire"

      redirect_to action: 'index'
    end
  end

  def destroy
     @message = Message.find(params['id'])
     if @message.destroy
       flash[:notice] = "Commentaire supprimé"
     else
       flash[:error] = "Impossible de supprimer ce commentaire"
     end

     redirect_to :back
  end

end
