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

class Admin::PDocumentsController < ApplicationController
	#before_filter :auth_admin

  include ActionView::Helpers::NumberHelper
  
	#layout "admin"

  before_filter :admin_space
  
  def admin_space
    @admin_space = "documents"
  end

  def search_to_affect
    @p_customer = PCustomer.where(:id => params[:p_customer_id]).first
  end

  def index
    @p_documents = PDocument.includes(:p_customer)
    params[:p_document_type_ids] = params[:p_document_type_ids] || []
    @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
      @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
    

    
    if params[:amount_min].to_s != ""
      @p_documents = @p_documents.where("cache_total_ttc >= ?", params[:amount_min])
    end
    
    if params[:amount_max].to_s != ""
      @p_documents = @p_documents.where("cache_total_ttc <= ?", params[:amount_max])
    end
    
    
    @p_documents = @p_documents.where("p_documents.created_at >= ?", @start) if @start

    @p_documents = @p_documents.where("p_documents.created_at <= ?", @stop.end_of_day) if @stop
    
    
    @p_documents = sort_by_sorting(@p_documents, "created_at DESC")
    
    per_page = (params[:search][:per_page] and params[:search][:per_page] != "") ? params[:search][:per_page] : 50
    page = (params[:search][:page] and params[:search][:page] != "") ? params[:search][:page] : 1 
    @p_documents = @p_documents.page(page).per(per_page)
    
    
    render :layout => "admin"
  end
	def detail
		@p_document = PDocument.find(params[:id])
    
    render :layout => "admin"
  end
	def show
		@p_document = PDocument.find_by_token(params[:id])
    @element = @p_document.element
    params[:inline] = true
    

    if !params[:html] and !Rails.env.development?
  
      @temp_file = "#{Rails.root}/pdf/p_documents/#{@p_document.d_number}_temp.pdf"
      @final_file = "#{Rails.root}/pdf/p_documents/#{@p_document.d_number}.pdf"
      
    
      url = (Rails.env.development? ? "http://localhost:4000" : "http://biocoton.quartz.xyz").to_s+admin_p_document_path(:id => @p_document.token, :html => true)
      puts url
      pdf = ("pdf")
      system("node #{pdf}.js #{Shellwords.escape(url)} #{Shellwords.escape(@temp_file)}")
  
    
      
      require 'posix/spawn'
  
      if @p_document.p_document_type.data_file 
        ::POSIX::Spawn::Child.new 'pdftk', @temp_file, 'background', @p_document.p_document_type.data_file.file.path, 'output',  @final_file

      else
        ::POSIX::Spawn::Child.new 'pdftk', @temp_file, 'stamp', "#{Rails.root}/pdf_stamp/en-tete.pdf", 'output',  @final_file
    
      end

      @data_to_send = File.open( @final_file).read

    
      send_data @data_to_send, :filename =>"#{@p_document.d_number}.pdf" , :type => 'application/pdf',:disposition => (params[:inline] ? 'inline' : "attachment")
  

    
    else
      render :layout => false
    end
    
	end


  def send_by_mail
    @p_document = PDocument.find(params[:id])
    @p_customer = @p_document.p_customer
    
    render :layout => "admin"
  end
  
  def send_by_mail_save
    @p_document = PDocument.find(params[:id])
    @p_customer = @p_document.p_customer
    
    
    params[:emails].each do |email|
      
      mail_history = MailHistory.generateMail("envoi_facture", email, {:element => @p_document, :p_customer => @p_customer, :mail_options => {:arguments =>  {:lien => admin_p_document_url(@p_document.token), :numero => @p_document.d_number, :document => @p_document.label.downcase, :date => @p_document.created_at.to_date.to_s, :montant => number_to_currency(@p_document.cache_total_ttc)}}})
      
      mail_history.deliver_mail
      
      
    end
    
    redirect_to detail_admin_p_document_path(@p_document)
    
    
  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"

    end

  end
  
end