class Admin::DonatorTransactionsController < ApplicationController
  layout "admin"
  def index
    @donator_transactions = DonatorTransaction.all
  end
  
  def new
    @donator_transaction = DonatorTransaction.new(:particular_idem => true, :donator_id => params[:donator_id])
    if params[:donator_id] and @donator = Donator.find(params[:donator_id])
      particular = @donator.particular.dup
      
    else
      particular = Particular.new
    end
    
    particular.particular_type = "facturation"
      
    @donator_transaction.particular_bill = particular
      
    @donator_transaction.particular_send = Particular.new(:particular_type => "expedition")
    
    @donator_transaction.tr_payment = TrPayment.new(:paid_at => Time.now)
    
    transaction_item =  TransactionItem.new(:amount => 10.5)
    transaction_item.transaction_content = TransactionDonate.new(:donate_destination_id => 1)
    
    @donator_transaction.transaction_items << transaction_item
    
    transaction_item =  TransactionItem.new(:amount => 7)
    transaction_item.transaction_content = TransactionSponsorship.new()
    
    @donator_transaction.transaction_items << transaction_item
    
    
    
  end
  
  
  def create
    @donator_transaction = DonatorTransaction.new(params.require(:donator_transaction).permit!)
    
    if @donator_transaction.save
      if @donator_transaction.donator
        redirect_to admin_donator_path(@donator_transaction.donator), :notice => "Donateur ajouté avec succès"
      else
        redirect_to :action => :index, :notice => "Donateur ajouté avec succès"
      end
      
    else
    
      render :action => :new
    end
    
      
  end
  
  def edit
    @donator_transaction = DonatorTransaction.find(params[:id])
  end
  
  def show
    @donator_transaction = DonatorTransaction.find(params[:id])
  end
  
  def update
    @donator_transaction = DonatorTransaction.find(params[:id])
    
    if @donator_transaction.update_attributes(params.require(:donator_transaction).permit!)
      if @donator_transaction.donator
        redirect_to admin_donator_path(@donator_transaction.donator), :notice => "Donateur ajouté avec succès"
      else
        redirect_to :action => :index, :notice => "Donateur ajouté avec succès"
      end
      
    else
    
      render :action => :edit
    end
    
  end
  
  def destroy
    @donator_transaction = DonatorTransaction.find(params[:id])
    @donator_transaction.destroy
    
    redirect_to :back
  end

  def import
    
    require 'roo'

    @xlsx = Roo::Spreadsheet.open("#{Rails.root}/import_donateurs/1.xls")
    #xlsx = Roo::Excelx.new("./new_prices.xlsx")

    # Use the extension option if the extension is ambiguous.
    #xlsx = Roo::Spreadsheet.open('./rails_temp_upload', extension: :xlsx)

    @xlsx.info
    @sheet = @xlsx.sheet(0)
    
  end
  
  
end
