# -*- encoding : utf-8 -*-
class Public::CustomersAuthsController < ApplicationController
  layout "public"
  before_filter :get_reseaux
  def new
    @biglogo = true
    @no_search = true
     params[:step] = "login"
    if params[:for_annonce]
      session[:for_annonce] = true

    else
      session[:for_annonce] = nil
    end
    
    
    if params[:p]
      @reseaux = Reseaux.where(:token => params[:p].to_s).first
      if @reseaux
        session[:reseaux_id] = @reseaux.id
          @reseaux_layout = true
          
      end
    end

    @customer = Customer.new()
    if params[:p]
      @customer.reseaux_token = params[:p]
    end
    if cookies[:mlm_token] and @parent = Customer.find_parrain(cookies[:mlm_token])
      @customer.parent_code = @parent.mlm_token.upcase

    elsif params[:p] and @parent = Customer.find_parrain(params[:p])
      @customer.parent_code = @parent.mlm_token.upcase

    end


  end

  def create
    if session[:reseaux_id]
      @reseaux = Reseaux.find(session[:reseaux_id])
      @reseaux_layout = true
    end
      
      
    @biglogo = true
    @customer = Customer.new()
    if cookies[:mlm_token] and @parent = Customer.find_parrain(cookies[:mlm_token])
      @customer.parent_code = @parent.mlm_token.upcase

    elsif params[:p] and @parent = Customer.find_parrain(params[:p])
      @customer.parent_code = @parent.mlm_token.upcase
    end

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


      if params[:remember_me]
        cookies.permanent[:customer_auth_token] = user.token
      else
        cookies[:customer_auth_token] = user.token
      end

      user.last_sign_in_at = Time.now
      user.save(:validate => false)

      if cookies[:video_read] == "true"
        flash[:read_video] = false
      else
        cookies.permanent[:video_read] = "true"
        flash[:read_video] = true
      end
      if false
        if user.reseauxes.map(&:id).include?(2)
        
          redirect_to public_reseaux_products_path(:reseaux_id => 2)
        else
          redirect_to :root
        end
        
      else
        if @reseaux
          redirect_to public_reseaux_products_path(:reseaux_id => @reseaux.id)
        else
          redirect_to public_my_reseauxes_path
        end
      end
    
    else
      flash.now.alert = "Email ou mot de passe incorect"

      render :action => "new"
    end
  end

  def logout
    cookies.delete(:customer_auth_token)
    redirect_to "/", notice: "Déconnecté."
  end
end
