# -*- encoding : utf-8 -*-

class Public::PaymentsController < ApplicationController
	
	layout "public"
  
  skip_before_filter :verify_authenticity_token, :only => [:payplug_ipn, :paypal_ipn, :ogone_ipn]
  
  def paid
    @payment = current_customer.payments.find(params[:id])
    
    if params[:orderID]
      if @payment.ogone_payid? and !@payment.element.paid
        
        if @payment.element_type == "ProductOrder"
          redirect_to select_payment_public_product_orders_path(:paid_fail => 1) 
        else
        
          @abonnement = @payment.element
          @payment = @abonnement.payments.create(:amount => @abonnement.total_price_ttc, :payment_type_id => 1, :customer_id => current_customer.id)
        end
      end
    end
    
  end
  def paid_by_ogone
    
    @payment = current_customer.payments.find(params[:id])
    
    if @payment.paid
      render :inline => "paiement déjà enregistré"
      #redirect_to new_public_donator_transaction_path(:paid => true)
    else
      

    
      @ogone_options = {
        :amount => @payment.amount,
        :accept_url => "http://#{HOSTNAME}"+paid_by_ogone_confirm_public_payment_path(@payment.id),
        :decline_url => "http://#{HOSTNAME}"+paid_public_payment_path(@payment.id),
        :exception_url => "http://#{HOSTNAME}"+paid_public_payment_path(@payment.id),
        :cancel_url => "http://#{HOSTNAME}"+paid_public_payment_path(@payment.id),    
        :orderid =>  @payment.token,
        :PARAMVAR => "ogoneipn",
        :PSPID => OgoneRails::pspid,
        :currency => OgoneRails::currency,
        :language => OgoneRails::language,
      
      }
    
     

    end
    
  end
  
  
  
  def paid_by_ogone_confirm
    
    @check = OgoneRails::CheckAuth.new( request )
  
    if @check.valid?
  
      @payment = Payment.find_by_token(params[:orderID])
      
      
        
    end
    
    if !@payment.paid
      update_ogone_infos()
      
    end
  
    
    
    if !@payment.paid
      
      #render :inline => "pas payé"
      #redirect_to paid_public_payment_path(@payment)
    end
    
    if @payment.element_type == "ProductOrder"
      redirect_to paid_by_ogone_confirm_public_product_orders_path()
    end
    
    
  end
  
  
  def ogone_ipn
    
    update_ogone_infos()
    
    render :inline => "ok"
    
  end
  
  
  
  
  
  #------------------------------
  
  
  
  
  
  def paid_by_paypal
    @donator_transaction = DonatorTransaction.find(session[:donator_transaction_id])
    
    if @donator_transaction.paid
      redirect_to new_public_donator_transaction_path(:paid => true)
    else
      @payment = Payment.create(:tr_payment_type_id => 6)
      @donator_transaction.tr_payments << @payment
      
      require 'paypal-sdk-merchant'
      @api = PayPal::SDK::Merchant::API.new

   
      @set_express_checkout = @api.build_set_express_checkout({
        :SetExpressCheckoutRequestDetails => {
          :custom => @payment.token,
          :ReturnURL => do_paypal_payment_public_donator_transaction_url(@donator_transaction.id),
          :CancelURL => edit_public_donator_transaction_url(@donator_transaction.id),
          :NoShipping => 1,
          :PaymentDetails => [{
            :OrderTotal => {
              :currencyID => "EUR",
              :value =>@donator_transaction.total },
          
            :NotifyURL => "http://#{HOSTNAME}"+paypal_ipn_public_donator_transaction_path(@donator_transaction),
            :ShipToAddress => {
              :Name => @donator_transaction.particular_bill.name.to_s+" "+@donator_transaction.particular_bill.firstname.to_s,
              :Street1 => @donator_transaction.particular_bill.address_2,
              :Street2 => @donator_transaction.particular_bill.address_3,
              :CityName => @donator_transaction.particular_bill.city.upcase,
              :StateOrProvince => "",
              :Country => @donator_transaction.particular_bill.country.upcase,
              :PostalCode => @donator_transaction.particular_bill.cp.upcase },
            
            :PaymentAction => "Sale" }] } })
    
      # Make API call & get response
      @set_express_checkout_response = @api.set_express_checkout(@set_express_checkout)

      # Access Response
      if @set_express_checkout_response.success?
      
        @get_express_checkout_details = @api.build_get_express_checkout_details({
          :Token => @donator_transaction.token })

        @get_express_checkout_details_response = @api.get_express_checkout_details(@get_express_checkout_details)
      
      
      
      
        @payment_detail = @get_express_checkout_details_response.GetExpressCheckoutDetailsResponseDetails.PaymentDetails[0]
      
      
        redirect_to @api.express_checkout_url(@set_express_checkout_response.Token)
      else
        @set_express_checkout_response.Errors
      end
    end
  end
  

  
  def do_paypal_payment
    load_specific_page if @new_site
    
    require 'paypal-sdk-merchant'
    @api = PayPal::SDK::Merchant::API.new
    
    
    @get_express_checkout_details = @api.build_get_express_checkout_details({:Token => params[:token] })

    @get_express_checkout_details_response = @api.get_express_checkout_details(@get_express_checkout_details)




    # Access Response
    if @get_express_checkout_details_response.success?
      
      
      @payment = Payment.find_by_token(@get_express_checkout_details_response.GetExpressCheckoutDetailsResponseDetails.Custom.to_s)
      
      
      @order = @payment.donator_transaction
    
      
      
      
    else
      
      
      @get_express_checkout_details_response.Errors
    end
    
    # Build request object
    @do_express_checkout_payment = @api.build_do_express_checkout_payment({
      :DoExpressCheckoutPaymentRequestDetails => {
        :PaymentAction => "Sale",
        :Token => params[:token],
        :PayerID => params[:PayerID],
        :PaymentDetails => [{
          :OrderTotal => {
            :currencyID => "EUR",
            :value => @order.total },
          :NotifyURL => "http://#{HOSTNAME}"+paypal_ipn_public_donator_transaction_path(@order) }] } })

    # Make API call & get response
    @do_express_checkout_payment_response = @api.do_express_checkout_payment(@do_express_checkout_payment)

    # Access Response
    if @do_express_checkout_payment_response.success?
      @payment_info = @do_express_checkout_payment_response.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0]
      
      @do_express_checkout_payment_response.DoExpressCheckoutPaymentResponseDetails
      @do_express_checkout_payment_response.FMFDetails
      
    
      
      
      
      
      
  
      if @payment_info.PaymentStatus.to_s == "Completed"

        params[:payment_status] ="Completed"
        update_paypal_infos()
        
        
      else
        redirect_to select_payment_public_donator_transaction_path(@donator_transaction.id)
        #render :file => 'public/500.html', :status => 500, :layout => false
        
      end
      
      
    

      
      
      
    else
      render :file => 'public/500.html', :status => 500, :layout => false
    end
    
    
    
    
  end
	
  def paypal_ipn
    
    
    @api = PayPal::SDK::Merchant.new
      if @api.ipn_valid?(request.raw_post)  # return true or false
        @payment = Payment.find_by_token(params[:custom].to_s)
      
        @order = @payment.donator_transaction
        
        
        
       # @order.payment_type= 6
       # @order.paid = true
       # @order.paid_at = Time.now
        
        @payment.paypal_test_ipn= params[:test_ipn]

        @payment.paypal_txn_type = params[:txn_type]
        @payment.paypal_txn_id = params[:txn_id]
        @payment.paypal_payment_date = params[:payment_date]

        @payment.paypal_payment_status = params[:payment_status]
        @payment.paypal_reason_code = params[:reason_code]
        @payment.paypal_payment_type = params[:payment_type]

        @payment.paypal_mc_currency = params[:mc_currency]
        @payment.paypal_mc_fee = params[:mc_fee]
        @payment.paypal_mc_gross = params[:mc_gross]

        @payment.paypal_residence_country = params[:residence_country]
        
        
        if params[:charset] == "windows-1252"
          
        else
          @payment.paypal_last_name = params[:last_name]
          @payment.paypal_first_name = params[:first_name]
          @payment.paypal_payer_email = params[:payer_email]
        end
        @payment.paypal_payer_id = params[:payer_id]
        @payment.paypal_payer_status = params[:payer_status]

        @payment.paypal_receiver_id = params[:receiver_id]
        @payment.paypal_receiver_email = params[:receiver_email]

        @payment.paypal_protection_eligibility = params[:protection_eligibility]
        @payment.paypal_ipn_track_id = params[:ipn_track_id]
        
        
        update_paypal_infos()
      
        
        
        
        
        
        
        
        
      else
        
      end
    render :inline => "test"
  end
  
  
  
  #------
  
  
  
  
  
  
  
  
  
  protected
  
    def update_ogone_infos
    
      @check = OgoneRails::CheckAuth.new( request )
    
      if @check.valid?
    
          @payment = Payment.find_by_token(params[:orderID])
        
          
          
    
          ####
          @payment.payment_type_id = 1
          @payment.amount = params[:amount].to_f
        
          @payment.ogone_payid = params[:PAYID]
          @payment.ogone_pm = params[:PM]
          @payment.ogone_status = params[:STATUS]
          @payment.ogone_acceptance = params[:ACCEPTANCE]
          @payment.ogone_cardno = params[:CARDNO]
          @payment.ogone_ed = params[:ED]
          @payment.ogone_cn = params[:CN]
          @payment.ogone_trxdate = params[:TRXDATE]
          @payment.ogone_ncerror = params[:NCERROR]
          @payment.ogone_brand = params[:BRAND]
          @payment.ogone_subbrand = params[:SUBBRAND]
          @payment.ogone_eci = params[:ECI]
          @payment.ogone_ip = params[:IP]
          @payment.ogone_alias = params[:ALIAS]
          @payment.ogone_cb_expiration = Date.parse(params[:ED][2..3].to_s+"/"+params[:ED][0..1].to_s+"/01") if params[:ED]
        
        
        
        
    
          
    
          if params["STATUS"].to_i == 9
            if !@payment.paid
              @payment.paid_at = Time.now
              
      
              
              @payment.paid = true
           
             
            end
      
          else
            @payment.paid = false
          
          end
         
          @payment.save
          
          if @payment.paid and @payment.element
            
            @payment.element.after_paid
            
          end
          
        
        
        
        end
    
    
    end
    
    
    def update_paypal_infos
    
      if params[:payment_status] == "Completed"
        if !@order.paid
          @payment.paid_at = Time.now
          
          @order.paid_at = @payment.paid_at
          
          @order.paid = true
       
          if @order.recurrent
            
            @order = true
            
            DonateTransactionsMails.general("fr", "confirmation_paypal_rec", @order).deliver
          else
            @gen_recu = true
            DonateTransactionsMails.general("fr", "confirmation_paypal", @order).deliver
          end
          @order.check_newsletter
          
        end
  
      else
        @order.paid = false
      
      end
      @order.completed_finish = true
      
      @payment.save
      @order.tr_payment_ok = @payment if @order.paid
      @order.save
      
      
      
      if @generate_recurrent
        
        @order.create_recurrent_payment
        @order.generated_recurrent_payment.generate_infos
        
      
      end
      
      if @gen_recu
        @order.generate_recu
      end
    
    
    
    end
    
    
    
  
end