# get '/users' do
# end

get '/users/new' do
  @form = true
  @user = User.new
  erb :'users/new'
end

post '/users/new' do
  @name = params[:name]
  @email = params[:email]
  @birthday = params[:birthday]

  user = User.new(name: @name, email: @email, birthday: Chronic.parse(@birthday), password: params[:password])

  if params[:password].length < 6
    @error = "Password must be at least 6 characters"
    erb :'users/new'
  elsif user.save
    session[:user_id] = user.id
    session[:user_name] = user.name
    redirect "/users/#{user.id}"
  else
    @error = user.errors.full_messages.to_sentence
    erb :'users/new'
  end
end

get '/users/:id/edit' do
  @id = params[:id].to_i
  erb :'users/edit'
end

put '/users/:id/edit' do
  @id = params[:id].to_i
  user = current_user

  user.name = params[:name]
  user.email = params[:email]
  user.birthday = params[:birthday]
  user.password = params[:password]

  if params[:password].length < 6
    @error = "Password must be 6 or more characters"
    erb :'users/edit'
  elsif user.save
    redirect "/users/#{params[:id]}?update=success"
  else
    @error = user.errors.full_messages.to_sentence
    erb :'users/edit'
  end
end

get '/users/:id' do
  @error = params[:error]
  begin
    @user = User.find(params[:id])
  rescue ActiveRecord::RecordNotFound
    status 404
    redirect '/404'
  end
  erb :'users/profile'
end

