# -*- encoding : utf-8 -*-
class Public::ProductCustomersAuthsController < ApplicationController
  layout "public"

  def new
    
    if params[:r] and params[:r] != ""
      session[:before_auth_url] = nil
    end
    
    @no_search = true
     params[:step] = "login"
    if params[:for_annonce] and params[:for_annonce] != ""
      session[:for_annonce] = true
      
    else
      session[:for_annonce] = nil
      params[:for_annonce] =nil
    end

    @product_customer = ProductCustomer.new()
    if cookies[:mlm_token] and @parent = ProductCustomer.find_parrain(cookies[:mlm_token]) 
      @product_customer.parent_code = @parent.mlm_token.upcase
    
    elsif params[:p] and @parent = ProductCustomer.find_parrain(params[:p]) 
      @product_customer.parent_code = @parent.mlm_token.upcase
      
    end 
    
  end

  

  def create
    params[:for_annonce] =nil if params[:for_annonce] == ""
    params[:for_mail] =nil if params[:for_mail] == ""
    @product_customer = ProductCustomer.new()
    

    params[:step] = "login"
    @no_search = true
    user = ProductCustomer.find_by_email(params[:email])
    if user && user.authenticate(params[:password])
      #session[:forum_user_id] = user.id


      if params[:remember_me]
        cookies.permanent[:product_customer_auth_token] = user.token
      else
        cookies[:product_customer_auth_token] = user.token
      end
      user.last_sign_in_at = Time.now
      user.last_sign_in_ip = user.current_sign_in_ip
      user.current_sign_in_ip = request.remote_ip 
      
      user.save(:validate => false)



        if session[:for_annonce]
          session[:for_annonce] = nil
          redirect_to new_public_annonce_path
        elsif session[:before_auth_url]
          url = session[:before_auth_url]
          session[:before_auth_url] = nil
          redirect_to url
        else
          redirect_to public_my_account_path
        end



    else
      flash.now.alert = "Email ou mot de passe incorect"
      render "new"
    end
  end

  def logout
    cookies.delete(:product_customer_auth_token)
    session[:before_auth_url] = nil
    redirect_to "/", notice: "Déconnecté."
  end
end
