class Admin::AnnonceAccountsController < ApplicationController
  layout "admin"
  

  
  def index
    
    per_page = (params[:per_page] and params[:per_page] != "") ? params[:per_page] : 50
    
    page = (params[:page] and params[:page] != "") ? params[:page] : 1 
    
    
    @annonce_accounts = AnnonceAccount
    
    if params[:q] and params[:q]
      @annonce_accounts = @annonce_accounts.where("email LIKE ? or organisation LIKE ? or name LIKE ? or firstname LIKE ?", "%"+params[:q]+"%","%"+params[:q]+"%","%"+params[:q]+"%","%"+params[:q]+"%")
    end
    
    @annonce_accounts = @annonce_accounts.page(page).per(per_page).order("created_at DESC").all
  end


  def show
    @annonce_account = AnnonceAccount.find(params[:id])
  end



  def edit
        @annonce_account = AnnonceAccount.find(params[:id])
      
  end
  def update
      @annonce_account = AnnonceAccount.find(params[:id])
      
      if @annonce_account.update_attributes(params.require(:annonce_account).permit!)
          
    else
        render :action => "edit" 
    end
    
  end
  
  def reconfirm
    @annonce_account = AnnonceAccount.find(params[:id])
    AnnonceAccountMailer.confirm(@annonce_account).deliver
    
    redirect_to :back, :notice => "Mail renvoyé"
    
    
  end
  
  def add_parent
    
    @parent = AnnonceAccount.find_parrain(params[:parent_code]) 
    @annonce_account = AnnonceAccount.find(params[:id])
    if @parent and @parent != @annonce_account
      
      @annonce_account.parent = @parent
      @annonce_account.parent_code = @parent.mlm_token
      @annonce_account.save
      @annonce_account.credits.create(:cred => true, :value => 10, :created_at => @annonce_account.created_at, :expire_after => @annonce_account.created_at+(6.months), :note => "Crédits offerts grâce au code de recommandation")
    
      @annonce_account.parent.credits.create(:cred => true, :value => 5, :created_at => @annonce_account.created_at, :expire_after => @annonce_account.created_at+(6.months), :note => "Crédits offerts grâce à votre nouvel affilié")
      
      AnnonceAccountMailer.new_user(@annonce_account).deliver
      redirect_to :back, :notice => "Le code de recommandation a été mis à jour"
      
    else
      redirect_to :back, :alert => "Le code de recommandation n'est pas valable"
      
    end
    
    
    
    
  end


end
