# sites logic goes here
class SiteController < ShopController
  # include RecaptchaVerifier
  def index
    set_cookies_and_inc_view(@ss, :index_number_of_views, 'index')
  end

  def show
    @page = PublishedPage.finder(params[:id]).first
    raise_404(@page)
    add_breadcrumb @page.name, "/site/#{@page.slug}"
    set_cookies_and_inc_view(@page, :number_of_views, @page.id)
  end

  def kontakt
    set_cookies_and_inc_view(@ss, :contact_number_of_views, 'kontakt')
  end

  def preview
    @page = AllPage.finder(params[:id]).first
    redirect_to '/404.html' if @page.blank?
  end

  def send_email
    if RecaptchaVerifier.verify(params['g-recaptcha-response'], request.ip)
      ContactMailer.contact_email(name: params[:name],
                                  message: params[:message],
                                  email: params[:email])
                   .deliver_now
      head :ok
    else
      head :bad_request
    end
  end

  private

  def set_cookies_and_inc_view(object, increment_column_name, pg_name)
    if cookies.encrypted[:visited].blank?
      cookies.permanent.encrypted[:visited] = JSON.generate([pg_name])
      object.increment!(increment_column_name)
    else
      arr = JSON.parse(cookies.encrypted[:visited])
      unless arr.include?(pg_name)
        arr << pg_name
        cookies.permanent.encrypted[:visited] = JSON.generate(arr)
        object.increment!(increment_column_name)
      end
    end
  end
end
