class Public::ProductOrdersController < ApplicationController

	layout "public"


  
  before_filter :cart_not_empty, :only => [:particulars, :particulars_save, :select_payment ,:select_payment_save, :select_fdp, :select_fdp_save ]
  
  skip_before_filter :verify_authenticity_token, :only => [:payplug_ipn]
  
  
  def index
    if params[:reseaux_id]
      @reseaux_layout = true
      @reseaux = current_customer.own_reseauxes.find(params[:reseaux_id]) 
      @reseaux_chief_layout = true
    end
    @product_orders = @reseaux.product_orders.where(:completed_finish => true).order("created_at DESC")
		
    
  end
  
  def show
    if params[:reseaux_id]
      @reseaux_layout = true
      @reseaux = current_customer.own_reseauxes.find(params[:reseaux_id]) 
      @reseaux_chief_layout = true
    end
    @product_order = @reseaux.product_orders.where(:completed_finish => true).find(params[:id])
    
  end
  
  def get_reseaux
    if session[:reseaux_id]
      @reseaux = current_customer.reseauxes.find(session[:reseaux_id])
      @reseaux_layout = true
    end
  end
  
  def my_cart
    get_reseaux
    
    if !@product_order.reseaux
      @product_order.reseaux = @reseaux
      @product_order.save
    end
    
  end

  def vourcher
    code = params[:vourcher_code]
    if vc = VourcherCode.find_by_slug( code)
      @product_order.vourcher_code = vc
      @product_order.save
      redirect_to :back
    else
      redirect_to :back, :notice => "Le code indiqué n'est pas valide"
      
      
    end
    
  end

  def particulars
    get_reseaux
    @product_order = ProductOrder.find(session[:product_order_id])
    if @product_order.paid
      redirect_to new_public_product_order_path(:paid => true)
    else
      @product_order.customer = current_customer
      @product_order.customer.particular_bill.skip_validation = true
      @product_order.customer.particular_send.skip_validation = true

      @product_order.save

      @product_order.customer.particular_bill.skip_validation = false
      @product_order.product_order_payment_type_ok_id = 3 if !@product_order.product_order_payment_type_ok_id?

    end

  end

  def particulars_save
    get_reseaux
    @product_order = ProductOrder.find(session[:product_order_id])
    @product_order.customer.particular_bill.skip_validation = false
    @product_order.customer.particular_bill.skip_email = true
    
    if !@product_order.particular_idem
      @product_order.customer.particular_send.skip_validation = false
      @product_order.customer.particular_send.skip_email = true
    end
    
    if @product_order.update_attributes(params.require(:product_order).permit!)

      @product_order.particular_bill = @product_order.customer.particular_bill.dup
      
      @product_order.particular_idem = @product_order.customer.particular_idem
      if @product_order.particular_idem
        @product_order.particular_send = @product_order.customer.particular_bill.dup
      else
        
        @product_order.customer.particular_send.skip_validation = false
        @product_order.customer.particular_send.skip_email = true
        
        @product_order.particular_send = @product_order.customer.particular_send.dup
      end
      @product_order.save
      
			@product_order.archive_now
      
      
      redirect_to select_fdp_public_product_orders_path()
      
      
      
      

    else

      render :action => :particulars

    end

  end
  
  
  def select_fdp
    get_reseaux
    @product_order = ProductOrder.find(session[:product_order_id])
    @product_order.force_fdp_validation = true
    redirect_to select_fdp_save_public_product_orders_path

  end
  
  
  def select_fdp_save
    get_reseaux
    @product_order = ProductOrder.find(session[:product_order_id])
    @product_order.force_fdp_validation = true
    @product_order.product_fdp_id = 1
    if @product_order.save
    #if @product_order.update_attributes(params.require(:product_order).permit!)
       

        redirect_to select_payment_public_product_orders_path()

      
    else
      render :action => :select_fdp
    end
    
    
    
    
    
  end
  
  def select_payment
    get_reseaux
    if params[:orderID]
      flash.now[:error] =  "Votre tentative de paiement par carte bancaire a échouée, ou vous avez annulé votre paiement, merci de bien vouloir essayer de nouveau ou changer de mode de paiement."
    end
    @product_order = ProductOrder.find(session[:product_order_id])
    @product_order.archive_now
    if !@product_order.product_order_payment_type_ok_id?
      @product_order.product_order_payment_type_ok_id = 2
    end
    @product_order.force_payment = true
    

  end
  
  
  
  def cart_not_empty
    get_reseaux
    @product_order = ProductOrder.find(session[:product_order_id])
    
    if @product_order.product_order_products.count == 0
      redirect_to public_my_cart_path
    end
      
  end
  
  def select_payment_save
    
        get_reseaux
    @product_order = ProductOrder.find(session[:product_order_id])
   
    
      @product_order.archive_now
      @product_order.force_payment
      @product_order.force_fdp_validation = true
      @product_order.force_cgv_validation = true
    
    
    
      if @product_order.update_attributes(params.require(:product_order).permit!)
       
        
        if @product_order.product_order_payment_type_ok_id == 3
          #redirect_to paid_by_ogone_public_product_orders_path()
          
          @payment = @product_order.payments.create(:amount => @product_order.archived_total_ttc, :payment_type_id => 1, :customer_id => current_customer.id)
          session[:payment_id] = @payment.id
          redirect_to paid_by_ogone_public_payment_path(@payment)
          
          
        else
          
          if [10, 1, 2, 4].include?(@product_order.product_order_payment_type_ok_id)
            
            @product_order_payment = ProductOrderPayment.create(:product_order_payment_type_id => @product_order.product_order_payment_type_ok_id)
            
            @product_order.product_order_payments << @product_order_payment
            
            @product_order.product_order_payment_ok = @product_order_payment
            
          end
          

          @product_order.completed_finish = true
        
          @product_order.save
          @product_order.after_paid_old
          
          #@product_order.generate_bl_number
          
          
          puts @product_order.bl_number
       
          ProductOrdersMails.confirmation_cheque(@product_order).deliver
          session[:product_order_id] = nil 
          redirect_to payment_instructions_public_product_order_path(@product_order.token)

        end
      else
        render :action => :select_payment
      end
    

    
    
    
    
  end
  
  
  def payment_instructions
    get_reseaux
    @product_order_ar = ProductOrder.find_by_token(params[:id])
  end
  
  
  
  def payplug_ipn
    
    
    payplug_retrieve_payement(params[:id])
    
    
    response = @response
    
    puts response["metadata"]
    @product_order = ProductOrder.find_by_token(response["metadata"]["product_order_id"])
    @product_order_payment = ProductOrderPayment.find_by_token(response["metadata"]["product_order_payment_id"])
    
    @product_order_payment.product_order_payment_type_id = 3
    @product_order_payment.amount = response["amount"].to_i*0.01
    @product_order_payment.payplug_payment_id = response["id"]
    
    if response["card"]
      @product_order_payment.payplug_card_id = response["card"]["id"]
      @product_order_payment.payplug_card_expiry_month = response["card"]["exp_month"]
      @product_order_payment.payplug_card_expiry_year = response["card"]["exp_year"]
      @product_order_payment.payplug_card_last_number = response["card"]["last4"]
      
    end
    
    if response["is_paid"] == true || response["is_paid"] == "true"
      
      @product_order_payment.paid_at = Time.now
      
      @product_order.paid = true
      @product_order.after_paid

      ProductOrdersMails.confirmation_cb(@product_order).deliver

      
    else
      @product_order.paid = false
    end
    @product_order.product_order_payment_ok = @product_order_payment
    @product_order.completed_finish = true
    @product_order.save
    @product_order_payment.save
    
    
    
    
    render :inline => "ok"
  end
    
    
  
  def paid_by_payplug
    @product_order = ProductOrder.find(session[:product_order_id])
    
    
    
    if @product_order.paid
      redirect_to select_payment_public_order_products_path(@product_order.id)
    else
      
      @product_order_payment = ProductOrderPayment.create(:product_order_payment_type_id => 3)
      @product_order.product_order_payments << @product_order_payment
      
      session[:product_order_payment_token] = @product_order_payment.token
      
      puts "AAAAAAAAAAAAAA"
      
      puts @product_order.particular_bill
      
      puts "AAAAAAAAAAAAAA"
      options = {
        :amount => @product_order.total_ttc.to_i,
        :email => @product_order.customer.email ,
        :first_name => @product_order.particular_bill.firstname,
        :last_name => @product_order.particular_bill.name,
        :return_url => "http://#{HOSTNAME}"+paid_by_payplug_confirm_public_product_orders_path(:token => @product_order_payment.token),
        :cancel_url => "http://#{HOSTNAME}"+select_payment_public_product_orders_path(),
        :notification_url  => "http://#{HOSTNAME}"+payplug_ipn_public_product_orders_path(),
        :product_order_id => @product_order.token,
        :product_order_payment_id => @product_order_payment.token,
        :save_card  => false,

      }
  
      payplug_init_payement(options)

      response = @new_payplug_payment

      @product_order_payment.payplug_payment_id = response["id"]
      @product_order_payment.save
      @product_order.save
    
      redirect_to response["hosted_payment"]["payment_url"]

    
    end
    
  end

  
  
  
  def paid_by_ogone
    
    @product_order = ProductOrder.find(session[:product_order_id])
    
    if @product_order.paid
      redirect_to public_my_cart_path
    else
      
      @product_order_payment = ProductOrderPayment.create(:product_order_payment_type_id => 3)
      @product_order.product_order_payments << @product_order_payment
      
      session[:product_order_payment_token] = @product_order_payment.token
      
    
      @ogone_options = {
        :amount => @product_order.total_ttc,
        :accept_url => "http://#{HOSTNAME}"+paid_by_ogone_confirm_public_product_orders_path(),
        :decline_url => "http://#{HOSTNAME}"+select_payment_public_product_orders_path(),
        :exception_url => "http://#{HOSTNAME}"+select_payment_public_product_orders_path(),
        :cancel_url => "http://#{HOSTNAME}"+select_payment_public_product_orders_path(),    
        :orderid =>  @product_order_payment.token,
        :PARAMVAR => "ogoneipnpo",
        :PSPID => OgoneRails::pspid,
        :currency => OgoneRails::currency,
        :language => OgoneRails::language,
      
      }
    
     

    end
    
  end
  
  
  def paid_by_payplug_confirm
    
  
    @product_order_payment = ProductOrderPayment.find_by_token(params[:token])
    @product_order_ar = @product_order_payment.product_order
    
    payplug_retrieve_payement @product_order_payment.payplug_payment_id
    
    if @response and @response["is_paid"] == true# || response["is_paid"] == "true"
        @paid = true
        
        @product_order = ProductOrder.new
        session[:product_order_id] = nil
    else
        redirect_to select_payment_public_product_orders_path(:paid_fail => 1) 
    
    end
  
  
  end
  
  
  
  def paid_by_ogone_confirm
    
    @product_order = ProductOrder.find(session[:product_order_id])
    
    session[:product_order_id] = nil if @product_order.paid

    
    
  end
  
  
  def ogone_ipn
    
    update_ogone_infos()
    
    render :inline => "ok"
    
  end
  
  protected
  
    def update_ogone_infos
    
      @check = OgoneRails::CheckAuth.new( request )
    
      if @check.valid?
    
        @product_order_payment = ProductOrderPayment.find_by_token(params[:orderID])
      
        @product_order = @product_order_payment.product_order

          @product_order_payment.product_order_payment_type_id = 3
          @product_order_payment.amount = params[:amount].to_f
        
          @product_order_payment.ogone_payid = params[:PAYID]
          @product_order_payment.ogone_pm = params[:PM]
          @product_order_payment.ogone_status = params[:STATUS]
          @product_order_payment.ogone_acceptance = params[:ACCEPTANCE]
          @product_order_payment.ogone_cardno = params[:CARDNO]
          @product_order_payment.ogone_ed = params[:ED]
          @product_order_payment.ogone_cn = params[:CN]
          @product_order_payment.ogone_trxdate = params[:TRXDATE]
          @product_order_payment.ogone_ncerror = params[:NCERROR]
          @product_order_payment.ogone_brand = params[:BRAND]
          @product_order_payment.ogone_subbrand = params[:SUBBRAND]
          @product_order_payment.ogone_eci = params[:ECI]
          @product_order_payment.ogone_ip = params[:IP]
          @product_order_payment.ogone_alias = params[:ALIAS]
          @product_order_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 !@product_order.paid
              
         
              @product_order_payment.paid_at = Time.now
              
              @product_order.paid_at = @product_order_payment.paid_at
              
              @product_order.paid = true
              
              
              
                #@gen_recu = true
                ProductOrdersMails.confirmation_cb(@product_order).deliver
              
              #@product_order.check_newsletter
              
            end
      
          else
            @product_order.paid = false
          
          end
          @product_order.completed_finish = true
          
          @product_order_payment.save
          @product_order.product_order_payment_ok = @product_order_payment if @product_order.paid
          @product_order.customer.particular_bill.skip_email = true
          @product_order.customer.particular_send.skip_email = true
          @product_order.save(:validate => false)
          
          @product_order.after_paid
          

          
          
       
          if @gen_recu
            #@product_order.generate_recu
          end
        
        
        
        
        end
    
    
    end
    
    

end
