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

class Admin::PPaymentsController < ApplicationController
  layout "admin"
  before_action :auth_admin, :except => [:paid_by_ogone_confirm]

  before_action :admin_space
  
  def relances
    params[:day] = 0 if params[:day].to_s == ""
    
    params[:day] =  params[:day].to_i
    params[:importeds] = "0" if params[:importeds].to_s == ""
    
    

    
    
    
    @relances = true
    
    @p_documents = PDocument.where(:p_document_type_id => 4, :paid => false, :i_archive => false).where("echeance_date <= ?", (Time.now - params[:day].day).end_of_day).order("DATEDIFF(NOW(), echeance_date) ASC,created_at DESC")
    
    if params[:importeds] == "0"
      @p_documents = @p_documents.where(:imported => false)
    end
    
    @p_document_bruts = @p_documents
    
		per_page = (params[:per_page] and params[:per_page] != "") ? params[:per_page] : 50
		page = (params[:page] and params[:page] != "") ? params[:page] : 1 
		@p_documents = @p_documents.page(page).per(per_page)
    
  end
  
  
  
  def import_lettrage
    if true
      require 'csv'    

      csv_text = File.read("#{Rails.root}/import_csv/lettrage.csv", :encoding => 'UTF-8')
      @csv = CSV.parse(csv_text, :headers => true, :col_sep => ";")
      
      
    end
  end
  
  def import
    if false
      if params[:csv_file]
        @file = params[:csv_file]
    
        require 'csv'    

        csv_text = @file.tempfile.read.force_encoding('ISO-8859-1').encode('utf-8')
      
        @csv = CSV.parse(csv_text, :headers => true, :col_sep => ";")
      end
      
    end
    
  end
  
  
  def import_arrondis
    
    if false
      
      
      @file = params[:csv_file]
    
      require 'csv'    

      csv_text = File.read("#{Rails.root}/import_csv/reglements3.csv", :encoding => 'UTF-8')
      @csv = CSV.parse(csv_text, :headers => true, :col_sep => ";")
    end
    
  end
  
  
  
  def admin_space
    @admin_space = "payments"
  end
  
  def index
    @p_payments = PPayment.includes(:p_payment_type)

    params[:p_payment_type_ids] = params[:p_payment_type_ids] || []
    @p_payments = @p_payments.where(:p_payment_type_id => params[:p_payment_type_ids]) if params[:p_payment_type_ids].size > 0
    
    date_regex = /^(0[1-9]|[12][0-9]|3[01])[\/](0[1-9]|1[012])[\/](19|20)\d\d$/i 
    
    
    params[:start] = Date.today.beginning_of_month.strftime('%d/%m/%Y') if !params[:start]
    
    if params[:start] and params[:start] =~ date_regex
      @start = Date.parse(params[:start]).beginning_of_day 
      params[:start]= @start.strftime('%d/%m/%Y')
    else
      @start = nil
    end
    
    
    
    if true
      params[:stop] = Date.today.end_of_month.strftime('%d/%m/%Y') if !params[:stop]

    
      if params[:stop].to_s != "" # and params[:stop] =~ date_regex
        @stop = Date.parse(params[:stop]).end_of_day 
        
        params[:stop]= @stop.strftime('%d/%m/%Y')
        
        
      else
         @stop = nil
      end
    
    end
    

    
    if params[:amount_min].to_s != ""
      @p_payments = @p_payments.where("amount >= ?", params[:amount_min])
    end
    
    if params[:amount_max].to_s != ""
      @p_payments = @p_payments.where("amount <= ?", params[:amount_max])
    end
    
    
    @p_payments = @p_payments.where("p_payments.created_at >= ?", @start) if @start

    @p_payments = @p_payments.where("p_payments.created_at <= ?", @stop.end_of_day) if @stop
    
    
    @p_payments = sort_by_sorting(@p_payments, "created_at DESC")
    
    per_page = (params[:search][:per_page] and params[:search][:per_page] != "") ? params[:search][:per_page] : 50
    page = (params[:search][:page] and params[:search][:page] != "") ? params[:search][:page] : 1 
    @p_payments = @p_payments.page(page).per(per_page)
    
   
  end

  def show
    @p_payment = PPayment.find(params[:id])

  end

  def new
    
    
		@p_payment = PPayment.new(:p_payment_type_id => 2, :paid => true)
    
    @p_payment.p_customer = PCustomer.find(params[:p_customer_id]) if params[:p_customer_id]

  end

 

  def edit
  
    
    @p_payment = PPayment.find(params[:id])
  end

  def create
    @p_payment = PPayment.new(params.require(:p_payment).permit!)


    if @p_payment.save
     #@p_payments = PPayment.all
      
    else
      render action: "new"
 
    end

  end


  def update
    @p_payment = PPayment.find(params[:id])


    if @p_payment.update_attributes(params.require(:p_payment).permit!)
      
       #@p_payments = PPayment.order("created_at ASC").all
    else
     render action: "edit" 
      
    end
      
  end


  def destroy
    @p_payment = PPayment.find(params[:id])
    @p_payment.destroy
    
    
  end
  
  def paid_by_ogone_confirm
    @check = OgoneRails::CheckAuth.new( request )
  
    if @check.valid?
  
      @p_payment = PPayment.find_by_token(params[:orderID])
      
      
        
    end
    
    if true #!@payment.paid
      update_ogone_infos()
      
    end
  
    

    
  end
  
  
  def update_ogone_infos

    @check = OgoneRails::CheckAuth.new( request )
  
    if @check.valid?
  
        @p_payment = PPayment.find_by_token(params[:orderID])
      
        
        
  
        ####
        @p_payment.p_payment_type_id = 1
        @p_payment.amount = params[:amount].to_f
      
        @p_payment.ogone_payid = params[:PAYID]
        @p_payment.ogone_pm = params[:PM]
        @p_payment.ogone_status = params[:STATUS]
        @p_payment.ogone_acceptance = params[:ACCEPTANCE]
        @p_payment.ogone_cardno = params[:CARDNO]
        @p_payment.ogone_ed = params[:ED]
        @p_payment.ogone_cn = params[:CN]
        @p_payment.ogone_trxdate = params[:TRXDATE]
        @p_payment.ogone_ncerror = params[:NCERROR]
        @p_payment.ogone_brand = params[:BRAND]
        @p_payment.ogone_subbrand = params[:SUBBRAND]
        @p_payment.ogone_eci = params[:ECI]
        @p_payment.ogone_ip = params[:IP]
        @p_payment.ogone_alias = params[:ALIAS]
        @p_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 true #!@p_payment.paid
            @p_payment.paid_at = Time.now
            
    
            
            @p_payment.paid = true
         
           
          end
    
        else
          @p_payment.paid = false
        
        end
       
        @p_payment.save
        
      
      
      end
      
      
      render :layout => "public"
  
  
  end
  
  
  
  
end
