# -*- 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 admin_space
    if params[:offre].to_s == "true"
      @admin_space = "ventes"
    else
      @admin_space = "clients"
    end

  end


  def index
    PCustomer.where(:enabled => true).update_all(:disabled_raison => "")

    params[:search] = params[:search] || {}

    @p_customers = PCustomer
    @p_customers = @p_customers.includes(:particular).includes(:p_commercial)
    @p_customers = sort_by_sorting(@p_customers)

    if true
      @fav_p_customers = PCustomer.where(:fav => true).order(:name).all



      if params[:p_customer_ids].to_s != ""
        @p_customers = @p_customers.where(:id => params[:p_customer_ids])
      end

      if params[:search][:enabled].to_s == "Oui"
        @p_customers = @p_customers.where(:enabled => true)
      elsif params[:search][:enabled].to_s == "Non"
        @p_customers = @p_customers.where(:enabled => false)
      end


      if params[:search][:disabled_raison].to_s != ""
        @p_customers = @p_customers.where(:disabled_raison => params[:search][:disabled_raison].to_s)
     end



      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





      if params[:encours_min].to_s != ""
        @p_customers = @p_customers.where("cache_encours_th >= ?", params[:encours_min])
      end

      if params[:encours_max].to_s != ""
        @p_customers = @p_customers.where("cache_encours_th <= ?", params[:encours_max])
      end

      if params[:ca_min].to_s != ""
        @p_customers = @p_customers.where("cache_ca >= ?", params[:ca_min])
      end

      if params[:ca_max].to_s != ""
        @p_customers = @p_customers.where("cache_ca <= ?", params[:ca_max])
      end

      if params[:search][:p_customer_cat_id].to_s != ""
        if params[:search][:p_customer_cat_id].to_s == "null"
          @p_customers = @p_customers.where(:p_customer_cat_id => nil)
        else
          @p_customers = @p_customers.where(:p_customer_cat_id => params[:search][:p_customer_cat_id])
        end
      end

      if params[:search][:p_commercial_id].to_s != ""
        if params[:search][:p_commercial_id].to_s == "null"
          @p_customers = @p_customers.where(:p_commercial_id => nil)
        else
          @p_customers = @p_customers.where(:p_commercial_id => params[:search][:p_commercial_id])
        end
      end




      if current_admin.p_commercial
        @p_customers = @p_customers.where(:p_commercial_id => current_admin.p_commercial.id )
      end


      @p_customers = @p_customers.distinct
      #@p_customers = @p_customers.limit(50)



      respond_to do |format|
        format.html{

          params[:search][:per_page] = params[:search][:per_page] || 50
      		per_page = params[:search][:per_page]
      		page = (params[:page] and params[:page] != "") ? params[:page] : 1
      		@all_p_customers = @p_customers
          @p_customers = @p_customers.page(page).per(per_page)

        }

        format.csv {
            @headers = []
            @columns = []
            PCustomer.qi_table_order.each do |key, value|

              if value.instance_of? Hash
                name = value[:name]
              else
                name = value
              end

              if name != "Actions"
                @headers << name.to_s
                @columns << key
              end

            end



            xlsx_package = Axlsx::Package.new
              wb = xlsx_package.workbook
              wb.add_worksheet(name: "import") do |sheet|
                sheet.add_row @headers

                @p_customers.each do |p_customer|
                  line = []

                  @columns.each do |column|

                    if (p_customer.respond_to?("csv_"+column.to_s))
                      line << p_customer.send("csv_"+column.to_s)
                    elsif (p_customer.respond_to?(column))
                      if p_customer.send(column.to_s).class.to_s == "BigDecimal"
                        line << p_customer.send(column.to_s).to_s.gsub('.', ',')
                      else
                        line << p_customer.send(column.to_s)
                      end
                    else
                      line << column.to_s
                    end

                  end


                  sheet.add_row line, types: line.map{|t| cell_type_from_value(t)}
                end


              end

              @final_file = "#{Rails.root}/private_medias/export-clients-#{Time.now.to_s.to_slug}.xlsx"


              xlsx_package.serialize(@final_file)


              send_file @final_file



          }

      end

    end
  end

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

  end

  def new


		@p_customer = PCustomer.new(:comptant => true)
    @p_customer.p_payment_type_id = 41
    @p_customer.comptant = false
    @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 !current_admin.has_permission?("customers-activer-desactiver")
      @p_customer.enabled = false
      @p_customer.disabled_raison = "Pas encore vérifié"
    end

    if current_admin.p_commercial
      @p_customer.p_commercial = current_admin.p_commercial
    end

    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, member_label: va.show_name_extend }}.to_json( :only => [:id, :show_name, :member_label] ) }
    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