class SiteController < ApplicationController
  #include RecaptchaVerifier
  def index
    @pages = PublishedPage.where('type_of != 3').order('priority ASC')
    @ss = ScSetting.first
    pg_name = 'index'
    if cookies.encrypted[:visited].blank?
      cookies.permanent.encrypted[:visited] = JSON.generate([pg_name])
      @ss.increment!(:index_number_of_views)
    else
      arr = JSON.parse(cookies.encrypted[:visited])
      if !arr.include?(pg_name)
        arr << pg_name
        cookies.permanent.encrypted[:visited] = JSON.generate(arr)
        @ss.increment!(:index_number_of_views)
      end
    end
  end

  def show
    pages_get
    @page = PublishedPage.where('id = ? OR slug = ?',params[:id],params[:id]).first
    if cookies.encrypted[:visited].blank?
      cookies.permanent.encrypted[:visited] = JSON.generate([@page.id])
      @page.increment!(:number_of_views)
    else
      arr = JSON.parse(cookies.encrypted[:visited])
      if !arr.include?(@page.id)
        arr << @page.id
        cookies.permanent.encrypted[:visited] = JSON.generate(arr)
        @page.increment!(:number_of_views)
      end
    end

    if @page.blank?
      redirect_to '/404.html'
    end
  end

  def kontakt
    @ss = ScSetting.first
    pg_name = 'kontakt'
    if cookies.encrypted[:visited].blank?
      cookies.permanent.encrypted[:visited] = JSON.generate([pg_name])
      @ss.increment!(:contact_number_of_views)
    else
      arr = JSON.parse(cookies.encrypted[:visited])
      if !arr.include?(pg_name)
        arr << pg_name
        cookies.permanent.encrypted[:visited] = JSON.generate(arr)
        @ss.increment!(:contact_number_of_views)
      end
    end
    pages_get
  end

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

  def send_email
    # reCaptcha secret: 6LeaskIUAAAAACcF5jFmO2l7GRzNAKESmzdcxB1k
    if RecaptchaVerifier.verify(params["g-recaptcha-response"], request.ip)
      contact = {'name' => params[:name], 'message' => params[:message], 'email' => params[:email]}
      ContactMailer.contact_email(contact).deliver_now
      head :ok
    else
      return head(:bad_request)
    end


  end


  def pages_get
    @pages = PublishedPage.where('type_of != 3').order('priority ASC')
  end
end
