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

class Admin::PRemisesController < ApplicationController
  layout "admin"
  before_action :auth_admin, :except => [:print]

  before_action :admin_space
  
  def admin_space
    @admin_space = "payments"
  end
  
  def print
    @p_remise = PRemise.find(params[:id])
    params[:inline] = true
    if !params[:html]
      doc_number = "remise-"+params[:id].to_s
      url = print_admin_p_remise_path(:id => params[:id],:html => true)
    
      @temp_file = "#{Rails.root}/pdf/p_documents/ADR-#{doc_number}.pdf"
    
    
    
    
      url = (Rails.env.development? ? "http://localhost:4000" : "http://3p.quartz.xyz").to_s+url
      puts url
      pdf = "pdfadr"
      command = "node #{pdf}.js #{Shellwords.escape(url)} #{Shellwords.escape(@temp_file)}"
      puts command
      system(command)
  
      @data_to_send = File.open( @temp_file).read
     
    
      send_data @data_to_send, :filename =>"#{doc_number}.pdf" , :type => 'application/pdf',:disposition => (params[:inline] ? 'inline' : "attachment")
    else
       render :layout => false
    end
    
    
    
    
    
  end
  
  
  def index
    @p_remises = PRemise.order("date DESC").all

   
  end

  def show
    @p_remise = PRemise.find(params[:id])

  end

  def new
    
    
		@p_remise = PRemise.new
    

  end

  def new_f
    
    @p_remise_form = true
		@p_remise = PRemise.new(:p_payment_ids => params[:p_payment_ids], :date => Date.today)
    
    if @p_remise.p_payments[0]
      @p_remise.p_payment_type_id = @p_remise.p_payments[0].p_payment_type_id
    end
      
    render :action => :new

  end

 

  def edit
    @p_remise_form = true
    
    @p_remise = PRemise.find(params[:id])
  end

  def create
    @p_remise_form = true
    
    @p_remise = PRemise.new(params.require(:p_remise).permit!)


    if @p_remise.save
     redirect_to admin_p_remises_path
      
    else
      render action: "new"
 
    end

  end


  def update
    @p_remise_form = true
    
    @p_remise = PRemise.find(params[:id])


    if @p_remise.update_attributes(params.require(:p_remise).permit!)
      
       redirect_to admin_p_remises_path
    else
     render action: "edit" 
      
    end
      
  end


  def destroy
    
    @p_remise = PRemise.find(params[:id])
    @p_payments_ids = @p_remise.p_payments.ids
    @p_remise.destroy
    PPayment.where(:id => @p_payments_ids).update_all(:remise => false)
    
  end
end
