class Admin::AnnoncesController < ApplicationController
  layout "admin"
  
  before_filter :auth_admin
  
  
  def index
    if params[:past]
      @annonces = Annonce.where("moderated = 1")
    else
      
      @annonces = Annonce.where("moderated = 0 or moderated is null")
    end
    @annonces = @annonces.where(:published => true).order("created_at DESC")
    
		per_page = (params[:per_page] and params[:per_page] != "") ? params[:per_page] : 50
		page = (params[:page] and params[:page] != "") ? params[:page] : 1 
		@annonces = @annonces.page(page).per(per_page)
  end


  def show
    @annonce = Annonce.find(params[:id])
    @no_search = true
    session[:mail_prev] = public_annonce_path(@annonce)
    
    params[:p] = @annonce.annonce_account.mlm_token.upcase if !cookies[:mlm_token] and @annonce.annonce_account.credits_boughts(Date.today) > 0
  end


  
  def edit
    params[:step] = "info"
    @annonce = current_annonce_account.annonces.find(params[:id])
    @no_search = true
    
    @create = true if params[:create]
  end
  
 
  def update
    params[:step] = "info"
    @create = true if params[:create]
    @annonce = Annonce.find(params[:id])
   
    if params[:annonce][:refused]
      @annonce.moderated = true
      
    end
    
    if params[:annonce][:refused] == "NULL"
      @annonce.refused = nil
      @annonce.save
      params[:annonce][:refused] =nil
    end
    
    
    respond_to do |format|
      @annonce.assign_attributes(params.require(:annonce).permit!)

      
      
      if @annonce.save(validate: false)
        
  
        format.html { 
          redirect_to public_my_account_path
          }
        format.js
        
      else
        
        format.html { render :action => "edit" }
        format.js {  render :action => "edit"  }
      end
    end
    
    
      
  end
  		


  def destroy

    	 @annonce = current_annonce_account.annonces.find(params[:id])
  	   @annonce.enabled = nil
       @annonce.save
       
       redirect_to public_my_account_path, :notice => "Votre annonce a bien été désactivée"

    

  end
  



end
