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

class Admin::PriceDocumentsController < ApplicationController
  layout "admin"
  before_action :auth_admin, :except => [:paid_by_ogone, :print]

  before_action :admin_space, :except => :print
  
  def admin_space
    @admin_space = "documents"
  end
  
  def search_to_affect
    @p_customer = PCustomer.where(:id => params[:p_customer_id]).first
  end
  
  def index
     
    if params[:price_document_type_ids]
      params[:price_document_type_ids] = params[:price_document_type_ids]
    else
      params[:price_document_type_ids] = PriceDocumentType.all.map{|pdt| pdt.id.to_s}
      puts params[:price_document_type_ids]
      #fgfgddg
    end
    
    if @p_customer
      @price_documents = @p_customer.price_documents
    else
      @price_documents = PriceDocument
    end

    
    @price_documents = @price_documents.where(:price_document_type_id => params[:price_document_type_ids]) if params[:price_document_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
      #fsfds = sdfsfd
      @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
    
    
    @price_documents = @price_documents.where("date >= ?", @start) if @start

    @price_documents = @price_documents.where("date <= ?", @stop.end_of_day) if @stop
    
    @price_documents = sort_by_sorting(@price_documents, "date DESC")

    respond_to do |format|
      format.html{
      
        params[:search][:per_page] = params[:search][:per_page] || 100
    		per_page = params[:search][:per_page]
    		page = (params[:page] and params[:page] != "") ? params[:page] : 1 
    		@price_documents = @price_documents.page(page).per(per_page)
      
      }
    end
    

  end

  def show
    @price_document = PriceDocument.find(params[:id])

  end

  def new
    if !params[:to_dup]
      @price_document = PriceDocument.new(:p_customer_id => params[:p_customer_id], :date => Date.today)
      @price_document.price_document_type = PriceDocumentType.where(:label => "Facture").first
      @price_document.price_line_block = PriceLineBlock.new(:p_customer_id => params[:p_customer_id])
  
    else
      @past_price_document = PriceDocument.find(params[:to_dup])
      
      @price_document = PriceDocument.new(:date => Date.today)
     
      to_dup = [:s_project_id, :p_commercial_id, :p_customer_id, :particular_bill_id, :price_document_type_id, :libelle]
          
      to_dup.each do |todup|
        @price_document[todup] = @past_price_document.send(todup.to_s)
      end
      
      @price_document.price_line_block = PriceLineBlock.new()
      
      to_dup = [:p_commercial_id, :p_customer_id, :particular_bill_id,:ct_gen_discount_percent, :particular_bill_id, :particular_send_id, :customer_ref]
          
      to_dup.each do |todup|
        @price_document.price_line_block[todup] = @past_price_document.price_line_block.send(todup.to_s)
      end
      
      @past_price_document.price_line_block.price_lines.each do |past_price_line|

        price_line = @price_document.price_line_block.price_lines.new
        
        to_dup = [:p_product_ref_id, :ct_title, :ct_description, :ct_u_price_ht, :qte, :ct_tva_account_id, :ct_p_product_cat_id]
          
        to_dup.each do |todup|
          price_line[todup] = past_price_line.send(todup.to_s)
        end
        
        
        
      end
        
      
    end
    
    
    if @price_document.p_customer
      
      @price_document.price_line_block.p_payment_type_id = @price_document.p_customer.p_payment_type_id
      @price_document.price_line_block.ct_payment_comptant = @price_document.p_customer.comptant
      @price_document.price_line_block.ct_payment_delais = @price_document.p_customer.payment_delais
      @price_document.price_line_block.ct_payment_month_end = @price_document.p_customer.payment_fin_de_mois
      
      
      
    end
    
  
  
  end

  def edit
    @price_document = PriceDocument.find(params[:id])
    
  end

  def create
    @price_document = PriceDocument.new(params.require(:price_document).permit!)

    if @price_document.save
      redirect_to action: "index"
    else
      render action: "new"
 
    end

  end


  def update
    @price_document = PriceDocument.find(params[:id])


    if @price_document.update_attributes(params.require(:price_document).permit!)
      redirect_to action: "index"
    else
     render action: "edit" 
      
    end
      
  end


  def destroy
    @price_document = PriceDocument.find(params[:id])
    @price_document.destroy
    
  end
  
  
  def print
    
  

    @price_document = PriceDocument.find_by_token(params[:id])
    @element = @price_document.ref_element
    
    doc_number = @price_document.d_number
    url = print_admin_price_document_path(:id => @price_document.token, :html => true)
  
  
  
    
    params[:inline] = true
    
    if !params[:html] # and !Rails.env.development?
      
      @data_to_send = File.open(@price_document.generate_pdf).read
      
      
      
      
      
      send_data @data_to_send, :filename =>"#{doc_number}.pdf" , :type => 'application/pdf',:disposition => (params[:inline] ? 'inline' : "attachment")
      #render :inline => "y"
    
    else
      render :layout => false
    end
    
  end
  
  
  def generate_number
    @price_document = PriceDocument.find(params[:id])
    if !@price_document.d_number?
      @price_document.generate_number
      
    end
    
    redirect_to admin_price_documents_path("price_document_type_ids[]" => @price_document.price_document_type_id)
    
  end 
  
  
  def paid_by_ogone
    
    @price_document = PriceDocument.find_by_token(params[:id])
    
    
    if @price_document.to_paid_ttc > 0.0
      @p_payment = PPayment.create(:price_document_id => @price_document.id, :p_customer => @price_document.p_customer, :amount => @price_document.to_paid_ttc, :p_payment_type_id => 1, :paid_at => Time.now)
   
      #render :inline => @p_payment.errors.messages
      if false # @p_payment.paid
        render :inline => "paiement déjà enregistré"
        #redirect_to new_public_donator_transaction_path(:paid => true)
      else
      

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

      end
    
    else
      
    end
    
    render :layout => "public"
    
  end
  
  
  
  
end
