class Public::OffersController < ApplicationController
  layout "public"

  before_filter :auth_customer, :check_enabled, :get_need, :check_interest, :get_offer



  def accept
    if @offer.customers.include?(current_customer)
      flash[:error] = "Vous avez déjà accepter cette offre"
      return redirect_back_or_default :root
    end
    @accepted_offer = AcceptedOffer.new
    @accepted_offer.offer = @offer
    
  end

  def accept_save
    if @offer.customers.include?(current_customer)
      flash[:error] = "Vous avez déjà accepter cette offre"
      return redirect_back_or_default :root
    end
    @accepted_offer = AcceptedOffer.new(params.require(:accepted_offer).permit(:qte))
    @accepted_offer.customer = current_customer
    @accepted_offer.offer = @offer

    @document = Document.new
    @document.title = "Offre"
    @accepted_offer.documents << @document

    if @accepted_offer.save
      admins = Admin.where.not(email: nil)
      admins.each do |admin|
        AdminMailer.customer_accept_offer(admin, @accepted_offer).deliver
      end

      CustomerMailer.offer_accepted(current_customer, @accepted_offer).deliver

      flash[:notice] = "Offre acceptée avec succès !"



      redirect_to public_need_path(@need)
    else
      render :action => :accept
    end
  end
  

  def get_need
    @need = Need.find(params[:need_id])
  end

  def get_offer
    @offer = @need.offers.find(params[:id])
  end



  def check_interest

    if !@need.customers.include?(current_customer)
      flash[:error] = "Impossible de réaliser cette action car vous n'êtes pas intéressé par ce besoin"
      redirect_back_or_default :root
    end
  end
end
