class Public::ContactMessagesController < ApplicationController
  layout "public"

  def index
    ContactMessage.update_all(read_by_customer: true)
    @contact_message = ContactMessage.new
    @contact_messages = ContactMessage.where("customer_id = ? OR contact_id = ?", current_customer.id,current_customer.id )
    .order(created_at: :desc)
    .page params[:page]


  end

  def create

    @contact_message = ContactMessage.new
    @contact_message.assign_attributes(message_params)
    @contact_message.customer = current_customer
    @contact_message.contact = current_customer
    @contact_message.read_by_customer = true

    if @contact_message.save
      flash[:notice] = "Message envoyé."

      admins = Admin.where.not(email: nil)
      admins.each do |admin|
        AdminMailer.customer_send_contact_message(admin, @contact_message).deliver
      end

      return redirect_to :back
    else
      flash[:error] = "Votre message n'a pas pu être envoyé."
      return render 'index'
    end




  end

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

     redirect_to :back
  end

  def message_params
     params.require(:contact_message).permit(:content)
  end
end
