# Konczenie zamowienia
class CheckoutController < ShopController
  include CheckoutHelper
  before_action :set_order, only: %i[order change_shipping end_order]
  def order
    add_breadcrumb 'Podsumowanie', '/checkout/order'
    return if @cart.blank?
    @shippings = Shipping.available.by_name_asc
    @payment_methods = PaymentMethod.available.by_name_asc
    if @order.blank?
      @order = Order.new
      @order.cart = @cart
      @order.shipping = Shipping.by_default.first
      @order.payment_method = PaymentMethod.by_default.first
      @order.save
    end
  end

  def change_shipping
    @shipping = Shipping.where(id: params[:val]).first
    if !@shipping.blank? && !@order.blank?
      @order.shipping = @shipping
      @order.save
    end
  end

  def end_order
    if !@cart.blank? && !@order.blank?
      if RecaptchaVerifier.verify(params['g-recaptcha-response'], request.ip)
        if @order.update_attributes(order_params)
          @order.status = 1
          # kopiujemy wszystkie produkty z koszyka i odejmujemy od ilosci
          # z rezerwacji jesli jest taka potrzeba
          copy_cart_prod_to_order(@cart, @order)
          @order.save
          # usunac ciasteczko z koszykiem jesli wszystko sie udalo
          delete_cookies_for_cart
          # wyslac maila z zamowieniem
          @order.reload
          @cart = nil
          OrderMailer.new_order(@order).deliver_later
          OrderMailer.new_order_to_shop_owner(@order).deliver_later
          @order_complete = true
        else
          @message = ['billing-info', errors_to_html(@order.errors)]
        end

      else
        # recapcha errors
        @message = ['payment', "<div class='alert alert-danger'>Potwierdź"\
                    ', że nie jesteś robotem</div>']
      end
    else
      @order_comlete = false
    end
  end

  def order_confirmation
    # TODO; order confirmation page
  end

  def gen_pdf
    # TODO
  end

  private

  def set_order
    @order = Order.where(cart_id: @cart.id).first unless @cart.blank?
  end

  def order_params
    params.require(:order)
          .permit(:email, :message_from_client, :terms_of_service_acceptance,
                  :first_name, :last_name, :phone, :street, :city, :zip_code)
  end
end
