class MainController < ApplicationController
  require 'open-uri'
  require 'uri'
  require 'digest/md5'

  # SMS API constants

  SMS_KEYPHRASE = 'keyphrase defined in the API control panel'
  SMS_URL = 'http://sms.deeplocal.com/dispatch/send/send.php'

  # SMS action is the destination point for the SMS API

  def sms

    # Verify the security checksum before continuing
    # Checksum is an md5 hash of the keyword, message and your secret keyphrase strings

    if (params[:checksum] == Digest::MD5.hexdigest(params[:keyword] + params[:smsmsg] + SMS_KEYPHRASE))

      # Parse out the message only

      msg = params[:smsmsg].split(' ')
      msg.shift if msg.first.downcase == 'tip'
      msg = msg.join(' ').strip

      # Verify the tip amount

      if msg.empty? || msg.to_f == 0.0
        sendMessage(params[:keyword], 'Please, enter a valid amount. Ex: TIP 47.32')
      else

        # Calculate

        amount = msg.to_f
        tip15 = "%.2f" % (amount * 0.15)
        tip20 = "%.2f" % (amount * 0.2)
        amount = "%.2f" % amount

        # Send

        returnMessage = "15% is $#{tip15} and 20% is $#{tip20} of $#{amount}"
        sendMessage(params[:keyword], returnMessage)

      end

    end

    return render(:nothing => true)
  end

  private

  def sendMessage(keyword, msg)
    msg = URI.escape(msg, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))
    checksum = Digest::MD5.hexdigest(keyword + msg + SMS_KEYPHRASE)
    url = SMS_URL + "?keyword=TIP&message=#{msg}&handset=#{params[:smsfrom]}&carrier=#{params[:network]}&checksum=#{checksum}"
    open(url) {|f|}
  end

end