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

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

  before_action :admin_space
  
  require 'csv'
  def admin_space
    @admin_space = "statistiques"
  end

  def index
    
    
 
    
    
    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 
  		
		else
  		@start = Date.today.beginning_of_month
		end
    params[:start]= @start.strftime('%d/%m/%Y')
    
    
		if params[:stop] and params[:stop] =~ date_regex
			@stop = Date.parse(params[:stop]).end_of_day 
			
	  else
		 	#@stop = Date.today.end_of_month
		end
    params[:stop]= @stop.strftime('%d/%m/%Y') if params[:stop]
    
    
    
   
  end
  
  def show
    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 
  		
		else
  		@start = Date.today.beginning_of_month
		end
    params[:start]= @start.strftime('%d/%m/%Y')
    
    
		if params[:stop] and params[:stop] =~ date_regex
			@stop = Date.parse(params[:stop]).end_of_day 
			
	  else
		 @stop = Date.today.end_of_month
		end
    
    
    @p_documents = PDocument.where(:p_document_type_id => [4,7]).where("created_at >= ? and created_at <= ?", @start, @stop)
    
    @file = ""
    
  
    
 
    
    @headers = [
      "JOURNAL",
      "DATE",
      "Compte",
      "?",
      "Libélé",
      "?",
      "?",
      "Montant",
      "?",
      "Devise",
     
      
    ]
  
    
    
    
    
    @csv = CSV.generate(:headers => true, :col_sep => ";") do |csv|
      csv << @headers
      date = @start
      if true
        i = 0
        while date <= @stop
          i += 1
          break if i == 50
          date_formate = date.strftime('%Y%m%d')
          
          
          line = []
          line << date.strftime('%d/%m/%Y')
          #csv << line
          
          [4,7].each do |p_document_type_id|
            p_documents = PDocument.where(:p_document_type_id => p_document_type_id).where("created_at >= ? and created_at <= ?", date.beginning_of_day, date.end_of_day)
            if p_documents.count > 0
              journal = "VE" if p_document_type_id == 4
              journal = "AV" if p_document_type_id == 7
              
              
              
              
              
              if false
                line = []
                line << journal  
                line << date_formate
                line << "41110000"
                line << ""
                line << "Ventes TTC du #{date.strftime('%d/%m/%Y')}"
                line << "S"
                line << "C"
                line << ('%.2f' % p_documents.sum(:cache_total_ttc)).to_s.sub(".",",")
              
                line << "N"
                line << "EUR"
            
            
            
                csv << line
            
            
                line = []
                line << journal 
                line << date_formate
                line << "44571000"
                line << ""
                line << "TVA du #{date.strftime('%d/%m/%Y')}"
                line << "S"
                line << "D"
                line << ('%.2f' % p_documents.sum(:cache_total_tva)).to_s.sub(".",",")
                line << "N"
                line << "EUR"
            
            
            
                csv << line
            
                line = []
                line << journal 
                line << date_formate
                line << "41110000"
                line << ""
                line << "Ventes HT du #{date.strftime('%d/%m/%Y')}"
                line << "S"
                line << "D"
                line << ('%.2f' % p_documents.sum(:cache_total_ht)).to_s.sub(".",",")
                line << "N"
                line << "EUR"
            
            
            
                csv << line
                
              end
            
              
              #Address.distinct.pluck(:city)
              
              comptes = {}
              
              PSheetLine.where(:p_document_id => p_documents.ids).includes(:p_product).each do |psl|
                
                
                compte_vente = psl.p_product.compte_vente? ? psl.p_product.compte_vente : psl.p_product.name
                
                comptes[compte_vente.to_s] = comptes[compte_vente.to_s] || {}
                
                comptes[compte_vente.to_s][:total_ht] = comptes[compte_vente.to_s][:total_ht].to_f + psl.ok_price_tot
                comptes[compte_vente.to_s][:total_tva] = comptes[compte_vente.to_s][:total_tva].to_f + (psl.ok_price_tot*(psl.tva))
                comptes[compte_vente.to_s][:total_ttc] = comptes[compte_vente.to_s][:total_ttc].to_f + psl.ok_price_tot_ttc
                
                
                
                
                
              end
              
              comptes.each do |index,value|
                
              
            
                
                
                
                line = []
                line << journal  
                line << date_formate
                line << "41110000"
                line << ""
                line << "Ventes TTC du #{date.strftime('%d/%m/%Y')}"
                line << "S"
                line << (journal ==  "VE" ? "D" : "C")
                line << ('%.2f' % value[:total_ttc].abs).to_s.sub(".",",")
              
                line << "N"
                line << "EUR"
            
            
            
                csv << line
            
            
                line = []
                line << journal 
                line << date_formate
                line << "44571000"
                line << ""
                line << "TVA du #{date.strftime('%d/%m/%Y')}"
                line << "S"
                line << (journal ==  "VE" ? "C" : "D")
                line << ('%.2f' % value[:total_tva].abs).to_s.sub(".",",")
                line << "N"
                line << "EUR"
            
            
            
                csv << line
            
                line = []
                line << journal 
                line << date_formate
                line << index
                line << ""
                line << "Ventes HT du #{date.strftime('%d/%m/%Y')}"
                line << "S"
                line << (journal ==  "VE" ? "C" : "D")
                line << ('%.2f' % value[:total_ht].abs).to_s.sub(".",",")
                line << "N"
                line << "EUR"
            
            
            
                csv << line
                
                
                
                
              end
            
            
            end
            
          end
          
          
          
          
          
          
        
        
          date = date + 1.day
        end
      end
        
      
    end
    
    
    @data_to_send = @csv.encode('iso-8859-1', :undef => :replace, :replace => '')
    
    file_path = Rails.root.join("pdf", "csv", "ssdfds.csv")
      
    
    
    File.open(file_path, "w+") do |f|
      f.write(@data_to_send)
    end
    
    
    
    
    
    respond_to do |format|
          format.html{
            
       
    
            require 'csv'    

            csv_text = File.read(file_path).encode('utf-8')
            @csv = CSV.parse(csv_text, :headers => true, :col_sep => ";")
            
          }
          
          
          
          format.csv { 
            
            
            
            send_file file_path, :filename => "export-csv.csv", :type => 'text/csv; charset=iso-8859-1; header=present' 
        
          }
    end
    
    
    
    
    
    
  end

  
  
  
end