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

class Admin::ProductOrdersController < ApplicationController
	before_filter :auth_admin, :except => [:bill, :bl]

	layout "admin"


	before_filter :find_product_orders



  def export2
    @product_orders = ProductOrder.where(:completed_finish => true).order("created_at DESC")
    
    
    
    respond_to do |format|
          format.html
          
          
          
          format.csv { 
            
            @file = ""
            
            elements = {
              
              "N°Pièce" => "product_order.bl_number",
              
              "Date" => "product_order.created_at",
              "Type document" => "product_order.sage_type_doc",
              "Tiers" => "product_order.sage_tiers",
              "Référence article" => "sage_reference",
              "Quantité" => "qty",
              
              
              
              
              
              
              "Type prix" => "product_order.sage_type_prix",
              "Prix unitaire" => "archived_product.price_ht",
              
      
              
   
              
            }
            
         
            
            headers = []
            attributes = []
            
            elements.each do |key, value|
              headers << key
              attributes << value
            end
            
            @csv = CSV.generate(:headers => true, :col_sep => ";") do |csv|
              csv << headers
              
              @product_orders.all.each do |product_order|
                product_order.product_order_products.each do |product_order_product|
                  csv << attributes.map{ |attr| eval("product_order_product."+attr.to_s) }
                end

                
              end

            end
            
            send_data @csv.encode('iso-8859-1', :undef => :replace, :replace => ''), :filename => "export-#{Date.today.to_s.to_slug}.csv", :type => 'text/csv; charset=iso-8859-1; header=present' }
    end
  end


  def export
    @product_orders = ProductOrder.where(:completed_finish => true).order("created_at DESC")
    
    
    
    respond_to do |format|
          format.html
          
          
          
          format.csv { 
            
            @file = ""
            
            elements = {
              
              "token" => "token",
              "bl_number" => "bl_number",
              "bl_index" => "bl_index",
              "bl_year" => "bl_year",
              "created_at" => "created_at",
              
              
              "fact_organisation" => "particular_bill.organisation",
              "fact_prenom" => "particular_bill.firstname",
              "fact_nom" => "particular_bill.name",
              "fact_adresse" => "particular_bill.address_2",
              "fact_adresse suite" => "particular_bill.address_3",
              "fact_cp" => "particular_bill.cp",
              "fact_ville" => "particular_bill.city",
              "fact_pays" => "particular_bill.country",
              "fact_tel" => "particular_bill.tel",
              
              "livr_organisation" => "particular_send.organisation",
              "livr_prenom" => "particular_send.firstname",
              "livr_nom" => "particular_send.name",
              "livr_adresse" => "particular_send.address_2",
              "livr_adresse suite" => "particular_send.address_3",
              "livr_cp" => "particular_send.cp",
              "livr_ville" => "particular_send.city",
              "livr_pays" => "particular_send.country",
              "livr_tel" => "particular_send.tel",
              
              
              "total HT" => "exp_archived_total_ht",
              "total TVA" => "exp_archived_total_tva",
              "total TTC" => "exp_archived_total_ttc",
              
      

   
              
            }
            
         
            
            headers = []
            attributes = []
            
            elements.each do |key, value|
              headers << key
              attributes << value
            end
            
            @csv = CSV.generate(:headers => true, :col_sep => ";") do |csv|
              csv << headers
              
              @product_orders.all.each do |product_order|
                

                csv << attributes.map{ |attr| eval("product_order."+attr.to_s) }
              end

            end
            
            send_data @csv.encode('iso-8859-1', :undef => :replace, :replace => ''), :filename => "export-#{Date.today.to_s.to_slug}.csv", :type => 'text/csv; charset=iso-8859-1; header=present' }
    end
    
    
    
    
    
    
    
    
    
    
    
    
    
  end



  def ship
    @product_order = ProductOrder.find(params[:id])
    @product_order.after_ship
    
    redirect_to :back
  end

	def index 

	end


	def edit
		@product_order = ProductOrder.find(params[:id])
	end
  
	
	def show
		@product_order = ProductOrder.find(params[:id])
	end

	def subs
		@product_order = ProductOrder.find(params[:id])
	end
  


  def bill
    @product_order = ProductOrder.find(params[:id])
    
    if @product_order.bill_number?
      
      
      
      @temp_file =  "#{Rails.root}/pdf/facture/FACTURE_#{@product_order.id}_temp.pdf"
      @final_file = "#{Rails.root}/pdf/facture/FACTURE_#{@product_order.id}.pdf"
    
    
      view = ActionView::Base.new(Rails.root.join('app/views'))
      view.class.include ApplicationHelper
      view.class.include Rails.application.routes.url_helpers

      pdf = view.render( 
              :pdf => "#{@product_order.id}",
              :template => "admin/product_orders/bill.html.haml",  
              
              :locals => {:@product_order => @product_order})
                                          
      # then save to a file
      pdf = WickedPdf.new.pdf_from_string(pdf, :margin =>  {   top:               0,                     # default 10 (mm)
                                          bottom:            0,
                                          left:              0,
                                          right:             0 })

      save_path = @temp_file
      File.open(save_path, 'wb') do |file|
      file << pdf
      end
      
      
      
     
      require 'posix/spawn'
     
      ::POSIX::Spawn::Child.new 'pdftk', @temp_file, 'background', Rails.root.join('pdf_stamp', 'facture.pdf').to_s, 'output',  @final_file
    
      #pdftk /Users/nico/Dev/sideplace_app.old/pdf/order_bills/SP20150700003.pdf background fond.pdf output sortie.pdf
      
      
      
      
      
      @data_to_send = File.open( @final_file).read
      
      send_data @data_to_send, :filename =>"facture.pdf" , :type => 'application/pdf',:disposition => (params[:inline] ? 'inline' : "attachment")
  
      
      
      
      
      
      
    else
      render :inline => "Aucune facture disponnible"
    end
    
    
  end



	def create
		@product_order = ProductOrder.new(params.require(:product_order).permit!)


		if @product_order.save
      self.find_product_orders
			flash[:notice] = "La catégorie à été ajouté avec succès."
		

		else
			render :action => "new" 
		
		end
	
	end
	

	def update
		@product_order = ProductOrder.find(params[:id])


		
		
		respond_to do |format|
			if @product_order.update_attributes(params.require(:product_order).permit!)
				
				#ProductOrder.all.each do |mi|
				#	mi.set_permalink
				
				#end
			
				flash[:notice] = "Le menu à été modifié avec succès."
				format.html { redirect_to(admin_product_orders_path(:parent_id => @product_order.parent_id)) }
				if @reorder
					format.js { 
						
						render :action => "update" }
				else
					format.js { 
					   @product_order = ProductOrder.find(@product_order.id)
						render :action => "update_row" }
				end
			else
				
				
					format.html { render :action => "edit" }
					format.js { render :action => "edit" }
			
				
				
			end
		end
    
    
    
    

	end


	def destroy
		@product_order = ProductOrder.find(params[:id])

		@product_order.destroy
    
  
    flash[:notice] = "La commande à bien été supprimée."
	end
	
  
  def bl
    @product_order = ProductOrder.find_by_token(params[:id])
    if !@product_order.bl_number?
      @product_order.generate_bl_number
    end
    if @product_order.bl_number?
      
      if true
      
        @temp_file = "#{Rails.root}/pdf/bl/BL_#{@product_order.id}_temp.pdf"
        @final_file = "#{Rails.root}/pdf/bl/BL_#{@product_order.id}.pdf"
    
    
        view = ActionView::Base.new(Rails.root.join('app/views'))
        view.class.include ApplicationHelper
        view.class.include Rails.application.routes.url_helpers

        pdf = view.render( 
                :pdf => "#{@product_order.id}",
                :template => "admin/product_orders/bl.html.haml",  
              
                :locals => {:@product_order => @product_order})
                                          
        # then save to a file
        pdf = WickedPdf.new.pdf_from_string(pdf, :margin =>  {   top:               0,                     # default 10 (mm)
                                            bottom:            0,
                                            left:              0,
                                            right:             0 })

        save_path = @temp_file
        File.open(save_path, 'wb') do |file|
        file << pdf
        end
      
      
      
     
        require 'posix/spawn'
     
        ::POSIX::Spawn::Child.new 'pdftk', @temp_file, 'background', Rails.root.join('pdf_stamp', "bl#{(@product_order.reseaux_id if @product_order.reseaux_id == 19)}.pdf").to_s, 'output',  @final_file
    
        #pdftk /Users/nico/Desktop/Sanstitre4.pdf background /Users/nico/Dev/negos_app/pdf_stamp/bl.pdf output sortie.pdf
      
      
      
      
      
        @data_to_send = File.open( @final_file).read
      
        send_data @data_to_send, :filename =>"#{@product_order.bl_number}.pdf" , :type => 'application/pdf',:disposition => (params[:inline] ? 'inline' : "attachment")
  
      
      else
        render :layout => false
      end
      
      
      
      
    else
      render :inline => "Aucun BL disponnible"
    end
    
    
  end
  
  
  
  
  
  
  
  
  
  
	
	protected
	
	def find_product_orders    
    @product_orders = ProductOrder.where(:completed_finish => true).order("created_at DESC")
		

	
  end
  
end
