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

class Admin::PProductStocksController < ApplicationController
  layout "admin"
  before_filter :auth_admin
  
  before_filter :admin_space
  
  def export
    @p_products = PProduct.where(:archived => false, :enabled => true).all
    
    @file = ""

    @headers = [
      "ID produit Sys.",
      "Ref produit",
      "Nom",
      "ID variante",
      "Ref variante",
      "Taille",
      "Couleur",
      "Stock Physique",
      "Stock theo",
      "Stock const"
 
    ]   
    
    @csv = CSV.generate(:headers => true, :col_sep => ";") do |csv|
      csv << @headers
      
      @p_products.each do |p_product|
        p_product.p_product_stocks.each do |pps|
          line = []
          
          line << p_product.id
          line << p_product.code
          line << p_product.name
          
          line << pps.id
          line << pps.code
          line << (pps.p_color ? pps.p_color.name : "")
          line << (pps.p_size ? pps.p_size.name : "")
          
          line << pps.stock_ok
          
          line << pps.stock_th_ok
              
          line << ""
          
          csv << line
          
        end
   
      end

    end
    
    
    @data_to_send = @csv.encode('iso-8859-1', :undef => :replace, :replace => '')
    
    file_path = Rails.root.join("pdf", "export.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 => "etat-stocks.csv", :type => 'text/csv; charset=iso-8859-1; header=present' 
        
          }
    end
    
    
    
    
  end
  
  def import
    if false
      
      #@file = params[:csv_file]
    
      require 'csv'    

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

      csv_text = File.read("#{Rails.root}/import_csv/prix.csv")#.force_encoding('ISO-8859-1')
      @csv = CSV.parse(csv_text, :headers => true, :col_sep => ";")
    end
    
  end
  
  
  
  def admin_space
    @admin_space = "ventes"
  end
  

  def index

   
  end

  
  
  
end
