class Admin::PComptaExportsController < ApplicationController
  layout "admin"
  before_action :auth_admin

  before_action :admin_space
  
  
  
  def admin_space
    @admin_space = "payments"
  end
  
  def index
    @p_compta_exports = PComptaExport.order("id DESC").all

   
  end

  def show
    @p_compta_export = PComptaExport.find(params[:id])
    
    @p_compta_export.add_elements if !@p_compta_export.validated
    
    
    
    @headers = [
      "compte comptable","compte client","client","date","echeance","numero piece","débit","crédit"
    
    ]
  
    
    @lines = []
    
    @lines_pnm = []

    @p_compta_export.price_documents.each do |price_document|
      
      line_pnm = []
      
      line_pnm << "C"
      
      line_pnm << "9"
    
      line_pnm << ('%-7.7s' % price_document.p_customer.code)
      
      line_pnm << ('%-30.30s' % price_document.p_customer.show_name)
      
      line_pnm << ('%-59.59s' % " " )
      

      
      line_pnm << "41100000"
      line_pnm << ('%-30.30s' % (price_document.p_customer and price_document.p_customer.particular ? price_document.p_customer.particular.address_2 : " "))
      line_pnm << ('%-30.30s' % (price_document.p_customer and price_document.p_customer.particular ? price_document.p_customer.particular.address_3 : " "))
      
      line_pnm << ('%-30.30s' % (price_document.p_customer and price_document.p_customer.particular ? price_document.p_customer.particular.cp.to_s+price_document.p_customer.particular.city : " "))
      line_pnm << ('%-20.20s' % (price_document.p_customer and price_document.p_customer.particular ? price_document.p_customer.particular.tel.to_s : " "))
      line_pnm << "1"
      line_pnm << "C"
      
      
      
      @lines_pnm << line_pnm
      
      
      line = []
      line << "41100000"
      line << price_document.p_customer.code if price_document.p_customer
      line << price_document.p_customer.show_name if price_document.p_customer
      line << price_document.date.strftime("%d/%m/%Y") 
      line << price_document.payment_end_at
      line << price_document.d_number
      

      


      if price_document.tot_amount_ttc.to_f >= 0
        line << price_document.tot_amount_ttc.to_s.gsub('.', ',')
        line << ""

      else
        line << ""
        line << (price_document.tot_amount_ttc*-1).to_s.gsub('.', ',')
      
      end

      @lines << line
      
      
      
      line_pnm = []
      
      line_pnm << "M"
    
      line_pnm << "9"
    
      line_pnm << ('%-7.7s' % price_document.p_customer.code)
      line_pnm << "VE"
      line_pnm << "000"
      line_pnm << ('%-6.6s' % price_document.date.strftime("%d%m%y") )
      
      if price_document.label == "Facture"
        line_pnm << "F"
      elsif price_document.label == "Avoir"
        line_pnm << "A"
      end
      
      line_pnm << ('%-20.20s' % price_document.d_number )
      
      if price_document.tot_amount_ttc.to_f >= 0
        line_pnm << "D+"
        


      else
        line_pnm << "C+"
        
      end
      
      line_pnm << ('%12.12s' % (price_document.tot_amount_ttc.abs*100).to_i.to_s ).gsub(' ', "0")
      
      line_pnm << ('%-8.8s' % " " )
    
      line_pnm << ('%-6.6s' % price_document.payment_end_at.strftime("%d%m%y") )
      
      line_pnm << ('%-5.5s' % " " )
      
      line_pnm << ('%-5.5s' % price_document.d_number )
      
      line_pnm << ('%-20.20s' % " " )
      
      line_pnm << ('%-8.8s' % price_document.d_number )
      
      line_pnm << "EUR"
      
      
      line_pnm << "VE"
      
      line_pnm << ('%-4.4s' % " " )
      
      line_pnm << ('%-30.30s' % (price_document.d_number+ " "+price_document.p_customer.show_name.to_s) )
      
      line_pnm << ('%-2.2s' % " " )
      
      line_pnm << ('%-10.10s' % price_document.d_number )
      
   
      
      @lines_pnm << line_pnm
      
      
      
      
      
      
      
      
      

      comptes = {}
      comptes_tva = {}
      tva_rate = nil
      
      cpt_fdp = "70700200"

      
      if tva_rate = TvaRate.where(:rate => 20.0,:accounting_zone_id => price_document.price_line_block.accounting_zone_id).first
        cpt_fdp_tva = tva_rate.sale_account
      else
        cpt_fdp_tva = "TVAfdpnondefini"
      end
      
      if price_document.price_line_block.tot_fdp_ht != 0.0
        comptes[cpt_fdp] = comptes[cpt_fdp] || 0.0
        comptes[cpt_fdp] += price_document.price_line_block.tot_fdp_ht
        
        comptes[cpt_fdp_tva] = comptes[cpt_fdp_tva] || 0.0
        comptes[cpt_fdp_tva] += price_document.price_line_block.tot_fdp_tva  
      end
      
      price_document.price_line_block.price_lines.each do |price_line|
        
        if price_line.tva_account_id
          tva_rate = TvaRate.where(:id => price_line.tva_account_id).first
        elsif price_line.tva_account_value and price_line.accounting_zone_id
          tva_rate = TvaRate.where(:rate => price_line.tva_account_value,:accounting_zone_id => price_line.accounting_zone_id).first
        end
        
        
        if price_line.tot_line_ht != 0.0
          
          if price_line.product_no_remise
            tot_amount_ht = price_line.tot_amount_ht
          else
            tot_amount_ht = (price_line.tot_amount_ht - ((price_document.price_line_block.ct_tot_discount_percent.to_f / 100.0) * (price_line.tot_amount_ht))).round(2)
            
          end
          
          
          
          
          if tva_rate
            sl_acc = tva_rate.sale_product_account
          else
            sl_acc = "70700800"
          end
          
          comptes[sl_acc] = comptes[sl_acc] || 0.0
          comptes[sl_acc] +=tot_amount_ht

        end

        if price_line.tot_line_tva != 0.0

          
          
          if price_line.product_no_remise
            tot_amount_tva = price_line.tot_amount_tva
          else
            tot_amount_tva = (price_line.tot_amount_tva - ((price_document.price_line_block.ct_tot_discount_percent.to_f / 100.0) * (price_line.tot_amount_tva))).round(3)
          end

          if tva_rate
            comptes[tva_rate.sale_account] = comptes[tva_rate.sale_account] || 0.0
            comptes[tva_rate.sale_account] += tot_amount_tva

          else
            comptes["cpt TVA introuvable"] = comptes["cpt TVA introuvable"] || 0.0
            comptes["cpt TVA introuvable"] += tot_amount_tva
          end
        end



      end
      
      
      

      comptes.each do |key, value|
        
        line = []
        line << key
        line << ""
        line << ""
        line << price_document.date.strftime("%d/%m/%Y") 
        line << price_document.payment_end_at
        line << price_document.d_number
      
        if value.to_f >= 0
          
          line << ""
          line << value.to_s.gsub('.', ',')

        else
          line << (value*-1).to_s.gsub('.', ',')
          line << ""
          
        
        end

        @lines << line
        
        
        line_pnm = []
      
        line_pnm << "M"
    
        line_pnm << ('%-8.8s' % key)
        line_pnm << "VE"
        line_pnm << "000"
        line_pnm << ('%-6.6s' % price_document.date.strftime("%d%m%y") )
      
        if price_document.label == "Facture"
          line_pnm << "F"
        elsif price_document.label == "Avoir"
          line_pnm << "A"
        end
      
        line_pnm << ('%-20.20s' % price_document.d_number )
      
        if value.to_f >= 0
          line_pnm << "C+"
        


        else
          line_pnm << "D+"
        
        end
      
        line_pnm << ('%12.12s' % (value.abs*100).to_i.to_s ).gsub(' ', "0")
      
        line_pnm << ('%-8.8s' % " " )
    
        line_pnm << ('%-6.6s' % "000000" )
      
        line_pnm << ('%-5.5s' % " " )
      
        line_pnm << ('%-5.5s' % price_document.d_number )
      
        line_pnm << ('%-20.20s' % " " )
      
        line_pnm << ('%-8.8s' % price_document.d_number )
      
        line_pnm << "EUR"
      
      
        line_pnm << "VE"
      
        line_pnm << ('%-4.4s' % " " )
      
        line_pnm << ('%-30.30s' % (price_document.d_number+ " "+price_document.p_customer.show_name.to_s) )
      
        line_pnm << ('%-2.2s' % " " )
      
        line_pnm << ('%-10.10s' % price_document.d_number )
      
   
      
        @lines_pnm << line_pnm
        
        
        
        
        
        
        

      end


      comptes_tva.each do |key, value|
        line = []
        line << key
        line << ""
        line << ""
        line << price_document.date.strftime("%d/%m/%Y") 
        line << price_document.payment_end_at
        line << price_document.d_number
        if price_document.s_project
          line << price_document.s_project.p_number 
        else
          line << ""
        end
        line << price_document.libelle


        if value.to_f >= 0
          
          line << ""
          line << value.to_s.gsub('.', ',')

        else
          line << value.to_s.gsub('.', ',')
          line << ""
          
        
        end

        @lines << line



        line_pnm = []
      
        line_pnm << "M"
    
        line_pnm << ('%-8.8s' % key)
        line_pnm << "VE"
        line_pnm << "000"
        line_pnm << ('%-6.6s' % price_document.date.strftime("%d%m%y") )
      
        if price_document.label == "Facture"
          line_pnm << "F"
        elsif price_document.label == "Avoir"
          line_pnm << "A"
        end
        
        line_pnm << ('%-20.20s' % price_document.d_number )
      
        if value.to_f >= 0
          line_pnm << "C+"
        


        else
          line_pnm << "D+"
        
        end
      
        line_pnm << ('%12.12s' % (value.abs*100).to_i.to_s ).gsub(' ', "0")
      
        line_pnm << ('%-8.8s' % " " )
    
        line_pnm << ('%-6.6s' % "000000" )
      
        line_pnm << ('%-5.5s' % " " )
      
        line_pnm << ('%-5.5s' % price_document.d_number )
      
        line_pnm << ('%-20.20s' % " " )
      
        line_pnm << ('%-8.8s' % price_document.d_number )
      
        line_pnm << "EUR"
      
      
        line_pnm << "VE"
      
        line_pnm << ('%-4.4s' % " " )
      
        line_pnm << ('%-30.30s' % (price_document.d_number+ " "+price_document.p_customer.show_name.to_s) )
      
        line_pnm << ('%-2.2s' % " " )
      
        line_pnm << ('%-10.10s' % price_document.d_number )
      
   
      
        @lines_pnm << line_pnm
        
        
      end


      



      







    end

    @table_header = @headers
    @table = @lines
  
    xlsx_package = Axlsx::Package.new
      wb = xlsx_package.workbook
      wb.add_worksheet(name: "import") do |sheet|
        sheet.add_row @table_header
        @table.each do |tr|
          sheet.add_row tr
        end
      end

      directory_name = "price_document_exports"
      Dir.mkdir("private_medias/#{directory_name}") unless File.exists?("private_medias/#{directory_name}")

      @filename = "export-#{@p_compta_export.id}"

      file_path = "private_medias/#{directory_name}/#{@filename}-#{Time.now.to_s.to_slug}.xlsx"
      xlsx_package.serialize(file_path)  
      

      pnm_file_path = "private_medias/#{directory_name}/#{@filename}-#{Time.now.to_s.to_slug}.txt"

      File.open(pnm_file_path, "w+:iso-8859-1") do |f|
        #@data_to_send_pnm = "NOM\r\n"
        @data_to_send_pnm = ""
        @lines_pnm.each do |line|
          
          @data_to_send_pnm += line.join("")
          
          if false
            @data_to_send_pnm += "M"
          
            @data_to_send_pnm += ('%-8.8s' % line[1])
            @data_to_send_pnm += "VE"
            @data_to_send_pnm += "000"
            @data_to_send_pnm += ('%-8.8s' % line[2])
          
          
            @data_to_send_pnm += ('%-3.3s' % line[0])
          
          
            @data_to_send_pnm += ('%-8.8s' % line[2])
            @data_to_send_pnm += ('%32.32s' % line[3])
            @data_to_send_pnm += ('%-25.25s' % line[4])
            @data_to_send_pnm += ('%-7.7s' % line[5])
            @data_to_send_pnm += ('%-1.1s' % line[6])
            @data_to_send_pnm += ('%20.20s' % line[7])
            @data_to_send_pnm += ('%-34.34s' % line[8])
            @data_to_send_pnm += ('%-26.26s' % line[9])
          end
          @data_to_send_pnm += "\r\n"
        end
        f.write(@data_to_send_pnm.encode("iso-8859-1", invalid: :replace, undef: :replace))
      end
    

    
    
    respond_to do |format|
          format.html{
            
       
            
          }
          
          
          
          format.csv { 
            
            
            
            send_file file_path, :filename => "#{@filename}-#{Time.now.to_s.to_slug}.xlsx" #, :type => 'text/csv; charset=iso-8859-1; header=present' 
        
          }
          
          
          format.pnm { 
            
            send_data @data_to_send_pnm.encode("iso-8859-1", :undef => :replace), filename: "export-ansi.txt", type: "text/plain; charset=iso-8859-1", :disposition => (false ? "inline" : "attachment")
            
            #send_file pnm_file_path, :filename => "export-pnm.pnm", :type => 'text/plain; charset=iso-8859-1', :disposition => "attachment"
        
          }
          
    
    end
    
    
    
    
    
    
    
    
    
    
    
    
    
    

  end

  def new
    
    
    @p_compta_export = PComptaExport.new
    

  end

  def lock
    @p_compta_export = PComptaExport.find(params[:id])
    @p_compta_export.valid_process
    
    redirect_to [:admin, @p_compta_export]
  end

  def edit
  
    
    @p_compta_export = PComptaExport.find(params[:id])
  end

  def create
    @p_compta_export = PComptaExport.new(params.require(:p_compta_export).permit!)


    if @p_compta_export.save
     @p_compta_exports = PComptaExport.all
      
    else
      render action: "new"
 
    end

  end


  def update
    @p_compta_export = PComptaExport.find(params[:id])


    if @p_compta_export.update_attributes(params.require(:p_compta_export).permit!)
      
       @p_compta_exports = PComptaExport.all
    else
     render action: "edit" 
      
    end
      
  end


  def destroy
    @p_compta_export = PComptaExport.find(params[:id])
    @p_compta_export.destroy
    
    
  end
end
