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

class Admin::PDocumentsController < ApplicationController
  #before_action :auth_admin

  #layout "admin"
  before_action :find_p_customer
  
  before_action :admin_space
  
  def edit
  
    
    @p_document = PDocument.find(params[:id])
    
  end



  def update
    @p_document = PDocument.find(params[:id])
   
    if @p_document.update_attributes(params.require(:p_document).permit!)
      
      #redirect_to ship_return_admin_p_ship_tour_path(@p_document.p_ship_tour_truck.p_ship_tour)
    else
     render action: "edit" 
      
    end
      
  end
  
  
  def admin_space
    if @p_customer
      @admin_space = "clients"
    else
      @admin_space = "documents"
    end
  end

  def index
    params[:p_document_type_ids] = params[:p_document_type_ids] || ["4", "7"]
    
    if @p_customer
      @p_documents = @p_customer.p_documents
    else
      @p_documents = PDocument
    end
    @p_documents = @p_documents.order("created_at DESC")
    
    @p_documents = @p_documents.where(:p_document_type_id => params[:p_document_type_ids]) if params[:p_document_type_ids].size > 0

    date_regex = /^(0[1-9]|[12][0-9]|3[01])[\/](0[1-9]|1[012])[\/](19|20)\d\d$/i 
    
    
    params[:start] = Date.today.beginning_of_month.strftime('%d/%m/%Y') if !params[:start]
    
    if params[:start] and params[:start] =~ date_regex
      #fsfds = sdfsfd
      @start = Date.parse(params[:start]).beginning_of_day 
      params[:start]= @start.strftime('%d/%m/%Y')
    else
      @start = nil
    end
    
    if true
      params[:stop] = Date.today.end_of_month.strftime('%d/%m/%Y') if !params[:stop]

    
      if params[:stop].to_s != "" # and params[:stop] =~ date_regex
        @stop = Date.parse(params[:stop]).end_of_day 
        
        params[:stop]= @stop.strftime('%d/%m/%Y')
        
        
      else
         @stop = nil
      end
    
    end
    
    
    @p_documents = @p_documents.where("created_at >= ?", @start) if @start

    @p_documents = @p_documents.where("created_at <= ?", @stop.end_of_day) if @stop
    
    params[:per_page] = 100000 if params[:print]
    per_page = (params[:per_page] and params[:per_page] != "") ? params[:per_page] : 50
    page = (params[:page] and params[:page] != "") ? params[:page] : 1 
    @p_documents = @p_documents.page(page).per(per_page)
    
    
    @p_documents = @p_documents.all
    
    if !params[:print]
      render :layout => "admin" 
    else
      render :layout => "print"
    end
  end
  
  
  def multiple
    params[:inline] = true
    
    @p_documents = PDocument.where(:token => params[:ids])
    
    files = []
    @p_documents.each do |p_document|
      files << Shellwords.escape(p_document.generate_pdf)
    end
    
    if @p_documents.count > 0
    
      name = "#{Time.now.to_s.to_slug}-#{Kernel.rand(10)}.pdf"
      @multiple_file = "#{Rails.root}/pdf/multiples/"+name.to_s
    
    
      #::POSIX::Spawn::Child.new 'pdftk',files,  'cat', 'output',  @multiple_file  #AJOUT CGV 
      system("pdftk #{files.join(" ")} cat output #{Shellwords.escape(@multiple_file)}")
    
    
   
      #doc_number = "tournee-"+params[:p_ship_tour_id].to_s
      #url = admin_p_document_path(:id => params[:id], :ids => params[:ids], :p_ship_tour_id => params[:p_ship_tour_id], :html => true)
      #@bl = true
    
      @data_to_send = File.open(@multiple_file).read
    
    
    
    
    
      send_data @data_to_send, :filename =>"#{name}.pdf" , :type => 'application/pdf',:disposition => (params[:inline] ? 'inline' : "attachment")
      #render :inline => "y"
      
    else
      render :inline => "Merci de sélectionner des documents"
    end
    
    
  end
  
  
  def show
    
    
    
    if params[:id] != "multiple"
      
      
      @p_document = PDocument.find_by_token(params[:id])
      @element = @p_document.element
      
      doc_number = @p_document.d_number
      url = admin_p_document_path(:id => @p_document.token, :html => true)
      
    else
      @p_documents = PDocument.where(:token => params[:ids])
      
      doc_number = "tournee-"+params[:p_ship_tour_id].to_s
      url = admin_p_document_path(:id => params[:id], :ids => params[:ids], :p_ship_tour_id => params[:p_ship_tour_id], :html => true)
      @bl = true
    
    end
    
    
    
    
    if @p_document and @p_document.d_prefix == "BL"
      @bl = true
    end
    
    params[:inline] = true
    
    if !params[:html] and !Rails.env.development?
      
      @data_to_send = File.open(@p_document.generate_pdf).read
      
      
      
      
      
      send_data @data_to_send, :filename =>"#{doc_number}.pdf" , :type => 'application/pdf',:disposition => (params[:inline] ? 'inline' : "attachment")
      #render :inline => "y"
    
    else
      render :layout => false
    end
    
  end
  
  def find_p_customer
    if params[:p_customer_id].to_s != ""
      @p_customer = PCustomer.find(params[:p_customer_id])
      
    end
  end
  
  def create_avoir
    @p_document = PDocument.find(params[:id])
    @avoir = @p_document.create_avoir
    #  @p_document.element.restock if @p_document.element and @p_document.element_type == "PCustomerSheet"
    #end
    #redirect_to :back
    
    render :layout => "admin"
    
    
  end
  

  def save_avoir
    @avoir = PDocument.new(params.require(:p_document).permit!)


    if @avoir.save
     
      redirect_to admin_p_customer_sheet_path(@avoir.element)
    else
      render action: "create_avoir", :layout => "admin"

    end

  end
  
  
  def detail
    @p_document = PDocument.find(params[:id])
    
    render :layout => "admin"
    
  end

  
end
