class CPanelSessionsController < CPanelController

  def login
    if session[:cpanel_user_login_errors].present?
      @errors = session[:cpanel_user_login_errors]
      session.delete(:cpanel_user_login_errors)
    end
  end

  def logout
    destroy_cpanel_session
    redirect_to cpanel_login_path
  end

  def signup
    @cpaneluser = CPanelUser.new
  end

  def create_user
    cpaneluser = CPanelUser.new(c_panel_user_params)
    cpaneluser.first_time_run = false
    cpaneluser.registered = true
    cpaneluser.save
    cpaneluser.generate_confirmation_token
  end

  def confirm_email
    @user = CPanelUser.find(params[:id]) rescue nil
    if !@user.nil?
      CPanelUser.confirm_email(params[:token])
    end
  end

  def requestpassword
  end

  def loguserin
    user = CPanelUser.where(:email => params[:username]).first rescue nil
    if user && user.authenticate(params[:password])
      if user.is_confirmed?
        create_cpanel_session(user)
        redirect_to :sites
      else
        session[:cpanel_user_login_errors] = "User is not confirmed. Please confirm the email before you login."
        redirect_to :cpanel_login
      end
    else
      session[:cpanel_user_login_errors] = "Invalid username or password."
      redirect_to :cpanel_login
    end
  end

  def instructions
    user = CPanelUser.where(:email => params[:email]).first rescue nil
    @user_found = false
    if !user.nil?
      @user_found = true
      user.send_password_reset_email
    end
  end

  def reset_password
    @user_found = CPanelUser.check_password_token(params[:token])
    @user_id = CPanelUser.where(reset_token: params[:token]).first.id rescue nil
  end

  def update_cpanel_user_password
    user = CPanelUser.find(params[:user_id]) rescue nil
    if user.update_password(params[:password], params[:confirmation_password])
      redirect_to :cpanel_login
    else
      redirect_to reset_password_path(:token => user.reset_token, :id => user.id.to_s)
    end
  end

  private

  def c_panel_user_params
    params.require(:c_panel_user).permit!
  end

end