class Public::AnnoncesController < ApplicationController
  layout "public"
  protect_from_forgery :except => [:search]
  before_filter :auth_annonce_account, :only => [:new, :create, :edit, :update]
  
  def search
    @search_index = true
		per_page = (params[:per_page] and params[:per_page] != "") ? params[:per_page] : 15
		page = (params[:page] and params[:page] != "") ? params[:page] : 1 
    
    if params[:annonce_cat_id] and params[:annonce_cat_id] != "" and @annonce_cat = AnnonceCat.find(params[:annonce_cat_id])
      
      @annonces = @annonce_cat.annonces
    else
      @annonces = Annonce.all
    end
    @annonces = @annonces.valid_to_show
    
    if params[:min_price] and params[:min_price] != ""
      @annonces = @annonces.where("price IS NOT NULL and price >= ?",params[:min_price].to_f )
    end
    if params[:max_price] and params[:max_price] != ""
      @annonces = @annonces.where("price IS NULL or price <= ?",params[:max_price].to_f )
    end
    
    #recherche par lieu

    
    
    @place_search = false
    
    if (params[:place] and params[:place] != "") #or (params[:place_lat] and params[:place_lng])
    
      if params[:with_radius] and params[:with_radius] != ""
        @place_search = true
        @annonces = @annonces.near([params[:place_lat].to_f, params[:place_lng].to_f], params[:place_dist].to_f, :units => :km, :order => nil)
      
      else
        if params[:place] != "" and params[:place_type] and params[:place_type].to_i == 1
          @annonces = @annonces.where("g_postal_code = ? and g_city = ?", params[:place_cp], params[:place_city])
          @place_search = true
    
        elsif params[:place] != "" and params[:place_type] and params[:place_type].to_i == 2
          @annonces = @annonces.where("g_postal_code = ?", params[:place_cp])
          @place_search = true
        elsif params[:place] != "" and params[:place_type] and params[:place_type].to_i == 3 
          @annonces = @annonces.where("g_sub_state = ?", params[:place_city])
          @place_search = true
      
        elsif params[:place] != "" and params[:place_type] and params[:place_type].to_i == 4 
          @annonces = @annonces.where("g_state = ?", params[:place_city])
          @place_search = true
        elsif params[:place] != "" and params[:place_type] and params[:place_type].to_i == 5 
          @annonces = @annonces.where("g_city = ?", params[:place_city] )
          @place_search = true
      
        elsif params[:place] != "" and params[:place_type] and params[:place_type].to_i == 6
          @annonces = @annonces.where("g_country = ?", params[:place_country] )
          @place_search = true
      
        end
    
      
      end
    else
      params[:with_radius] = nil
      params[:place_lat] = nil
      params[:place_lng]=nil
    end
    
    
    #text
    
      
    if params[:q]
    
      @annonces = @annonces.where("title LIKE ? ", "%"+params[:q].to_s+"%" )

     
    end
    
    if @annonce_cat and @annonce_cat.specific?
      @annonces = @annonces.where(:specific_annonce_type => @annonce_cat.specific).joins(@annonce_cat.specific.tableize.singularize.to_sym)
    end
    
    
    if @annonce_cat and (@annonce_cat.specific == "AnnonceAuto" or @annonce_cat.specific == "AnnonceMoto" or @annonce_cat.specific == "AnnonceUtil")
      
      
      
      if params[:marque_id] and params[:marque_id] != ""
        @annonces = @annonces.where("#{@annonce_cat.specific.tableize}.marque_id = ?",params[:marque_id] )
      
      end
      
      if params[:energie] and params[:energie] != ""
        @annonces = @annonces.where("#{@annonce_cat.specific.tableize}.energie = ?",params[:energie] )
      
      end
      
      if params[:bv] and params[:bv] != ""
        @annonces = @annonces.where("#{@annonce_cat.specific.tableize}.bv = ?",params[:bv] )
      
      end
      
      
    end
    
    if @annonce_cat and (@annonce_cat.specific == "AnnonceAuto" or @annonce_cat.specific == "AnnonceUtil")
      
      if params[:year] and params[:year].size > 3
        
        @date = Date.parse(params[:year]+"/01/01")
        @date = @date.beginning_of_year
        
        @annonces = @annonces.where("#{@annonce_cat.specific.tableize}.year >= ?", @date)
      
      end
      
      if params[:max_year] and params[:max_year].size > 3
        
        @date = Date.parse(params[:max_year]+"/01/01")
        @date = @date.end_of_year
        
        @annonces = @annonces.where("#{@annonce_cat.specific.tableize}.year <= ?", @date)
      
      end
      
      if params[:min_kms] and params[:min_kms] != ""
        

        @annonces = @annonces.where("#{@annonce_cat.specific.tableize}.kms >= ?", params[:min_kms])
      
      end
      
      if params[:max_kms] and params[:max_kms] != ""

        
        @annonces = @annonces.where("#{@annonce_cat.specific.tableize}.kms <= ?", params[:max_kms])
      
      end
      
    end
    
    
    
    if params[:tags]
      
      @annonce_ids = Annonce.joins(:annonce_tag_cats).where('annonce_tag_cats.tag_cat_id IN (?)', params[:tags]).group('annonce_tag_cats.annonce_id').having('count(*)=?', params[:tags].size)
      annonce_ids = []
      @annonce_ids.each do |annonce_id|
        annonce_ids << annonce_id.id
      end
      @annonce_ids = annonce_ids
    
      @annonces = @annonces.where(:id => @annonce_ids)
      
      
    end
    
    
    @annonces = @annonces.page(page).per(per_page).reorder("list_head DESC, created_at DESC").all
    
    @title = "Sideplace, nouveau site d'annonces gratuites"
    
    @description = "Simple, design, efficace, une nouvelle manière de déposer vos annonces. Pour les particuliers et les professionnels, avec programme d'affiliation."
    
  end
  
  
  def geocode
    params[:where] = "#{params[:lat]},#{params[:lng]}"
  end
  
  def index
   
    per_page = (params[:per_page] and params[:per_page] != "") ? params[:per_page] : 10
    
    page = (params[:page] and params[:page] != "") ? params[:page] : 1 
    
    @annonces = Annonce.valid_to_show
    
    @annonces = @annonces.page(page).per(per_page).order("list_head DESC, created_at DESC").all
    
    
    @title = "Sideplace, nouveau site d'annonces gratuites"
    
    @description = "Simple, design, efficace, une nouvelle manière de déposer vos annonces. Pour les particuliers et les professionnels, avec programme d'affiliation."
    
    
    render :layout => "home"
  end


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


  def new
    params[:step] = "info"
    
    @create = true
    @no_search = true
    @annonce = Annonce.new(:annonce_cat_id => params[:annonce_cat_id], :tel_number => current_annonce_account.tel_number)
    
    @annonce.devise_id = session[:devise_id].to_i
    
    if @annonce.annonce_cat_id == 5
      #@annonce.specific_annonce_type = "AnnonceAuto"
      @annonce.specific_annonce = AnnonceAuto.new
    elsif @annonce.annonce_cat_id == 6
      @annonce.specific_annonce = AnnonceMoto.new
    elsif @annonce.annonce_cat_id == 10
      @annonce.specific_annonce = AnnonceUtil.new
    elsif @annonce.annonce_cat_id == 11
      @annonce.specific_annonce = AnnonceCarav.new
    elsif @annonce.annonce_cat_id == 12
      @annonce.specific_annonce = AnnonceNaut.new
    elsif @annonce.annonce_cat_id == 17
      @annonce.specific_annonce = AnnonceHab.new
    elsif @annonce.annonce_cat_id == 19
      @annonce.specific_annonce = AnnonceOffice.new
    elsif @annonce.annonce_cat_id == 32
      @annonce.specific_annonce = AnnonceTel.new
    elsif @annonce.annonce_cat_id == 36
      @annonce.specific_annonce = AnnonceNum.new
    elsif @annonce.annonce_cat_id == 49
      @annonce.specific_annonce = AnnoncePdv.new
    elsif @annonce.annonce_cat_id == 52
      @annonce.specific_annonce = AnnoncePet.new
    elsif @annonce.annonce_cat_id == 35
      @annonce.specific_annonce = AnnonceHigh.new
    elsif @annonce.annonce_cat_id == 34
      @annonce.specific_annonce = AnnoncePlay.new
    elsif @annonce.annonce_cat_id == 33
      @annonce.specific_annonce = AnnonceInf.new
    
    elsif @annonce.annonce_cat_id == 28
      @annonce.specific_annonce = AnnonceGite.new
    elsif @annonce.annonce_cat_id == 29
      @annonce.specific_annonce = AnnonceCamping.new
    elsif @annonce.annonce_cat_id == 30
      @annonce.specific_annonce = AnnonceHotel.new
      
    elsif @annonce.annonce_cat_id == 79
      @annonce.specific_annonce = AnnonceDraw.new
    elsif @annonce.annonce_cat_id == 80
      @annonce.specific_annonce = AnnonceAntiquity.new
    elsif @annonce.annonce_cat_id == 81
      @annonce.specific_annonce = AnnonceGraphic.new
    elsif @annonce.annonce_cat_id == 82
      @annonce.specific_annonce = AnnonceSculpture.new
    
    
    end
    
  end

  def edit
    params[:step] = "info"
    @annonce = current_annonce_account.annonces.find(params[:id])
    @no_search = true
    
    @create = true if params[:create]
  end
  
  def specific
    annonce = current_annonce_account.annonces.find(params[:id])
  
  end


  def photos
    @annonce = current_annonce_account.annonces.find(params[:id])
    params[:step] = "photos"
    @no_search = true
    
    @create = true if params[:create]
  end




  def create
    params[:step] = "info"
    @create = true
    
    specific_annonce_params = params[:annonce].delete(:specific_annonce_attributes)
    content_type = params[:annonce][:specific_annonce_type]
    
  	@annonce = Annonce.new(params.require(:annonce).permit!)
    @annonce.annonce_account = current_annonce_account
    
    if content_type
      specific_annonce = content_type.constantize.new(specific_annonce_params.permit!)
    
      @annonce.specific_annonce =specific_annonce
    
    end
    
    
    
    if @annonce.save
      
      
      #redirect_to photos_public_annonce_path(@annonce)
      

          
  	else
  		render :action => "new" 
  	end
  end

  def confirm
    @annonce = Annonce.find_by_token(params[:id])
    @annonce.enabled = true
    @annonce.save
    
    
    cookies[:annonce_auth_token] = @annonce.token
    
    redirect_to public_my_account_path
    #redirect_to "/"
  end
  def publish
    params[:step] = "publish"
    @annonce = current_annonce_account.annonces.find(params[:id])
    @annonce.published = true
    @annonce.refused = true
    if !@annonce.published_date?
      @annonce.published_date = Date.today
       @annonce.list_head = Time.now
      
      
      
    end
    @annonce.save
    @no_search = true
    
    @create = true if params[:create]
  end
  
  def update
    params[:step] = "info"
    @create = true if params[:create]
    @annonce = current_annonce_account.annonces.find(params[:id])
   
    

    
    respond_to do |format|
      if @annonce.update_attributes(params.require(:annonce).permit!)



        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
  
  def options
    @annonce = current_annonce_account.annonces.find(params[:id])
  end
  
  def buy_option
    @annonce = current_annonce_account.annonces.find(params[:id])
    @annonce_option_type = AnnonceOptionType.find(params[:annonce_option_type_id])
    @annonce_option_log = nil
    
    if current_annonce_account.solde_credits(Date.today) >= @annonce_option_type.cost
      
      if @annonce_option_type.slug == "5-photos" and @annonce.nbr_photos <= 10
        @annonce.nbr_photos = @annonce.nbr_photos + 5
        
        @transaction = true

        
        
      elsif @annonce_option_type.slug == "10-photos" and @annonce.nbr_photos <= 5
        @annonce.nbr_photos = @annonce.nbr_photos + 10
        
        @transaction = true
        
      elsif @annonce_option_type.slug == "list-head"
        @annonce.list_head = Time.now
        
        @transaction = true
        
      elsif @annonce_option_type.slug == "surligne-une-semaine"
        
        if @annonce.highlight_expire? and @annonce.highlight_expire >= Date.today  
          @annonce.highlight_expire = @annonce.highlight_expire + 1.week
        else
          @annonce.highlight_expire = Date.today + 1.week
        end
        
        @annonce.highlight = true
         
        @transaction = true
        
      elsif @annonce_option_type.slug == "surligne-un-mois"

        
        if @annonce.highlight_expire? and @annonce.highlight_expire >= Date.today  
          @annonce.highlight_expire = @annonce.highlight_expire + 1.month
        else
          @annonce.highlight_expire = Date.today + 1.month
        end
        
        @annonce.highlight = true
         
        @transaction = true
        
      
      elsif @annonce_option_type.slug == "urgent-une-semaine"
        
        if @annonce.urgent_expire? and @annonce.urgent_expire >= Date.today  
          @annonce.urgent_expire = @annonce.urgent_expire + 1.week
        else
          @annonce.urgent_expire = Date.today + 1.week
        end
        
        @annonce.urgent = true
         
        @transaction = true
        
      elsif @annonce_option_type.slug == "urgent-un-mois"
        
        if @annonce.urgent_expire? and @annonce.urgent_expire >= Date.today  
          @annonce.urgent_expire = @annonce.urgent_expire + 1.month
        else
          @annonce.urgent_expire = Date.today + 1.month
        end
        
        @annonce.urgent = true
         
        @transaction = true
        
        
    
    
      elsif @annonce_option_type.slug == "big-une-semaine"
        
        if @annonce.big_annonce_expire? and @annonce.big_annonce_expire >= Date.today  
          @annonce.big_annonce_expire = @annonce.big_annonce_expire + 1.week
        else
          @annonce.big_annonce_expire = Date.today + 1.week
        end
        
        @annonce.big_annonce = true
         
        @transaction = true
        
      elsif @annonce_option_type.slug == "big-un-mois"
        
        if @annonce.big_annonce_expire? and @annonce.big_annonce_expire >= Date.today  
          @annonce.big_annonce_expire = @annonce.big_annonce_expire + 1.month
        else
          @annonce.big_annonce_expire = Date.today + 1.month
        end
        
        @annonce.big_annonce = true
         
        @transaction = true
    
        
      elsif @annonce_option_type.slug == "link" 
        @annonce.link = true
      
        @transaction = true
        
      elsif @annonce_option_type.slug == "video" 
        @annonce.video = true
      
        @transaction = true
        
      end
      
      if @transaction == true
        
        @annonce_option_log = AnnonceOptionLog.new(:annonce => @annonce, :annonce_option_type => @annonce_option_type, :cost => @annonce_option_type.cost, :name => @annonce_option_type.name, :periode => @annonce_option_type.periode, :periode_type => @annonce_option_type.periode_type)
        
      
        
      end
      
      
    end
    
  
    
    if @annonce_option_log
      
      @annonce_option_log.save
      
      paid = current_annonce_account.credit_paid @annonce_option_type.cost, @annonce_option_log.id, "AnnonceOptionLog", @annonce_option_log.name
      if paid 
        
        @annonce.save
        
        
        
        if @annonce_option_type.slug == "10-photos" or @annonce_option_type.slug == "5-photos"
          redirect_to edit_public_annonce_path(:anchor => "photos"), :notice => "Votre option a bien été enregistrée, vous pouvez désormais ajotuer les photos supplémentaires"
        elsif @annonce_option_type.slug == "link" 
            redirect_to edit_public_annonce_path(:anchor => "link"), :notice => "Votre option a bien été enregistrée, vous pouvez désormais ajotuer un lien sur votre annonce"
        elsif @annonce_option_type.slug == "video" 
            redirect_to edit_public_annonce_path(:anchor => "video"), :notice => "Votre option a bien été enregistrée, vous pouvez désormais ajotuer une video sur votre annonce"
      
        
        else
          redirect_to public_annonce_path, :notice => "Votre option a bien été enregistrée."
        end
        
        
      else
        redirect_to :back
      end
    
    else
      redirect_to :back
    
    end
  
  end



end
