Conditional logic not working correctly