class Admin::VirementRemisesController < ApplicationController
  layout "admin"
  

  
  def index

    @virement_remises = VirementRemise.order("created_at DESC").all
  end


  def show

    @virement_remise = VirementRemise.find(params[:id])
    
    
    
    file_path = Rails.root.join("private_medias", "remises", "remise_#{@virement_remise.token}.xml")
    if !File.exist?(file_path)
      @data_to_send = render_to_string(:layout => "admin/virement_remise/show.html.erb", :layout => false)
      
      File.open(file_path, "w+") do |f|
        f.write(@data_to_send)
      end
    end

    send_file file_path, :filename =>"remise_#{@virement_remise.token}.xml" , :type => 'text/xml'#,:disposition => (params[:inline] ? 'inline' : "attachment")
    
  end
  
  def sended
    @virement_remise = VirementRemise.find(params[:id])
    
    
    @virement_remise.sended = true
    
    @virement_remise.virements.each do |virement|
      virement.sended = true
      virement.save(:validate => false)
    end
   
    
    @virement_remise.save
    
    #redirect_to :back
    
  end

  def edit
    @virement_remise = VirementRemise.find(params[:id])
  end


  def create
    @virement_remise = VirementRemise.new()
    
    if @virement_remise.save
      params[:virement_ids].each do |id|
        virement = Virement.find(id.to_i)
        virement.virement_remise_id = @virement_remise.id
        virement.save(:validate => false)
      end
      
      @virement_remise.init
      redirect_to :action => :index
          
    else
      render :action => "new" 
    end
    
  end


  def update
    @virement_remise = VirementRemise.find(params[:id])
    
    if @virement_remise.update_attributes(params.require(:virement_remise).permit!)

          
    else
      render :action => "edit" 
    end
    
  end

end
