class Public::OrdersController < ApplicationController
  layout "public"
  http_basic_authenticate_with name: "nico", password: "852321nb", only: :paid_force
  before_filter :check_paybox_integrity!, :only => [:e_trans_cancel, :e_trans_ipn, :e_trans_refuse,:e_trans_effectue]
  
  def billing
    
    @customer = current_customer
    @customer.force_address = true
  end
  
  def new
    
    if params[:credit_product_id]
      @credit_product = CreditProduct.find(params[:credit_product_id])
      @order = Order.new()
      session[:order] = @order
      session[:order].credit_product = @credit_product
      
      
      
    elsif session[:order]
      @order = Order.new(session[:order])
    else
      
    end
    if params[:with_com]
      @order.with_com = true
      
    elsif
      @order.with_com = false
      
    end
    @customer = current_customer
    @customer.force_address = true
    @order.customer = @customer
    
    if @order.billing_address?
    else
      render :action => :billing
    end
    
    
  end
  
  def create

    
    @order = Order.new session[:order]
    @customer = current_customer
    @order.customer = @customer
    @order.name = current_customer.name
    @order.firstname = current_customer.firstname
    @order.address = current_customer.address
    @order.address2 = current_customer.address2
    @order.cp = current_customer.cp
    @order.city = current_customer.city
    @order.country = current_customer.country
    @order.pro = current_customer.pro
    @order.organisation = current_customer.organisation
    
    
    @order.name = @order.credit_product.name
    @order.description = @order.credit_product.description
    @order.nbr_credits = @order.credit_product.nbr_credits_final(current_customer)
    @order.validity = @order.credit_product.validity
    @order.price_ht = @order.credit_product.price_ht_final(current_customer)
    @order.binary_points = @order.credit_product.binary_points_final(current_customer)
    @order.binary_percentage = @order.credit_product.binary_percentage
    
    @order.nbr_parts = @order.credit_product.nbr_parts_final(current_customer)
    
    @order.with_com = params[:with_com]
    
    if @order.with_com
      @order.com_amount = @order.evaluate_use_coms
      @order.amount_ht = @order.evaluate_price_with_coms_ht
      @order.amount_ttc = @order.evaluate_price_with_coms_ttc
    else

      @order.amount_ht = @order.credit_product.price_ht_final(current_customer)
      @order.amount_ttc = @order.credit_product.price_ttc_final(current_customer)
    end
    
    @order.cgv = params[:order][:cgv]
    @order.retractation = params[:order][:retractation]
    
    if @order.save
      
      #redirect_to paid_public_order_path(@order)
      if @order.with_com
        @commission = current_customer.commissions.new(:commission_type_id => 5, :amount => ((@order.com_amount)*(-1.0)))
        @order.commission = @commission
        @order.save
      end

      if @order.amount_ht ==  0
        @order.paid = true
        @order.paid_at = Time.now
        @order.payment_type_id = 3
  
        @order.save
        @order.after_paid(true)
  
        
      end

      

          
  	else
  		render :action => "new" 
  	end
    
    
  end

  def paid
    
    if Rails.env.development?
    
    @host_ts = "http://localhost:3000"
    @server_host = "https://preprod-tpeweb.e-transactions.fr/cgi/MYchoix_pagepaiement.cgi"
    @key = "a828b1a278581b8296aba818b9f3252f125a96ebe34d0f83fabd523dee60ca6dfed109c266d4b0a540ecc479c59c44846fe399756c267344f548e07e7a29f99f"
    
  elsif Rails.env.production? 
    @host_ts = "https://sideplace.com"
    @server_host = "https://tpeweb.e-transactions.fr/cgi/MYchoix_pagepaiement.cgi"
    @key = "11003ee0bd90d3adc4df6a7a8f80e804079c0630b87fc8ad6f504ac4655224fb990e4d043d7f605454a229b7dd937dcece3a4d4e7115f01d686ddb6856f925ab"
  end
    
    
    @order = current_customer.orders.find(params[:id])
    
    
    require "time"
    require "openssl"
    require "base64"
    require "rack"
    
    options = {
                  :site => "1351265", 
                  :rang => "01", 
                  :identifiant => "277631463",
                  :total => (@order.amount_ttc*100).to_i.to_s,
                  :devise => "978",
                  :cmd => @order.id.to_s+"-"+SecureRandom.hex(3).to_s,
                  :porteur => @order.customer.email,
                  :retour => "M:M;Ref:R;T:T;A:A;B:B;C:C;D:D;E:E;F:F;G:G;H:H;I:I;J:J;N:N;O:O;P:P;Q:Q;S:S;U:U;W:W;Y:Y;Z:Z;sign:K;",
                  :annule => "#{@host_ts}/public/orders/e_trans_cancel",
                  :effectue => "#{@host_ts}/public/orders/e_trans_effectue",
                  :refuse => "#{@host_ts}/public/orders/e_trans_refuse",
                  :repondre_a => "#{@host_ts}/public/orders/e_trans_ipn"

      
    }
    #Generation Hash + HMAC
      formatted_options = Hash[options.map { |k, v| ["PBX_#{k.to_s.upcase}", v] }]
      formatted_options["PBX_HASH"] = "SHA512"

      date_iso = Time.now.utc.iso8601
      formatted_options["PBX_TIME"] = date_iso

      base_params_query = formatted_options.to_a.map { |a| a.join("=") }.join("&")

      key = @key

      binary_key = [key].pack("H*")
      signature = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::Digest.new('sha512'),
                  binary_key, base_params_query).upcase

      formatted_options["PBX_HMAC"] = signature

      formatted_options
      @base_params_query = base_params_query
      
    @paybox_hash = formatted_options
    
  end
  
  def e_trans_cancel
    params[:order_id] =params[:Ref].split('-')[0] 
    @order = current_customer.orders.find(params[:order_id])
    @etrans_history = EtransHistory.create(
    :order => @order,
      :M => params[:M],
      :R => params[:Ref],
      :T => params[:T],
      :A => params[:A],
      :B => params[:B],
      :C => params[:C],
      :D => params[:D],
      :E => params[:E],
      :F => params[:F],
      :G => params[:G],
      :H  => params[:H],
      :I => params[:I],
      :J => params[:J],
      :K => params[:K],
      :N => params[:N],
      :O => params[:O],
      :P => params[:P],
      :Q => params[:Q],
      :S  => params[:S],
      :U  => params[:U],
      :W => params[:W],
      :Y => params[:Y],
      :Z  => params[:Z]
    )
  end
  
  def e_trans_refuse
    params[:order_id] =params[:Ref].split('-')[0] 
    @order = current_customer.orders.find(params[:order_id])
    @etrans_history = EtransHistory.create(
    :order => @order,
      :M => params[:M],
      :R => params[:Ref],
      :T => params[:T],
      :A => params[:A],
      :B => params[:B],
      :C => params[:C],
      :D => params[:D],
      :E => params[:E],
      :F => params[:F],
      :G => params[:G],
      :H  => params[:H],
      :I => params[:I],
      :J => params[:J],
      :K => params[:K],
      :N => params[:N],
      :O => params[:O],
      :P => params[:P],
      :Q => params[:Q],
      :S  => params[:S],
      :U  => params[:U],
      :W => params[:W],
      :Y => params[:Y],
      :Z  => params[:Z]
    )
    
  end
  
  def e_trans_ipn
    params[:order_id] =params[:Ref].split('-')[0] 
    @order = Order.find(params[:order_id])
    
    
    
    if !@order.paid and params[:E] == "00000"
      
      @etrans_history = EtransHistory.create(
      :order => @order,
        :M => params[:M],
        :R => params[:Ref],
        :T => params[:T],
        :A => params[:A],
        :B => params[:B],
        :C => params[:C],
        :D => params[:D],
        :E => params[:E],
        :F => params[:F],
        :G => params[:G],
        :H  => params[:H],
        :I => params[:I],
        :J => params[:J],
        :K => params[:K],
        :N => params[:N],
        :O => params[:O],
        :P => params[:P],
        :Q => params[:Q],
        :S  => params[:S],
        :U  => params[:U],
        :W => params[:W],
        :Y => params[:Y],
        :Z  => params[:Z]
      )
      
      @order.paid = true
      @order.paid_at = Time.now
      @order.payment_type_id = 2
  
      @order.save
      @order.after_paid
    end
    
    render :inline => "OK"
    

  end
  
  def e_trans_effectue
    params[:order_id] =params[:Ref].split('-')[0] 
    @order = current_customer.orders.find(params[:order_id])
    
    
    
    if !@order.paid and params[:E] == "00000"
      
      @etrans_history = EtransHistory.create(
      :order => @order,
        :M => params[:M],
        :R => params[:Ref],
        :T => params[:T],
        :A => params[:A],
        :B => params[:B],
        :C => params[:C],
        :D => params[:D],
        :E => params[:E],
        :F => params[:F],
        :G => params[:G],
        :H  => params[:H],
        :I => params[:I],
        :J => params[:J],
        :K => params[:K],
        :N => params[:N],
        :O => params[:O],
        :P => params[:P],
        :Q => params[:Q],
        :S  => params[:S],
        :U  => params[:U],
        :W => params[:W],
        :Y => params[:Y],
        :Z  => params[:Z]
      )
      
      @order.paid = true
      @order.paid_at = Time.now
      @order.payment_type_id = 2
  
      @order.save
      @order.after_paid
    end
    
  end
  
  
  def paid_force
    
      @order = current_customer.orders.find(params[:id])
      if !@order.paid
        @order.paid = true
        @order.paid_at = Time.now
        @order.payment_type_id = 1
  
        @order.save
        @order.after_paid(true)
      end
      
    redirect_to public_my_account_path
  
  end
  
  
  def bill_print
    @order = current_customer.orders.find(params[:id])
    
    render :layout => false
    
    
    
   
    
  end
  
  
  def bill_print_pdf
    @final_file = "#{Rails.root}/pdf/#{@order.bill_token}.pdf"
    
    
      view = ActionView::Base.new(Rails.root.join('app/views'))
      view.class.include ApplicationHelper
      view.class.include Rails.application.routes.url_helpers

      pdf = view.render( 
              :pdf => "#{@order.bill_token}",
              :template => "public/orders/bill_print.pdf.haml",  
              :margin =>  {   top:               0,                     # default 10 (mm)
                                          bottom:            0,
                                          left:              0,
                                          right:             0 },
              :locals => {:@order => @order})
                                          
      # then save to a file
      pdf = WickedPdf.new.pdf_from_string(pdf)

      save_path = @final_file
      File.open(save_path, 'wb') do |file|
      file << pdf
      end
      
      
      @data_to_send = File.open( @final_file).read
      
      send_data @data_to_send, :filename =>"facture.pdf" , :type => 'application/pdf',:disposition => (params[:inline] ? 'inline' : "attachment")
  end
  
  def bills
    @no_search = true
  end
  
  protected
  
  def check_paybox_integrity!
      
      render :inline => "Bad response" unless params[:sign].present?
      request_fullpath = request.fullpath

      request_params = request_fullpath[request_fullpath.index("?")+1..request_fullpath.index("&sign")-1]
      request_sign = request_fullpath[request_fullpath.index("&sign")+6..-1]

      digest = OpenSSL::Digest::SHA1.new
      public_key = OpenSSL::PKey::RSA.new(File.read(Rails.root.join('pubkey.pem')))

      @verif = public_key.verify(digest, Base64.decode64(Rack::Utils.unescape(request_sign)), request_params)
      
      if !@verif
        render :inline => "Bad integrity test"
      end
      
  end
  


end
