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

class Admin::PCustomersController < ApplicationController
  layout "admin"
  before_action :auth_admin, :except => :etat
  
  before_action :admin_space
  
  
  def archive_import
    @p_customer = PCustomer.find(params[:id])
  end
  
  
  
  def import
    if true
      
      @file = params[:csv_file]
    
      require 'csv'    

      csv_text = File.read("#{Rails.root}/import_csv/clients5.csv").force_encoding('ISO-8859-1').encode('utf-8')
      @csv = CSV.parse(csv_text, :headers => true, :col_sep => ";")
    end
    
  end
  
  
  def import_cat
    if true
      
      @file = params[:csv_file]
    
      require 'csv'    

      csv_text = File.read("#{Rails.root}/import_csv/cat-clients.csv", :encoding => 'UTF-8')
      @csv = CSV.parse(csv_text, :headers => true, :col_sep => ";")
    end
    
  end
  
  
  
  
  def admin_space
    if params[:offre].to_s == "true"
      @admin_space = "ventes"
    else
      @admin_space = "clients"
    end
    
  end
  
  
  def index
    
    
    
    
    @p_customers = PCustomer #.joins(:p_documents).all
    @p_customers = @p_customers.includes(:particular)
  
    
    if true
   
      
      
      if params[:code].to_s != ""
        @p_customers = @p_customers.where("p_customers.code LIKE ?","#{params[:code]}%")
      end
      
        if params[:name].to_s != ""
          @p_customers = @p_customers.joins(:particulars).where("p_customers.code LIKE ? or particulars.organisation LIKE ? or particulars.name LIKE ? or particulars.firstname LIKE ?","%#{params[:name]}%", "%#{params[:name]}%", "%#{params[:name]}%", "%#{params[:name]}%")
        end
      
        if params[:city].to_s != ""
          @p_customers = @p_customers.joins(:particulars).where("particulars.cp LIKE ? or particulars.city LIKE ?","%#{params[:city]}%", "%#{params[:city]}%")
        end
        
        if params[:tel].to_s != ""
          @p_customers = @p_customers.joins(:particulars).joins("INNER JOIN `p_contacts` AS `p_contacts` ON ((`p_contacts`.`contactable_id` = `p_customers`.`id` AND `p_contacts`.`contactable_type` = 'PCustomer') OR (`p_contacts`.`contactable_id` = `particulars`.`id` AND `p_contacts`.`contactable_type` = 'Particular'))").where("p_contacts.tel LIKE ? or p_contacts.tel LIKE ?","%#{params[:tel]}%","%#{params[:tel]}%")
        end
      
        if params[:document_number].to_s != ""
          @p_customers = @p_customers.joins(:p_documents).where("p_documents.d_number LIKE ?","%#{params[:document_number]}%")
        end
        #FP38057504
        
      
      
      
      
      boolean_search @p_customers ,:comptant
          
      collection_search @p_customers ,:p_payment_type_id
      
      collection_search @p_customers ,:accounting_zone_id
      
          
      
      @p_customers = @p_customers.distinct
  		
      @p_customers = sort_by_sorting(@p_customers, "created_at 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 
      		@p_customers = @p_customers.page(page).per(per_page)
      
        }
      end
      
      
    end
  end

  def show
    @p_customer = PCustomer.find(params[:id])

  end

  def new
    
    
		@p_customer = PCustomer.new()
    @p_customer.p_payment_type_id = 41
    @p_customer.particulars << Particular.new(:pro => true, :skip_validation => false, :open_range_ids => OpenRange.all.ids)

  end

 

  def edit
  
    
    @p_customer = PCustomer.find(params[:id])
  end

  def create
    @p_customer = PCustomer.new(params.require(:p_customer).permit!)


    if @p_customer.save
      redirect_to [:admin, @p_customer]
    else
      #@p_customer.code = nil
      render action: "new"
 
    end

  end


  def update
    @p_customer = PCustomer.find(params[:id])


    if @p_customer.update_attributes(params.require(:p_customer).permit!)
      redirect_to [:admin, @p_customer]
    else
     render action: "edit" 
      
    end
      
  end


  def destroy
    @p_customer = PCustomer.find(params[:id])
    @p_customer.destroy
    
    
  end
  
  
  def autocomplete
    @p_customers = PCustomer.for_search(params[:search]) #.limit(50)
    
    respond_to do |format|
        format.json { render json: @p_customers.map {|va| { id: va.id, show_name: va.show_name_extend }}.to_json( :only => [:id, :show_name] ) }
    end
  end
  
  def autocomplete_apercu
    @p_customer = PCustomer.find(params[:id])
    
  end
  
  
  def etat
    @p_customer = PCustomer.find(params[:id]) if params[:id]
  
  
  
  
  
  
    date_regex = /^(0[1-9]|[12][0-9]|3[01])[\/](0[1-9]|1[012])[\/](19|20)\d\d$/i 
    
    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 params[:stop] and params[:stop] =~ date_regex
			@stop = Date.parse(params[:stop]).end_of_day 
			params[:stop]= @stop.strftime('%d/%m/%Y')
	  else
		 	@stop = nil
		end
    
    if !@p_customer and !@start
			@start = Date.today.beginning_of_year
			params[:start]= @start.strftime('%d/%m/%Y')
    end
    
    
    
    if @p_customer
      @p_compta_elements = @p_customer.p_compta_elements.order("date DESC")
    else
      @p_compta_elements = PComptaElement.order("date DESC")
    end
    
    @p_compta_elements = @p_compta_elements.where("date >= ?", @start) if @start

    @p_compta_elements = @p_compta_elements.where("date < ?", @stop.end_of_day) if @stop
    params[:ok] = "0" if params[:ok].to_s == "" and !@p_customer
    if params[:ok].to_s != ""
      if params[:ok] == "1"
        @p_compta_elements = @p_compta_elements.where(:solde => true) 
      else
        @p_compta_elements = @p_compta_elements.where(:solde => false) 
      end
    end
    
    
    
    
    
    
    
    params[:inline] = true
    if params[:pdf] == "true"
      
      require 'posix/spawn'
      
      doc_number = ""+params[:id].to_s
      #url = adr_admin_p_ship_tour_path(:id => params[:id],:html => true)
      url = url_for( request.query_parameters.merge({html: true, pdf: false, :only_path => true}))
      puts "AAA"
      puts url
      @final_file = "#{Rails.root}/pdf/p_documents/etat-#{doc_number}.pdf"
      @temp_file = "#{Rails.root}/pdf/p_documents/etat-#{doc_number}-temp.pdf"
    
    
    
    
      url = (Rails.env.development? ? "http://localhost:4000" : "http://3p.quartz.xyz").to_s+url
      puts url
      pdf = "pdfportrait"
      command = "node #{pdf}.js #{Shellwords.escape(url)} #{Shellwords.escape(@temp_file)}"
      puts command
      system(command)
      
      
      ::POSIX::Spawn::Child.new 'pdftk', @temp_file, 'stamp', "#{Rails.root}/pdf_stamp/en-tete.pdf", 'output',  @final_file
      
      @data_to_send = File.open( @final_file).read
     
    
      send_data @data_to_send, :filename =>"#{doc_number}.pdf" , :type => 'application/pdf',:disposition => (params[:inline] ? 'inline' : "attachment")
    else
       render :layout => false if params[:html]
    end
    
    
    
    
    
    
    
    
  end
  
  
end
